repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
jeremyrea/tekky | Tekky/RequestManager.swift | 1 | 1118 | //
// RequestManager.swift
// Tekky
//
// Created by Jeremy Rea on 2017-03-17.
// Copyright © 2017 Jeremy Rea. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
class RequestManager {
static let sharedInstance: RequestManager = {
let sharedInstance = RequestManager()
return sharedInstance
}()
private let SERVER = "https://api.teksavvy.com/web/Usage/UsageSummaryRecords"
func getUsage(withKey apiKey: String, completionHandler: @escaping ([UsageSummaryRecord]?) -> ()) {
let headers: HTTPHeaders = [
"TekSavvy-APIKey": apiKey,
]
Alamofire.request(SERVER, method: .get, headers: headers).responseJSON { response in
switch response.result {
case .success(let value):
let json = JSON(value)
guard let values = json.dictionaryValue["value"]?.arrayValue else {
return
}
let usageSummaryRecords = values.map() {
UsageSummaryRecord(withValues: $0)
}
completionHandler(usageSummaryRecords)
case .failure(let error):
print(error)
}
}
}
}
| mit | 277476db02b5035d448fcb03167539d5 | 23.822222 | 101 | 0.65085 | 4.346304 | false | false | false | false |
LoveZYForever/HXWeiboPhotoPicker | Pods/HXPHPicker/Sources/HXPHPicker/Picker/Extension/Picker+UIImageView.swift | 1 | 9809 | //
// Picker+UIImageView.swift
// HXPHPicker
//
// Created by Slience on 2021/5/26.
//
import UIKit
import AVKit
#if canImport(Kingfisher)
import Kingfisher
#endif
extension UIImageView {
#if canImport(Kingfisher)
@discardableResult
func setImage(
for asset: PhotoAsset,
urlType: DonwloadURLType,
indicatorColor: UIColor? = nil,
progressBlock: DownloadProgressBlock? = nil,
downloadTask: ((Kingfisher.DownloadTask?) -> Void)? = nil,
completionHandler: ImageView.ImageCompletion? = nil
) -> Any? {
#if HXPICKER_ENABLE_EDITOR
if asset.photoEdit != nil || asset.videoEdit != nil {
getEditedImage(asset, urlType: urlType, completionHandler: completionHandler)
return nil
}
#endif
let isThumbnail = urlType == .thumbnail
if isThumbnail {
kf.indicatorType = .activity
if let color = indicatorColor {
(kf.indicator?.view as? UIActivityIndicatorView)?.color = color
}
}
var url = URL(string: "")
var placeholderImage: UIImage?
var options: KingfisherOptionsInfo = []
var loadVideoCover: Bool = false
if let imageAsset = asset.networkImageAsset {
url = isThumbnail ? imageAsset.thumbnailURL : imageAsset.originalURL
placeholderImage = UIImage.image(for: imageAsset.placeholder)
let processor = DownsamplingImageProcessor(size: imageAsset.thumbnailSize)
options = isThumbnail ?
[.onlyLoadFirstFrame, .processor(processor), .cacheOriginalImage] :
[]
}else if let videoAsset = asset.networkVideoAsset {
if let coverImage = videoAsset.coverImage {
image = coverImage
completionHandler?(coverImage, nil, asset)
return nil
}else if let coverImageURL = videoAsset.coverImageURL {
url = coverImageURL
options = []
}else {
let key = videoAsset.videoURL.absoluteString
var videoURL: URL
if PhotoTools.isCached(forVideo: key) {
videoURL = PhotoTools.getVideoCacheURL(for: key)
}else {
videoURL = videoAsset.videoURL
}
loadVideoCover = true
url = videoURL
}
}else if let videoAsset = asset.localVideoAsset {
if let coverImage = videoAsset.image {
image = coverImage
completionHandler?(coverImage, nil, asset)
return nil
}
loadVideoCover = true
url = videoAsset.videoURL
}
if let url = url, loadVideoCover {
let provider = AVAssetImageDataProvider(assetURL: url, seconds: 0.1)
provider.assetImageGenerator.appliesPreferredTrackTransform = true
let task = KF.dataProvider(provider)
.onSuccess { (result) in
let image = result.image
let videoSize: CGSize?
if asset.isNetworkAsset {
videoSize = asset.networkVideoAsset?.videoSize
}else {
videoSize = asset.localVideoAsset?.videoSize
}
if let videoSize = videoSize, videoSize.equalTo(.zero) {
asset.localVideoAsset?.videoSize = image.size
asset.networkVideoAsset?.videoSize = image.size
}
completionHandler?(image, nil, asset)
}
.onFailure { (error) in
completionHandler?(nil, error, asset)
}
.set(to: self)
return task
}
return kf.setImage(
with: url,
placeholder: placeholderImage,
options: options,
progressBlock: progressBlock
) { (result) in
switch result {
case .success(let value):
switch asset.mediaSubType {
case .networkImage(_):
if asset.localImageAsset == nil {
let localImageAsset = LocalImageAsset(image: value.image)
asset.localImageAsset = localImageAsset
}
asset.networkImageAsset?.imageSize = value.image.size
if asset.localImageType != .original && !isThumbnail {
if let imageData = value.image.kf.data(format: asset.mediaSubType.isGif ? .GIF : .unknown) {
asset.networkImageAsset?.fileSize = imageData.count
}
asset.localImageType = urlType
}
case .networkVideo:
asset.networkVideoAsset?.coverImage = value.image
asset.networkVideoAsset?.videoSize = value.image.size
default: break
}
completionHandler?(value.image, nil, asset)
case .failure(let error):
completionHandler?(nil, error, asset)
}
}
}
#if HXPICKER_ENABLE_EDITOR
private func getEditedImage(
_ photoAsset: PhotoAsset,
urlType: DonwloadURLType,
completionHandler: ImageView.ImageCompletion?
) {
if let photoEdit = photoAsset.photoEdit {
if urlType == .thumbnail {
image = photoEdit.editedImage
completionHandler?(photoEdit.editedImage, nil, photoAsset)
}else {
do {
let imageData = try Data(contentsOf: photoEdit.editedImageURL)
let img = DefaultImageProcessor.default.process(item: .data(imageData), options: .init([]))!
let kfView = self as? AnimatedImageView
kfView?.image = img
}catch {
image = photoEdit.editedImage
}
completionHandler?(photoEdit.editedImage, nil, photoAsset)
}
}else if let videoEdit = photoAsset.videoEdit {
image = videoEdit.coverImage
completionHandler?(videoEdit.coverImage, nil, photoAsset)
}
}
#endif
#else
@discardableResult
func setVideoCoverImage(
for asset: PhotoAsset,
imageGenerator: ((AVAssetImageGenerator) -> Void)? = nil,
completionHandler: ((UIImage?, PhotoAsset) -> Void)? = nil
) -> Any? {
#if HXPICKER_ENABLE_EDITOR
if let videoEdit = asset.videoEdit {
completionHandler?(videoEdit.coverImage, asset)
return nil
}
#endif
var videoURL: URL?
if let videoAsset = asset.networkVideoAsset {
if let coverImage = videoAsset.coverImage {
if videoAsset.videoSize.equalTo(.zero) {
asset.networkVideoAsset?.videoSize = coverImage.size
}
completionHandler?(coverImage, asset)
return nil
}else {
let key = videoAsset.videoURL.absoluteString
if PhotoTools.isCached(forVideo: key) {
videoURL = PhotoTools.getVideoCacheURL(for: key)
}else {
videoURL = videoAsset.videoURL
}
}
}else if let videoAsset = asset.localVideoAsset {
if let coverImage = videoAsset.image {
if videoAsset.videoSize.equalTo(.zero) {
asset.localVideoAsset?.videoSize = coverImage.size
}
completionHandler?(coverImage, asset)
return nil
}
videoURL = videoAsset.videoURL
}else {
completionHandler?(nil, asset)
return nil
}
return PhotoTools.getVideoThumbnailImage(
url: videoURL!,
atTime: 0.1,
imageGenerator: imageGenerator
) { videoURL, image, result in
if let image = image {
if asset.isNetworkAsset {
asset.networkVideoAsset?.videoSize = image.size
asset.networkVideoAsset?.coverImage = image
}else {
asset.localVideoAsset?.videoSize = image.size
asset.localVideoAsset?.image = image
}
}
if result == .cancelled { return }
completionHandler?(image, asset)
}
}
#endif
}
extension ImageView {
#if canImport(Kingfisher)
typealias ImageCompletion = (UIImage?, KingfisherError?, PhotoAsset) -> Void
@discardableResult
func setImage(
for asset: PhotoAsset,
urlType: DonwloadURLType,
progressBlock: DownloadProgressBlock? = nil,
downloadTask: ((Kingfisher.DownloadTask?) -> Void)? = nil,
completionHandler: ImageCompletion? = nil
) -> Any? {
imageView.setImage(
for: asset,
urlType: urlType,
progressBlock: progressBlock,
downloadTask: downloadTask,
completionHandler: completionHandler
)
}
#else
@discardableResult
func setVideoCoverImage(
for asset: PhotoAsset,
imageGenerator: ((AVAssetImageGenerator) -> Void)? = nil,
completionHandler: ((UIImage?, PhotoAsset) -> Void)? = nil
) -> Any? {
imageView.setVideoCoverImage(
for: asset,
imageGenerator: imageGenerator,
completionHandler: completionHandler
)
}
#endif
}
| mit | b948c646ba46f2a60e65bb60f0af0ebc | 36.872587 | 116 | 0.541442 | 5.842168 | false | false | false | false |
bogosmer/UnitKit | Example/UnitKit Example/DetailViewController.swift | 1 | 1890 | //
// DetailViewController.swift
// UnitKit Example
//
// Created by Bo Gosmer on 15/02/2016.
// Copyright © 2016 Deadlock Baby. All rights reserved.
//
import UIKit
class DetailViewController: UITableViewController {
var options: [String]? = nil
var completion: (String -> ())?
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return options?.count ?? 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let somethingsWrong = "Wrong!"
if let unwrappedOptions = options {
cell.textLabel?.text = indexPath.row < unwrappedOptions.count ? unwrappedOptions[indexPath.row] : somethingsWrong
} else {
cell.textLabel?.text = somethingsWrong
}
return cell
}
// MARK: - Delegate
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
navigationController?.popViewControllerAnimated(true)
guard let unwrappedCompletion = completion, unwrappedOptions = options else {
return
}
if indexPath.row < unwrappedOptions.count {
unwrappedCompletion(unwrappedOptions[indexPath.row])
}
}
// 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?) {
print("going back")
}
}
| mit | 9b83b483d5179548a1d1ceed86cdce00 | 28.984127 | 125 | 0.667549 | 5.30618 | false | false | false | false |
kuznetsovVladislav/KVSpinnerView | KVSpinnerView/Layers/RectangleLayer.swift | 1 | 3623 | //
// RectangleLayer.swift
// CALayer
//
// Created by Владислав on 31.01.17.
// Copyright © 2017 Владислав . All rights reserved.
//
import UIKit
class RectangleLayer: CAShapeLayer {
var statusMessage: String? {
didSet {
updateLayers()
}
}
fileprivate let rectSide = KVSpinnerView.settings.spinnerRadius + 80
fileprivate var bezierPath: UIBezierPath {
return UIBezierPath(roundedRect: CGRect.init(x: -rectSide / 2,
y: -rectSide / 2,
width: rectSide,
height: rectSide), cornerRadius: rectSide / 5)
}
fileprivate func bezierPathWithStatus(width: CGFloat, height: CGFloat) -> UIBezierPath {
return UIBezierPath(roundedRect: CGRect.init(x: width > rectSide ? -(width / 2 + 10) : -rectSide / 2 - 10,
y: -rectSide / 2,
width: width > rectSide ? width + 20 : rectSide + 20,
height: rectSide + height),
cornerRadius: rectSide / 5)
}
fileprivate func setup() {
path = bezierPath.cgPath
fillColor = KVSpinnerView.settings.backgroundRectColor.cgColor
}
//TODO: - Perhapse need to extend font in settings
fileprivate func updateLayers() {
if let message = statusMessage {
sublayers?.removeAll()
let font = UIFont.systemFont(ofSize: 16.0)
var isTextWrapped = false
let messageString = message as NSString
var messageWidth = messageString.size(attributes: [NSFontAttributeName : font]).width
if messageWidth > 200 {
isTextWrapped = true
messageWidth = 200
}
let attributes = [NSFontAttributeName : font]
let attributedString = NSAttributedString(string: message,
attributes: attributes)
let rect = attributedString.boundingRect(
with: CGSize.init(width: 200, height: 10000),
options: [.usesLineFragmentOrigin, .usesFontLeading],
context: nil)
let messageHeight = rect.size.height
path = bezierPathWithStatus(width: messageWidth, height: messageHeight).cgPath
let statusLayer = StatusTitleLayer(message: message,
frame: CGRect(
x: bounds.midX - max(messageWidth, rectSide) / 2,
y: KVSpinnerView.settings.spinnerRadius,
width: max(messageWidth, rectSide),
height: isTextWrapped ? messageHeight : 25))
let radius = KVSpinnerView.settings.spinnerRadius
// let layerPosition = CGPoint(x: bounds.midX, y: radius + frame.size.height)
// statusLayer.position = layerPosition
addSublayer(statusLayer)
} else {
path = bezierPath.cgPath
sublayers?.removeAll()
}
}
override init() {
super.init()
setup()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | fcf96854c0e34c9c82ce1e68a9a5b383 | 38.173913 | 114 | 0.504162 | 5.831715 | false | false | false | false |
WestlakeAPC/game-off-2016 | external/Fiber2D/Fiber2D/PhysicsJoint.swift | 1 | 2781 | //
// PhysicsJoint.swift
// Fiber2D
//
// Created by Andrey Volodin on 18.09.16.
// Copyright © 2016 s1ddok. All rights reserved.
//
/**
* @brief An PhysicsJoint object connects two physics bodies together.
*/
public class PhysicsJoint: Tagged {
/**
* Get this joint's tag.
*
* @return An integer number.
*/
public var tag: Int = 0
/**Get the physics world.*/
internal(set) weak public var world: PhysicsWorld?
/**Get physics body a connected to this joint.*/
internal(set) weak public var bodyA: PhysicsBody?
/**Get physics body a connected to this joint.*/
internal(set) weak public var bodyB: PhysicsBody?
/** Determines if the collision is enabled. */
public var collisionEnabled = true
/** Determines if the joint is enable. */
public var enabled = true {
didSet {
guard let world = self.world else {
return
}
if enabled != oldValue {
if enabled {
world.add(joint: self)
} else {
world.remove(joint: self)
}
}
}
}
/** Set the max force between two bodies. */
public var maxForce = Float.infinity {
didSet {
for cpc in chipmunkConstraints {
cpConstraintSetMaxForce(cpc, cpFloat(maxForce))
}
}
}
init(bodyA: PhysicsBody, bodyB: PhysicsBody) {
guard bodyA !== bodyB else {
fatalError("Bodies can't be joined to itself")
}
self.bodyA = bodyA
self.bodyB = bodyB
bodyA.joints.append(self)
bodyB.joints.append(self)
}
// MARK: Internal vars
private var chipmunkInitialized = false
internal var chipmunkConstraints = [UnsafeMutablePointer<cpConstraint>]()
internal func createConstraints() {}
internal func chipmunkInitJoint() -> Bool {
guard !chipmunkInitialized else {
return chipmunkInitialized
}
createConstraints()
for subjoint in chipmunkConstraints {
cpConstraintSetMaxForce(subjoint, cpFloat(maxForce));
cpConstraintSetErrorBias(subjoint, cpFloat(pow(1.0 - 0.15, 60.0)));
cpSpaceAddConstraint(world!.chipmunkSpace, subjoint);
}
chipmunkInitialized = true
return chipmunkInitialized
}
deinit {
collisionEnabled = false
for cpc in chipmunkConstraints {
cpConstraintFree(cpc)
}
}
}
public extension PhysicsJoint {
/** Remove the joint from the world. */
public func removeFormWorld() { world?.remove(joint: self) }
}
| apache-2.0 | 7259e490cafb0d28c091e64b598dc08b | 26.8 | 79 | 0.570144 | 4.776632 | false | false | false | false |
gavrix/ImageViewModel | Carthage/Checkouts/ReactiveSwift/Tests/ReactiveSwiftTests/SignalProducerNimbleMatchers.swift | 4 | 1489 | //
// SignalProducerNimbleMatchers.swift
// ReactiveSwift
//
// Created by Javier Soto on 1/25/15.
// Copyright (c) 2015 GitHub. All rights reserved.
//
import Foundation
import ReactiveSwift
import Nimble
public func sendValue<T: Equatable, E: Equatable>(_ value: T?, sendError: E?, complete: Bool) -> NonNilMatcherFunc<SignalProducer<T, E>> {
return sendValues(value.map { [$0] } ?? [], sendError: sendError, complete: complete)
}
public func sendValues<T: Equatable, E: Equatable>(_ values: [T], sendError maybeSendError: E?, complete: Bool) -> NonNilMatcherFunc<SignalProducer<T, E>> {
return NonNilMatcherFunc { actualExpression, failureMessage in
precondition(maybeSendError == nil || !complete, "Signals can't both send an error and complete")
failureMessage.postfixMessage = "Send values \(values). Send error \(maybeSendError). Complete: \(complete)"
let maybeProducer = try actualExpression.evaluate()
if let signalProducer = maybeProducer {
var sentValues: [T] = []
var sentError: E?
var signalCompleted = false
signalProducer.start { event in
switch event {
case let .value(value):
sentValues.append(value)
case .completed:
signalCompleted = true
case let .failed(error):
sentError = error
default:
break
}
}
if sentValues != values {
return false
}
if sentError != maybeSendError {
return false
}
return signalCompleted == complete
}
else {
return false
}
}
}
| mit | cb335a63eabc2e51c7cad402b5e8a318 | 25.122807 | 156 | 0.690396 | 3.857513 | false | false | false | false |
AlvinL33/TownHunt | TownHunt/TownHunt/BorderedButton.swift | 1 | 645 | //
// RoundedButton.swift
// TownHunt
//
// Created by Alvin Lee on 7/27/16.
// Copyright © 2016 LeeTech. All rights reserved.
//
import UIKit
class BorderedButton: UIButton {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
layer.cornerRadius = 5.0
layer.shadowColor = UIColor.black.cgColor
layer.shadowOpacity = 1
layer.shadowRadius = 10
clipsToBounds = true
contentEdgeInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
setTitleColor(tintColor, for: UIControlState())
setTitleColor(UIColor.white, for: .highlighted)
}
}
| apache-2.0 | 8c0ed2d60ae84826443c2123a47e769d | 25.833333 | 78 | 0.647516 | 4.181818 | false | false | false | false |
jeffreybergier/WaterMe2 | WaterMe/Frameworks/Datum/Datum/ModelHelpers/Reminder+Helpers.swift | 1 | 3937 | //
// Reminder+Helpers.swift
// Datum
//
// Created by Jeffrey Bergier on 2020/05/15.
// Copyright © 2020 Saturday Apps.
//
// This file is part of WaterMe. Simple Plant Watering Reminders for iOS.
//
// WaterMe is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// WaterMe is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with WaterMe. If not, see <http://www.gnu.org/licenses/>.
//
import Calculate
// MARK: Core Data
extension CD_Reminder {
internal var kind: ReminderKind {
get {
return .init(rawValue: (self.kindString, self.descriptionString))
}
set {
let raw = newValue.rawValue
self.kindString = raw.primary
raw.secondary.map { self.descriptionString = $0 }
}
}
}
extension CD_Reminder: ModelCompleteCheckable {
internal var isModelComplete: ModelCompleteError? {
switch self.kind {
case .fertilize, .water, .trim, .mist:
return nil
case .move(let description):
return description?.nonEmptyString == nil ?
ModelCompleteError(_actions: [.reminderMissingMoveLocation, .cancel, .saveAnyway])
: nil
case .other(let description):
return description?.nonEmptyString == nil ?
ModelCompleteError(_actions: [.reminderMissingOtherDescription, .cancel, .saveAnyway])
: nil
}
}
}
// MARK: Realm
extension RLM_Reminder {
internal var vessel: RLM_ReminderVessel? { return self.vessels.first }
internal var kind: ReminderKind {
get {
return .init(rawValue: (self.kindString, self.descriptionString))
}
set {
let raw = newValue.rawValue
self.kindString = raw.primary
raw.secondary.map { self.descriptionString = $0 }
}
}
internal func recalculateNextPerformDate(comparisonPerform: RLM_ReminderPerform? = nil) {
if let lastPerform = comparisonPerform ?? self.performed.last {
self.nextPerformDate = lastPerform.date + TimeInterval(self.interval * 24 * 60 * 60)
} else {
self.nextPerformDate = nil
}
}
}
extension RLM_Reminder: ModelCompleteCheckable {
internal var isModelComplete: ModelCompleteError? {
switch self.kind {
case .fertilize, .water, .trim, .mist:
return nil
case .move(let description):
return description?.nonEmptyString == nil ?
ModelCompleteError(_actions: [.reminderMissingMoveLocation, .cancel, .saveAnyway])
: nil
case .other(let description):
return description?.nonEmptyString == nil ?
ModelCompleteError(_actions: [.reminderMissingOtherDescription, .cancel, .saveAnyway])
: nil
}
}
}
public enum ReminderSection: Int, CaseIterable {
case late, today, tomorrow, thisWeek, later
var dateInterval: DateInterval {
switch self {
case .late:
return ReminderDateCalculator.late()
case .today:
return ReminderDateCalculator.today()
case .tomorrow:
return ReminderDateCalculator.tomorrow()
case .thisWeek:
return ReminderDateCalculator.thisWeek()
case .later:
return ReminderDateCalculator.later()
}
}
}
public enum ReminderSortOrder {
case nextPerformDate, interval, kind, note
}
| gpl-3.0 | 1e9454f42e5cc1cdcf07d4f82547e1dc | 32.07563 | 102 | 0.629827 | 4.625147 | false | false | false | false |
elliottminns/blackfish | Sources/Blackfire/RequestHandler.swift | 2 | 1080 | //
// RequestHandler.swift
// Blackfire
//
// Created by Elliott Minns on 20/01/2017.
//
//
import Foundation
struct RequestHandler {
let nodes: [Node]
init(nodes: [Node]) {
self.nodes = nodes
}
func handle(request: HTTPRequest, response: HTTPResponse) {
let handlers = nodes.last?.handlers[request.method] ?? []
guard handlers.count > 0 else {
response.send(status: 404)
return
}
/*
let comps = request.path.components(separatedBy: "/")
let params = self.nodes.reduce((0, [:])) { (result, node) -> (Int, [String: String]) in
if !node.path.isEmpty && node.path[node.path.startIndex] == ":" {
let key = node.path.substring(from: node.path.index(after: node.path.startIndex))
let value = comps[result.0]
return (result.0 + 1, [key: value])
} else {
return (result.0 + 1, result.1)
}
}.1
*/
let params: [String: String] = [:]
let request = Request(params: params, raw: request)
handlers.forEach { handler in
handler(request, response)
}
}
}
| apache-2.0 | 859bf2bafff6aa152bb891d2106c872b | 24.116279 | 91 | 0.597222 | 3.552632 | false | false | false | false |
sora0077/LayoutKit | LayoutKitDemo/TextRow.swift | 1 | 1363 | //
// TextRow.swift
// LayoutKit
//
// Created by 林 達也 on 2015/01/12.
// Copyright (c) 2015年 林 達也. All rights reserved.
//
import UIKit
import LayoutKit
protocol TextRowRendererAcceptable: TableElementRendererProtocol {
weak var titleLabel: UILabel! { get }
}
class TextRow<T: UITableViewCell where T: TextRowRendererAcceptable>: TableRow<T> {
var title: String {
willSet {
self.renderer?.titleLabel.text = newValue
}
}
init(title: String) {
self.title = title
super.init()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// println(("viewDidAppear", self.renderer))
self.renderer?.titleLabel.text = self.title
}
override func viewWillDisappear() {
super.viewWillDisappear()
println(("viewWillDisappear", self.renderer))
}
override func viewDidDisappear() {
super.viewDidDisappear()
// println(("viewDidDisappear", self.renderer))
}
override func didSelect() {
super.didSelect()
// self.size.height = 100
// self.replace()
let row = TextRow<ColoredTextTableViewCell>(title: "replaced \(self.title)")
row.size.height = 60
// row.size.height = self.renderer!.frame.height * 1.1
self.replace(to: row)
}
}
| mit | e165d7dca48f5f9bc17db30654096b0d | 21.114754 | 84 | 0.623425 | 4.337621 | false | false | false | false |
sekouperry/news-pro | codecanyon-11884937-wp-news-pro/Code_Documentation/Code/WPNews2/WPNews2/ISFrostedSidebar.swift | 1 | 17956 | //
// ISFrostedSidebar.swift
//
import UIKit
import QuartzCore
public protocol ISFrostedSidebarDelegate{
func sidebar(sidebar: ISFrostedSidebar, willShowOnScreenAnimated animated: Bool)
func sidebar(sidebar: ISFrostedSidebar, didShowOnScreenAnimated animated: Bool)
func sidebar(sidebar: ISFrostedSidebar, willDismissFromScreenAnimated animated: Bool)
func sidebar(sidebar: ISFrostedSidebar, didDismissFromScreenAnimated animated: Bool)
func sidebar(sidebar: ISFrostedSidebar, didTapItemAtIndex index: Int)
func sidebar(sidebar: ISFrostedSidebar, didEnable itemEnabled: Bool, itemAtIndex index: Int)
}
var sharedSidebar: ISFrostedSidebar?
public class ISFrostedSidebar: UIViewController {
public var width: CGFloat = 110.0
public var showFromRight: Bool = false
public var animationDuration: CGFloat = 0.25
public var itemSize: CGSize = CGSize(width: 80.0, height: 80.0)
public var tintColor: UIColor = UIColor(white: 0.2, alpha: 0.73)
public var itemBackgroundColor: UIColor = UIColor(white: 1, alpha: 0.25)
public var borderWidth: CGFloat = 1
public var delegate: ISFrostedSidebarDelegate? = nil
public var actionForIndex: [Int : ()->()] = [:]
public var selectedIndices: NSMutableIndexSet = NSMutableIndexSet()
public var isSingleSelect: Bool = false{
didSet{
if isSingleSelect{ calloutsAlwaysSelected = false }
}
}
public var calloutsAlwaysSelected: Bool = false{
didSet{
if calloutsAlwaysSelected{
isSingleSelect = false
selectedIndices = NSMutableIndexSet(indexesInRange: NSRange(location: 0,length: images.count) )
}
}
}
private var contentView: UIScrollView = UIScrollView()
private var blurView: UIVisualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .Light))
private var dimView: UIView = UIView()
private var tapGesture: UITapGestureRecognizer? = nil
private var images: [UIImage] = []
private var borderColors: [UIColor]? = nil
private var itemViews: [CalloutItem] = []
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public init(itemImages: [UIImage], colors: [UIColor]?, selectedItemIndices: NSIndexSet?){
contentView.alwaysBounceHorizontal = false
contentView.alwaysBounceVertical = true
contentView.bounces = true
contentView.clipsToBounds = false
contentView.showsHorizontalScrollIndicator = false
contentView.showsVerticalScrollIndicator = false
if colors != nil{
assert(itemImages.count == colors!.count, "If item color are supplied, the itemImages and colors arrays must be of the same size.")
}
selectedIndices = selectedItemIndices != nil ? NSMutableIndexSet(indexSet: selectedItemIndices!) : NSMutableIndexSet()
borderColors = colors
images = itemImages
for (index, image) in enumerate(images){
let view = CalloutItem(index: index)
view.clipsToBounds = true
view.imageView.image = image
contentView.addSubview(view)
itemViews += [view]
if borderColors != nil{
if selectedIndices.containsIndex(index){
let color = borderColors![index]
view.layer.borderColor = color.CGColor
}
} else{
view.layer.borderColor = UIColor.clearColor().CGColor
}
}
super.init(nibName: nil, bundle: nil)
}
public override func loadView() {
super.loadView()
view.backgroundColor = UIColor.clearColor()
view.addSubview(dimView)
view.addSubview(blurView)
view.addSubview(contentView)
tapGesture = UITapGestureRecognizer(target: self, action: "handleTap:")
view.addGestureRecognizer(tapGesture!)
}
public override func shouldAutorotate() -> Bool {
return true
}
public override func supportedInterfaceOrientations() -> Int {
return Int(UIInterfaceOrientationMask.All.rawValue)
}
public override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
if isViewLoaded(){
dismissAnimated(false, completion: nil)
}
}
public func showInViewController(viewController: UIViewController, animated: Bool){
if let bar = sharedSidebar{
bar.dismissAnimated(false, completion: nil)
}
delegate?.sidebar(self, willShowOnScreenAnimated: animated)
sharedSidebar = self
addToParentViewController(viewController, callingAppearanceMethods: true)
view.frame = viewController.view.bounds
dimView.backgroundColor = UIColor.blackColor()
dimView.alpha = 0
dimView.frame = view.bounds
let parentWidth = view.bounds.size.width
var contentFrame = view.bounds
contentFrame.origin.x = showFromRight ? parentWidth : -width
contentFrame.size.width = width
contentView.frame = contentFrame
contentView.contentOffset = CGPoint(x: 0, y: 0)
layoutItems()
var blurFrame = CGRect(x: showFromRight ? view.bounds.size.width : 0, y: 0, width: 0, height: view.bounds.size.height)
blurView.frame = blurFrame
blurView.contentMode = showFromRight ? UIViewContentMode.TopRight : UIViewContentMode.TopLeft
blurView.clipsToBounds = true
view.insertSubview(blurView, belowSubview: contentView)
contentFrame.origin.x = showFromRight ? parentWidth - width : 0
blurFrame.origin.x = contentFrame.origin.x
blurFrame.size.width = width
let animations: () -> () = {
self.contentView.frame = contentFrame
self.blurView.frame = blurFrame
self.dimView.alpha = 0.25
}
let completion: (Bool) -> Void = { finished in
if finished{
self.delegate?.sidebar(self, didShowOnScreenAnimated: animated)
}
}
if animated{
UIView.animateWithDuration(NSTimeInterval(animationDuration), delay: 0, options: UIViewAnimationOptions.allZeros, animations: animations, completion: completion)
} else{
animations()
completion(true)
}
for (index, item) in enumerate(itemViews){
item.layer.transform = CATransform3DMakeScale(0.3, 0.3, 1)
item.alpha = 0
item.originalBackgroundColor = itemBackgroundColor
item.layer.borderWidth = borderWidth
animateSpringWithView(item, idx: index, initDelay: animationDuration)
}
}
public func dismissAnimated(animated: Bool, completion: ((Bool) -> Void)?){
let completionBlock: (Bool) -> Void = {finished in
self.removeFromParentViewControllerCallingAppearanceMethods(true)
self.delegate?.sidebar(self, didDismissFromScreenAnimated: true)
self.layoutItems()
if completion != nil{
completion!(finished)
}
}
delegate?.sidebar(self, willDismissFromScreenAnimated: animated)
if animated{
let parentWidth = view.bounds.size.width
var contentFrame = contentView.frame
contentFrame.origin.x = showFromRight ? parentWidth : -width
var blurFrame = blurView.frame
blurFrame.origin.x = showFromRight ? parentWidth : 0
blurFrame.size.width = 0
UIView.animateWithDuration(NSTimeInterval(animationDuration), delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState, animations: {
self.contentView.frame = contentFrame
self.blurView.frame = blurFrame
self.dimView.alpha = 0
}, completion: completionBlock)
} else{
completionBlock(true)
}
}
//MARK: Private Classes
private class CalloutItem: UIView{
var imageView: UIImageView = UIImageView()
var itemIndex: Int
var originalBackgroundColor:UIColor? {
didSet{
self.backgroundColor = originalBackgroundColor
}
}
required init(coder aDecoder: NSCoder) {
self.itemIndex = 0
super.init(coder: aDecoder)
}
init(index: Int){
imageView.backgroundColor = UIColor.clearColor()
imageView.contentMode = UIViewContentMode.ScaleAspectFit
itemIndex = index
super.init(frame: CGRect.zeroRect)
addSubview(imageView)
}
override func layoutSubviews() {
super.layoutSubviews()
let inset: CGFloat = bounds.size.height/2
imageView.frame = CGRect(x: 0, y: 0, width: inset, height: inset)
imageView.center = CGPoint(x: inset, y: inset)
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
super.touchesBegan(touches, withEvent: event)
var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0
let darkenFactor: CGFloat = 0.3
var darkerColor: UIColor
if originalBackgroundColor != nil && originalBackgroundColor!.getRed(&r, green: &g, blue: &b, alpha: &a){
darkerColor = UIColor(red: max(r - darkenFactor, 0), green: max(g - darkenFactor, 0), blue: max(b - darkenFactor, 0), alpha: a)
} else if originalBackgroundColor != nil && originalBackgroundColor!.getWhite(&r, alpha: &a){
darkerColor = UIColor(white: max(r - darkenFactor, 0), alpha: a)
} else{
darkerColor = UIColor.clearColor()
assert(false, "Item color should be RBG of White/Alpha in order to darken the button")
}
backgroundColor = darkerColor
}
override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
super.touchesEnded(touches, withEvent: event)
backgroundColor = originalBackgroundColor
}
override func touchesCancelled(touches: Set<NSObject>, withEvent event: UIEvent!) {
super.touchesCancelled(touches, withEvent: event)
backgroundColor = originalBackgroundColor
}
}
//MARK: Private Methods
private func animateSpringWithView(view: CalloutItem, idx: Int, initDelay: CGFloat){
let delay: NSTimeInterval = NSTimeInterval(initDelay) + NSTimeInterval(idx) * 0.1
UIView.animateWithDuration(0.5,
delay: delay,
usingSpringWithDamping: 10.0,
initialSpringVelocity: 50.0,
options: UIViewAnimationOptions.BeginFromCurrentState,
animations: {
view.layer.transform = CATransform3DIdentity
view.alpha = 1
},
completion: nil)
}
@objc private func handleTap(recognizer: UITapGestureRecognizer){
let location = recognizer.locationInView(view)
if !CGRectContainsPoint(contentView.frame, location){
dismissAnimated(true, completion: nil)
} else{
let tapIndex = indexOfTap(recognizer.locationInView(contentView))
if tapIndex != nil{
didTapItemAtIndex(tapIndex!)
}
}
}
private func didTapItemAtIndex(index: Int){
let didEnable = !selectedIndices.containsIndex(index)
if borderColors != nil{
let stroke = borderColors![index]
let item = itemViews[index]
if didEnable{
if isSingleSelect{
selectedIndices.removeAllIndexes()
for (index, item) in enumerate(itemViews){
item.layer.borderColor = UIColor.clearColor().CGColor
}
}
item.layer.borderColor = stroke.CGColor
var borderAnimation = CABasicAnimation(keyPath: "borderColor")
borderAnimation.fromValue = UIColor.clearColor().CGColor
borderAnimation.toValue = stroke.CGColor
borderAnimation.duration = 0.5
item.layer.addAnimation(borderAnimation, forKey: nil)
selectedIndices.addIndex(index)
} else{
if !isSingleSelect{
if !calloutsAlwaysSelected{
item.layer.borderColor = UIColor.clearColor().CGColor
selectedIndices.removeIndex(index)
}
}
}
let pathFrame = CGRect(x: -CGRectGetMidX(item.bounds), y: -CGRectGetMidY(item.bounds), width: item.bounds.size.width, height: item.bounds.size.height)
let path = UIBezierPath(roundedRect: pathFrame, cornerRadius: item.layer.cornerRadius)
let shapePosition = view.convertPoint(item.center, fromView: contentView)
let circleShape = CAShapeLayer()
circleShape.path = path.CGPath
circleShape.position = shapePosition
circleShape.fillColor = UIColor.clearColor().CGColor
circleShape.opacity = 0
circleShape.strokeColor = stroke.CGColor
circleShape.lineWidth = borderWidth
view.layer.addSublayer(circleShape)
let scaleAnimation = CABasicAnimation(keyPath: "transform.scale")
scaleAnimation.fromValue = NSValue(CATransform3D: CATransform3DIdentity)
scaleAnimation.toValue = NSValue(CATransform3D: CATransform3DMakeScale(2.5, 2.5, 1))
let alphaAnimation = CABasicAnimation(keyPath: "opacity")
alphaAnimation.fromValue = 1
alphaAnimation.toValue = 0
let animation = CAAnimationGroup()
animation.animations = [scaleAnimation, alphaAnimation]
animation.duration = 0.5
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
circleShape.addAnimation(animation, forKey: nil)
}
if let action = actionForIndex[index]{
action()
}
delegate?.sidebar(self, didTapItemAtIndex: index)
delegate?.sidebar(self, didEnable: didEnable, itemAtIndex: index)
}
private func layoutSubviews(){
let x = showFromRight ? parentViewController!.view.bounds.size.width - width : 0
contentView.frame = CGRect(x: x, y: 0, width: width, height: parentViewController!.view.bounds.size.height)
blurView.frame = contentView.frame
layoutItems()
}
private func layoutItems(){
let leftPadding: CGFloat = (width - itemSize.width) / 2
let topPadding: CGFloat = leftPadding
for (index, item) in enumerate(itemViews){
let idx: CGFloat = CGFloat(index)
let frame = CGRect(x: leftPadding, y: topPadding*idx + itemSize.height*idx + topPadding, width:itemSize.width, height: itemSize.height)
item.frame = frame
item.layer.cornerRadius = frame.size.width / 2
item.layer.borderColor = UIColor.clearColor().CGColor
item.alpha = 0
if selectedIndices.containsIndex(index){
if borderColors != nil{
item.layer.borderColor = borderColors![index].CGColor
}
}
}
let itemCount = CGFloat(itemViews.count)
contentView.contentSize = CGSizeMake(0, itemCount * (itemSize.height + topPadding) + topPadding)
}
private func indexOfTap(location: CGPoint) -> Int? {
var index: Int?
for (idx, item) in enumerate(itemViews){
if CGRectContainsPoint(item.frame, location){
index = idx
break
}
}
return index
}
private func addToParentViewController(viewController: UIViewController, callingAppearanceMethods: Bool){
if (parentViewController != nil){
removeFromParentViewControllerCallingAppearanceMethods(callingAppearanceMethods)
}
if callingAppearanceMethods{
beginAppearanceTransition(true, animated: false)
}
viewController.addChildViewController(self)
viewController.view.addSubview(self.view)
didMoveToParentViewController(self)
if callingAppearanceMethods{
endAppearanceTransition()
}
}
private func removeFromParentViewControllerCallingAppearanceMethods(callAppearanceMethods: Bool){
if callAppearanceMethods{
beginAppearanceTransition(false, animated: false)
}
willMoveToParentViewController(nil)
view.removeFromSuperview()
removeFromParentViewController()
if callAppearanceMethods{
endAppearanceTransition()
}
}
}
| apache-2.0 | 97985ab07ca9f3bfd3f964dd0222c2a6 | 41.95933 | 173 | 0.602361 | 5.644766 | false | false | false | false |
caicai0/ios_demo | load/Carthage/Checkouts/SwiftSoup/Example/Pods/SwiftSoup/Sources/Node.swift | 1 | 25607 | //
// Node.swift
// SwifSoup
//
// Created by Nabil Chatbi on 29/09/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
import Foundation
open class Node: Equatable, Hashable {
private static let EMPTY_NODES: Array<Node> = Array<Node>()
var parentNode: Node?
var childNodes: Array <Node>
var attributes: Attributes?
var baseUri: String?
/**
* Get the list index of this node in its node sibling list. I.e. if this is the first node
* sibling, returns 0.
* @return position in node sibling list
* @see org.jsoup.nodes.Element#elementSiblingIndex()
*/
public private(set) var siblingIndex: Int = 0
/**
Create a new Node.
@param baseUri base URI
@param attributes attributes (not null, but may be empty)
*/
public init(_ baseUri: String, _ attributes: Attributes) {
self.childNodes = Node.EMPTY_NODES
self.baseUri = baseUri.trim()
self.attributes = attributes
}
public init(_ baseUri: String) {
childNodes = Node.EMPTY_NODES
self.baseUri = baseUri.trim()
self.attributes = Attributes()
}
/**
* Default constructor. Doesn't setup base uri, children, or attributes; use with caution.
*/
public init() {
self.childNodes = Node.EMPTY_NODES
self.attributes = nil
self.baseUri = nil
}
/**
Get the node name of this node. Use for debugging purposes and not logic switching (for that, use instanceof).
@return node name
*/
public func nodeName() -> String {
preconditionFailure("This method must be overridden")
}
/**
* Get an attribute's value by its key. <b>Case insensitive</b>
* <p>
* To get an absolute URL from an attribute that may be a relative URL, prefix the key with <code><b>abs</b></code>,
* which is a shortcut to the {@link #absUrl} method.
* </p>
* E.g.:
* <blockquote><code>String url = a.attr("abs:href");</code></blockquote>
*
* @param attributeKey The attribute key.
* @return The attribute, or empty string if not present (to avoid nulls).
* @see #attributes()
* @see #hasAttr(String)
* @see #absUrl(String)
*/
open func attr(_ attributeKey: String)throws ->String {
let val: String = try attributes!.getIgnoreCase(key: attributeKey)
if (val.characters.count > 0) {
return val
} else if (attributeKey.lowercased().startsWith("abs:")) {
return try absUrl(attributeKey.substring("abs:".characters.count))
} else {return ""}
}
/**
* Get all of the element's attributes.
* @return attributes (which implements iterable, in same order as presented in original HTML).
*/
open func getAttributes() -> Attributes? {
return attributes
}
/**
* Set an attribute (key=value). If the attribute already exists, it is replaced.
* @param attributeKey The attribute key.
* @param attributeValue The attribute value.
* @return this (for chaining)
*/
@discardableResult
open func attr(_ attributeKey: String, _ attributeValue: String)throws->Node {
try attributes?.put(attributeKey, attributeValue)
return self
}
/**
* Test if this element has an attribute. <b>Case insensitive</b>
* @param attributeKey The attribute key to check.
* @return true if the attribute exists, false if not.
*/
open func hasAttr(_ attributeKey: String) -> Bool {
guard let attributes = attributes else {
return false
}
if (attributeKey.startsWith("abs:")) {
let key: String = attributeKey.substring("abs:".characters.count)
do {
let abs = try absUrl(key)
if (attributes.hasKeyIgnoreCase(key: key) && !"".equals(abs)) {
return true
}
} catch {
return false
}
}
return attributes.hasKeyIgnoreCase(key: attributeKey)
}
/**
* Remove an attribute from this element.
* @param attributeKey The attribute to remove.
* @return this (for chaining)
*/
@discardableResult
open func removeAttr(_ attributeKey: String)throws->Node {
try attributes?.removeIgnoreCase(key: attributeKey)
return self
}
/**
Get the base URI of this node.
@return base URI
*/
open func getBaseUri() -> String {
return baseUri!
}
/**
Update the base URI of this node and all of its descendants.
@param baseUri base URI to set
*/
open func setBaseUri(_ baseUri: String)throws {
class nodeVisitor: NodeVisitor {
private let baseUri: String
init(_ baseUri: String) {
self.baseUri = baseUri
}
func head(_ node: Node, _ depth: Int)throws {
node.baseUri = baseUri
}
func tail(_ node: Node, _ depth: Int)throws {
}
}
try traverse(nodeVisitor(baseUri))
}
/**
* Get an absolute URL from a URL attribute that may be relative (i.e. an <code><a href></code> or
* <code><img src></code>).
* <p>
* E.g.: <code>String absUrl = linkEl.absUrl("href");</code>
* </p>
* <p>
* If the attribute value is already absolute (i.e. it starts with a protocol, like
* <code>http://</code> or <code>https://</code> etc), and it successfully parses as a URL, the attribute is
* returned directly. Otherwise, it is treated as a URL relative to the element's {@link #baseUri}, and made
* absolute using that.
* </p>
* <p>
* As an alternate, you can use the {@link #attr} method with the <code>abs:</code> prefix, e.g.:
* <code>String absUrl = linkEl.attr("abs:href");</code>
* </p>
*
* @param attributeKey The attribute key
* @return An absolute URL if one could be made, or an empty string (not null) if the attribute was missing or
* could not be made successfully into a URL.
* @see #attr
* @see java.net.URL#URL(java.net.URL, String)
*/
open func absUrl(_ attributeKey: String)throws->String {
try Validate.notEmpty(string: attributeKey)
if (!hasAttr(attributeKey)) {
return "" // nothing to make absolute with
} else {
return StringUtil.resolve(baseUri!, relUrl: try attr(attributeKey))
}
}
/**
Get a child node by its 0-based index.
@param index index of child node
@return the child node at this index. Throws a {@code IndexOutOfBoundsException} if the index is out of bounds.
*/
open func childNode(_ index: Int) -> Node {
return childNodes[index]
}
/**
Get this node's children. Presented as an unmodifiable list: new children can not be added, but the child nodes
themselves can be manipulated.
@return list of children. If no children, returns an empty list.
*/
open func getChildNodes()->Array<Node> {
return childNodes
}
/**
* Returns a deep copy of this node's children. Changes made to these nodes will not be reflected in the original
* nodes
* @return a deep copy of this node's children
*/
open func childNodesCopy()->Array<Node> {
var children: Array<Node> = Array<Node>()
for node: Node in childNodes {
children.append(node.copy() as! Node)
}
return children
}
/**
* Get the number of child nodes that this node holds.
* @return the number of child nodes that this node holds.
*/
public func childNodeSize() -> Int {
return childNodes.count
}
final func childNodesAsArray() -> [Node] {
return childNodes as Array
}
/**
Gets this node's parent node.
@return parent node or null if no parent.
*/
open func parent() -> Node? {
return parentNode
}
/**
Gets this node's parent node. Node overridable by extending classes, so useful if you really just need the Node type.
@return parent node or null if no parent.
*/
final func getParentNode() -> Node? {
return parentNode
}
/**
* Gets the Document associated with this Node.
* @return the Document associated with this Node, or null if there is no such Document.
*/
open func ownerDocument() -> Document? {
if let this = self as? Document {
return this
} else if (parentNode == nil) {
return nil
} else {
return parentNode!.ownerDocument()
}
}
/**
* Remove (delete) this node from the DOM tree. If this node has children, they are also removed.
*/
open func remove()throws {
try parentNode?.removeChild(self)
}
/**
* Insert the specified HTML into the DOM before this node (i.e. as a preceding sibling).
* @param html HTML to add before this node
* @return this node, for chaining
* @see #after(String)
*/
@discardableResult
open func before(_ html: String)throws->Node {
try addSiblingHtml(siblingIndex, html)
return self
}
/**
* Insert the specified node into the DOM before this node (i.e. as a preceding sibling).
* @param node to add before this node
* @return this node, for chaining
* @see #after(Node)
*/
@discardableResult
open func before(_ node: Node)throws ->Node {
try Validate.notNull(obj: node)
try Validate.notNull(obj: parentNode)
try parentNode?.addChildren(siblingIndex, node)
return self
}
/**
* Insert the specified HTML into the DOM after this node (i.e. as a following sibling).
* @param html HTML to add after this node
* @return this node, for chaining
* @see #before(String)
*/
@discardableResult
open func after(_ html: String)throws ->Node {
try addSiblingHtml(siblingIndex + 1, html)
return self
}
/**
* Insert the specified node into the DOM after this node (i.e. as a following sibling).
* @param node to add after this node
* @return this node, for chaining
* @see #before(Node)
*/
@discardableResult
open func after(_ node: Node)throws->Node {
try Validate.notNull(obj: node)
try Validate.notNull(obj: parentNode)
try parentNode?.addChildren(siblingIndex+1, node)
return self
}
private func addSiblingHtml(_ index: Int, _ html: String)throws {
try Validate.notNull(obj: parentNode)
let context: Element? = parent() as? Element
let nodes: Array<Node> = try Parser.parseFragment(html, context, getBaseUri())
try parentNode?.addChildren(index, nodes)
}
/**
* Insert the specified HTML into the DOM after this node (i.e. as a following sibling).
* @param html HTML to add after this node
* @return this node, for chaining
* @see #before(String)
*/
@discardableResult
open func after(html: String)throws->Node {
try addSiblingHtml(siblingIndex + 1, html)
return self
}
/**
* Insert the specified node into the DOM after this node (i.e. as a following sibling).
* @param node to add after this node
* @return this node, for chaining
* @see #before(Node)
*/
@discardableResult
open func after(node: Node)throws->Node {
try Validate.notNull(obj: node)
try Validate.notNull(obj: parentNode)
try parentNode?.addChildren(siblingIndex + 1, node)
return self
}
open func addSiblingHtml(index: Int, _ html: String)throws {
try Validate.notNull(obj: html)
try Validate.notNull(obj: parentNode)
let context: Element? = parent() as? Element
let nodes: Array<Node> = try Parser.parseFragment(html, context, getBaseUri())
try parentNode?.addChildren(index, nodes)
}
/**
Wrap the supplied HTML around this node.
@param html HTML to wrap around this element, e.g. {@code <div class="head"></div>}. Can be arbitrarily deep.
@return this node, for chaining.
*/
@discardableResult
open func wrap(_ html: String)throws->Node? {
try Validate.notEmpty(string: html)
let context: Element? = parent() as? Element
var wrapChildren: Array<Node> = try Parser.parseFragment(html, context, getBaseUri())
let wrapNode: Node? = wrapChildren.count > 0 ? wrapChildren[0] : nil
if (wrapNode == nil || !(((wrapNode as? Element) != nil))) { // nothing to wrap with; noop
return nil
}
let wrap: Element = wrapNode as! Element
let deepest: Element = getDeepChild(el: wrap)
try parentNode?.replaceChild(self, wrap)
wrapChildren = wrapChildren.filter { $0 != wrap}
try deepest.addChildren(self)
// remainder (unbalanced wrap, like <div></div><p></p> -- The <p> is remainder
if (wrapChildren.count > 0) {
for i in 0..<wrapChildren.count {
let remainder: Node = wrapChildren[i]
try remainder.parentNode?.removeChild(remainder)
try wrap.appendChild(remainder)
}
}
return self
}
/**
* Removes this node from the DOM, and moves its children up into the node's parent. This has the effect of dropping
* the node but keeping its children.
* <p>
* For example, with the input html:
* </p>
* <p>{@code <div>One <span>Two <b>Three</b></span></div>}</p>
* Calling {@code element.unwrap()} on the {@code span} element will result in the html:
* <p>{@code <div>One Two <b>Three</b></div>}</p>
* and the {@code "Two "} {@link TextNode} being returned.
*
* @return the first child of this node, after the node has been unwrapped. Null if the node had no children.
* @see #remove()
* @see #wrap(String)
*/
@discardableResult
open func unwrap()throws ->Node? {
try Validate.notNull(obj: parentNode)
let firstChild: Node? = childNodes.count > 0 ? childNodes[0] : nil
try parentNode?.addChildren(siblingIndex, self.childNodesAsArray())
try self.remove()
return firstChild
}
private func getDeepChild(el: Element) -> Element {
let children = el.children()
if (children.size() > 0) {
return getDeepChild(el: children.get(0))
} else {
return el
}
}
/**
* Replace this node in the DOM with the supplied node.
* @param in the node that will will replace the existing node.
*/
public func replaceWith(_ input: Node)throws {
try Validate.notNull(obj: input)
try Validate.notNull(obj: parentNode)
try parentNode?.replaceChild(self, input)
}
public func setParentNode(_ parentNode: Node)throws {
if (self.parentNode != nil) {
try self.parentNode?.removeChild(self)
}
self.parentNode = parentNode
}
public func replaceChild(_ out: Node, _ input: Node)throws {
try Validate.isTrue(val: out.parentNode === self)
try Validate.notNull(obj: input)
if (input.parentNode != nil) {
try input.parentNode?.removeChild(input)
}
let index: Int = out.siblingIndex
childNodes[index] = input
input.parentNode = self
input.setSiblingIndex(index)
out.parentNode = nil
}
public func removeChild(_ out: Node)throws {
try Validate.isTrue(val: out.parentNode === self)
let index: Int = out.siblingIndex
childNodes.remove(at: index)
reindexChildren(index)
out.parentNode = nil
}
public func addChildren(_ children: Node...)throws {
//most used. short circuit addChildren(int), which hits reindex children and array copy
try addChildren(children)
}
public func addChildren(_ children: [Node])throws {
//most used. short circuit addChildren(int), which hits reindex children and array copy
for child in children {
try reparentChild(child)
ensureChildNodes()
childNodes.append(child)
child.setSiblingIndex(childNodes.count-1)
}
}
public func addChildren(_ index: Int, _ children: Node...)throws {
try addChildren(index, children)
}
public func addChildren(_ index: Int, _ children: [Node])throws {
ensureChildNodes()
for i in (0..<children.count).reversed() {
let input: Node = children[i]
try reparentChild(input)
childNodes.insert(input, at: index)
reindexChildren(index)
}
}
public func ensureChildNodes() {
// if (childNodes === Node.EMPTY_NODES) {
// childNodes = Array<Node>()
// }
}
public func reparentChild(_ child: Node)throws {
if (child.parentNode != nil) {
try child.parentNode?.removeChild(child)
}
try child.setParentNode(self)
}
private func reindexChildren(_ start: Int) {
for i in start..<childNodes.count {
childNodes[i].setSiblingIndex(i)
}
}
/**
Retrieves this node's sibling nodes. Similar to {@link #childNodes() node.parent.childNodes()}, but does not
include this node (a node is not a sibling of itself).
@return node siblings. If the node has no parent, returns an empty list.
*/
open func siblingNodes()->Array<Node> {
if (parentNode == nil) {
return Array<Node>()
}
let nodes: Array<Node> = parentNode!.childNodes
var siblings: Array<Node> = Array<Node>()
for node in nodes {
if (node !== self) {
siblings.append(node)
}
}
return siblings
}
/**
Get this node's next sibling.
@return next sibling, or null if this is the last sibling
*/
open func nextSibling() -> Node? {
if (parentNode == nil) {
return nil // root
}
let siblings: Array<Node> = parentNode!.childNodes
let index: Int = siblingIndex+1
if (siblings.count > index) {
return siblings[index]
} else {
return nil
}
}
/**
Get this node's previous sibling.
@return the previous sibling, or null if this is the first sibling
*/
open func previousSibling() -> Node? {
if (parentNode == nil) {
return nil // root
}
if (siblingIndex > 0) {
return parentNode?.childNodes[siblingIndex-1]
} else {
return nil
}
}
public func setSiblingIndex(_ siblingIndex: Int) {
self.siblingIndex = siblingIndex
}
/**
* Perform a depth-first traversal through this node and its descendants.
* @param nodeVisitor the visitor callbacks to perform on each node
* @return this node, for chaining
*/
@discardableResult
open func traverse(_ nodeVisitor: NodeVisitor)throws->Node {
let traversor: NodeTraversor = NodeTraversor(nodeVisitor)
try traversor.traverse(self)
return self
}
/**
Get the outer HTML of this node.
@return HTML
*/
open func outerHtml()throws->String {
let accum: StringBuilder = StringBuilder(128)
try outerHtml(accum)
return accum.toString()
}
public func outerHtml(_ accum: StringBuilder)throws {
try NodeTraversor(OuterHtmlVisitor(accum, getOutputSettings())).traverse(self)
}
// if this node has no document (or parent), retrieve the default output settings
func getOutputSettings() -> OutputSettings {
return ownerDocument() != nil ? ownerDocument()!.outputSettings() : (Document("")).outputSettings()
}
/**
Get the outer HTML of this node.
@param accum accumulator to place HTML into
@throws IOException if appending to the given accumulator fails.
*/
func outerHtmlHead(_ accum: StringBuilder, _ depth: Int, _ out: OutputSettings) throws {
preconditionFailure("This method must be overridden")
}
func outerHtmlTail(_ accum: StringBuilder, _ depth: Int, _ out: OutputSettings) throws {
preconditionFailure("This method must be overridden")
}
/**
* Write this node and its children to the given {@link Appendable}.
*
* @param appendable the {@link Appendable} to write to.
* @return the supplied {@link Appendable}, for chaining.
*/
open func html(_ appendable: StringBuilder)throws -> StringBuilder {
try outerHtml(appendable)
return appendable
}
public func indent(_ accum: StringBuilder, _ depth: Int, _ out: OutputSettings) {
accum.append("\n").append(StringUtil.padding(depth * Int(out.indentAmount())))
}
/**
* Check if this node is the same instance of another (object identity test).
* @param o other object to compare to
* @return true if the content of this node is the same as the other
* @see Node#hasSameValue(Object) to compare nodes by their value
*/
open func equals(_ o: Node) -> Bool {
// implemented just so that javadoc is clear this is an identity test
return self === o
}
/**
* Check if this node is has the same content as another node. A node is considered the same if its name, attributes and content match the
* other node; particularly its position in the tree does not influence its similarity.
* @param o other object to compare to
* @return true if the content of this node is the same as the other
*/
open func hasSameValue(_ o: Node)throws->Bool {
if (self === o) {return true}
// if (type(of:self) != type(of: o))
// {
// return false
// }
return try self.outerHtml() == o.outerHtml()
}
/**
* Create a stand-alone, deep copy of this node, and all of its children. The cloned node will have no siblings or
* parent node. As a stand-alone object, any changes made to the clone or any of its children will not impact the
* original node.
* <p>
* The cloned node may be adopted into another Document or node structure using {@link Element#appendChild(Node)}.
* @return stand-alone cloned node
*/
public func copy(with zone: NSZone? = nil) -> Any {
return copy(clone: Node())
}
public func copy(parent: Node?) -> Node {
let clone = Node()
return copy(clone: clone, parent: parent)
}
public func copy(clone: Node) -> Node {
let thisClone: Node = copy(clone: clone, parent: nil) // splits for orphan
// Queue up nodes that need their children cloned (BFS).
var nodesToProcess: Array<Node> = Array<Node>()
nodesToProcess.append(thisClone)
while (!nodesToProcess.isEmpty) {
let currParent: Node = nodesToProcess.removeFirst()
for i in 0..<currParent.childNodes.count {
let childClone: Node = currParent.childNodes[i].copy(parent:currParent)
currParent.childNodes[i] = childClone
nodesToProcess.append(childClone)
}
}
return thisClone
}
/*
* Return a clone of the node using the given parent (which can be null).
* Not a deep copy of children.
*/
public func copy(clone: Node, parent: Node?) -> Node {
clone.parentNode = parent // can be null, to create an orphan split
clone.siblingIndex = parent == nil ? 0 : siblingIndex
clone.attributes = attributes != nil ? attributes?.clone() : nil
clone.baseUri = baseUri
clone.childNodes = Array<Node>()
for child in childNodes {
clone.childNodes.append(child)
}
return clone
}
private class OuterHtmlVisitor: NodeVisitor {
private var accum: StringBuilder
private var out: OutputSettings
init(_ accum: StringBuilder, _ out: OutputSettings) {
self.accum = accum
self.out = out
}
open func head(_ node: Node, _ depth: Int)throws {
try node.outerHtmlHead(accum, depth, out)
}
open func tail(_ node: Node, _ depth: Int)throws {
if (!(node.nodeName() == "#text")) { // saves a void hit.
try node.outerHtmlTail(accum, depth, out)
}
}
}
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func ==(lhs: Node, rhs: Node) -> Bool {
return lhs === rhs
}
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
public var hashValue: Int {
var result: Int = description.hashValue
result = Int.addWithOverflow(Int.multiplyWithOverflow(31, result).0, baseUri != nil ? baseUri!.hashValue : 31).0
return result
}
}
extension Node : CustomStringConvertible {
public var description: String {
do {
return try outerHtml()
} catch {
}
return ""
}
}
extension Node : CustomDebugStringConvertible {
public var debugDescription: String {
do {
return try String(describing: type(of: self)) + " " + outerHtml()
} catch {
}
return String(describing: type(of: self))
}
}
| mit | 4f20053111fbd0361aeefbd3424d5e0c | 30.967541 | 142 | 0.611771 | 4.278363 | false | false | false | false |
luizilha/Alert-Coin | Alert Coin/ViewController.swift | 1 | 1647 | //
// ViewController.swift
// Alert Coin
//
// Created by Luiz Ilha on 7/29/15.
// Copyright (c) 2015 Ilha. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func getCoin(index: Int, key: String) -> String {
let url = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22USDBRL%22%2C%22GBPUSD%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback="
let jsonData = NSData(contentsOfURL: NSURL(string: url)!)
let result = NSJSONSerialization.JSONObjectWithData(jsonData!, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary
return (result.objectForKey("query")!.objectForKey("results")!.objectForKey("rate")?.objectAtIndex(index).objectForKey(key)?.description)!
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("mainCell") as! MainCell
cell.coinName.text = "BRL/USD Dolar Americano"
cell.coinValue.text = getCoin(0, key: "Bid")
return cell
}
}
| mit | 9f707fc97269357c11e86db2965e2eee | 38.214286 | 232 | 0.706132 | 4.233933 | false | false | false | false |
scodx/LoL-Champions-Demo | LoL Champions/AppDelegate.swift | 1 | 7601 | //
// AppDelegate.swift
// LoL Champions
//
// Created by Oscar on 02/07/15.
// Copyright (c) 2015 uinik. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let splitViewController = self.window!.rootViewController as! UISplitViewController
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
navigationController.topViewController.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem()
splitViewController.delegate = self
let masterNavigationController = splitViewController.viewControllers[0] as! UINavigationController
let controller = masterNavigationController.topViewController as! MasterViewController
controller.managedObjectContext = self.managedObjectContext
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Split view
func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController!, ontoPrimaryViewController primaryViewController:UIViewController!) -> Bool {
if let secondaryAsNavController = secondaryViewController as? UINavigationController {
if let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController {
if topAsDetailController.detailItem == nil {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
}
}
return false
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.uinik.LoL_Champions" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as! NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("LoL_Champions", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("LoL_Champions.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
| mit | 1c040f7419abd5e412552c5d0ba50363 | 56.583333 | 290 | 0.723457 | 6.075939 | false | false | false | false |
Johennes/firefox-ios | Utils/Extensions/NSFileManagerExtensions.swift | 1 | 4114 | /* 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/. */
/* Created and contributed by Nikolai Ruhe and rewritten in Swift.
* https://github.com/NikolaiRuhe/NRFoundation */
import Foundation
public let NSFileManagerExtensionsDomain = "org.mozilla.NSFileManagerExtensions"
public enum NSFileManagerExtensionsErrorCodes: Int {
case EnumeratorFailure = 0
case EnumeratorElementNotURL = 1
case ErrorEnumeratingDirectory = 2
}
public extension NSFileManager {
private func directoryEnumeratorForURL(url: NSURL) throws -> NSDirectoryEnumerator {
let prefetchedProperties = [
NSURLIsRegularFileKey,
NSURLFileAllocatedSizeKey,
NSURLTotalFileAllocatedSizeKey
]
// If we run into an issue getting an enumerator for the given URL, capture the error and bail out later.
var enumeratorError: NSError?
let errorHandler: (NSURL, NSError?) -> Bool = { _, error in
enumeratorError = error
return false
}
guard let directoryEnumerator = NSFileManager.defaultManager().enumeratorAtURL(url,
includingPropertiesForKeys: prefetchedProperties,
options: [],
errorHandler: errorHandler) else {
throw errorWithCode(.EnumeratorFailure)
}
// Bail out if we encountered an issue getting the enumerator.
if let _ = enumeratorError {
throw errorWithCode(.ErrorEnumeratingDirectory, underlyingError: enumeratorError)
}
return directoryEnumerator
}
private func sizeForItemURL(url: AnyObject, withPrefix prefix: String) throws -> Int64 {
guard let itemURL = url as? NSURL else {
throw errorWithCode(.EnumeratorElementNotURL)
}
// Skip files that are not regular and don't match our prefix
guard itemURL.isRegularFile && itemURL.lastComponentIsPrefixedBy(prefix) else {
return 0
}
return (url as? NSURL)?.allocatedFileSize() ?? 0
}
func allocatedSizeOfDirectoryAtURL(url: NSURL, forFilesPrefixedWith prefix: String, isLargerThanBytes threshold: Int64) throws -> Bool {
let directoryEnumerator = try directoryEnumeratorForURL(url)
var acc: Int64 = 0
for item in directoryEnumerator {
acc += try sizeForItemURL(item, withPrefix: prefix)
if acc > threshold {
return true
}
}
return false
}
/**
Returns the precise size of the given directory on disk.
- parameter url: Directory URL
- parameter prefix: Prefix of files to check for size
- throws: Error reading/operating on disk.
*/
func getAllocatedSizeOfDirectoryAtURL(url: NSURL, forFilesPrefixedWith prefix: String) throws -> Int64 {
let directoryEnumerator = try directoryEnumeratorForURL(url)
return try directoryEnumerator.reduce(0) {
let size = try sizeForItemURL($1, withPrefix: prefix)
return $0 + size
}
}
func contentsOfDirectoryAtPath(path: String, withFilenamePrefix prefix: String) throws -> [String] {
return try NSFileManager.defaultManager().contentsOfDirectoryAtPath(path)
.filter { $0.hasPrefix("\(prefix).") }
.sort { $0 < $1 }
}
func removeItemInDirectory(directory: String, named: String) throws {
if let file = NSURL.fileURLWithPath(directory).URLByAppendingPathComponent(named)!.path {
try self.removeItemAtPath(file)
}
}
private func errorWithCode(code: NSFileManagerExtensionsErrorCodes, underlyingError error: NSError? = nil) -> NSError {
var userInfo = [String: AnyObject]()
if let _ = error {
userInfo[NSUnderlyingErrorKey] = error
}
return NSError(
domain: NSFileManagerExtensionsDomain,
code: code.rawValue,
userInfo: userInfo)
}
}
| mpl-2.0 | 1ea56e439c7c712ae4784d2c4cde66b7 | 35.40708 | 140 | 0.657268 | 5.227446 | false | false | false | false |
huangboju/Moots | Examples/UIScrollViewDemo/UIScrollViewDemo/BannerView/CycleView.swift | 1 | 4372 | //
// Copyright © 2016年 xiAo_Ju. All rights reserved.
//
import UIKit
class CycleView: UIView, UIScrollViewDelegate {
// MARK: - 🍀 变量
var scrollView: UIScrollView!
var page = 0 // 当前处于的页面,默认为0
private var imageViewX: CGFloat = 0
var canCycle = true // 能否循环
var canAutoRun: Bool = true { // 能否自动滑动
didSet {
if canAutoRun {
timerInit()
} else {
timer?.invalidate()
timer = nil
}
}
}
var timer: Timer? // 计时器(用来控制自动滑动)
// MARK: - 💖 初始化
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .white
scrollView = UIScrollView(frame: CGRect(origin: CGPoint.zero, size: frame.size))
scrollView.isPagingEnabled = true
scrollView.showsHorizontalScrollIndicator = false
scrollView.isUserInteractionEnabled = false // 这句和下一句可以让点击响应到父类 #SO
addGestureRecognizer(scrollView.panGestureRecognizer)
addSubview(scrollView)
scrollView.delegate = self
}
// MARK: - 💜 UIScrollViewDelegate
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
if canAutoRun {
// 计时器 inValidate
timer?.invalidate()
timer = nil
}
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
page = Int(scrollView.contentOffset.x / scrollView.frame.width)
if canCycle {
if page <= 0 {
let value = data.count - 2
if scrollView.contentOffset.x < scrollView.frame.width / 2 && (value >= 0) {
scrollView.contentOffset.x = scrollView.frame.width * CGFloat(value) + scrollView.contentOffset.x
}
} else if page >= data.count - 1 {
// 最后一个
scrollView.contentOffset.x = scrollView.frame.width
} else {
}
// 卡顿版本
// let count = data.count
// if scrollView.contentOffset.x == 0.0 {
// scrollView.contentOffset.x = scrollView.frame.width * CGFloat(count - 2)
// } else if scrollView.contentOffset.x == scrollView.frame.width * CGFloat(count - 1) {
// scrollView.contentOffset.x = scrollView.frame.width
// }
}
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
timerInit()
}
var data: [String]!
func set(contents: [String]) {
data = [contents[0]] + contents + [contents[contents.count - 1]]
let width = scrollView.frame.width
scrollView.contentSize = CGSize(width: width * CGFloat(data.count), height: scrollView.frame.height)
for (i, _) in data.enumerated() {
let contentLabel = UILabel(frame: CGRect(x: CGFloat(i) * width, y: 0, width: width, height: scrollView.frame.height))
contentLabel.text = i.description
contentLabel.font = UIFont.systemFont(ofSize: 58)
contentLabel.textAlignment = .center
contentLabel.textColor = .white
contentLabel.backgroundColor = UIColor(white: CGFloat(i) / 10, alpha: 1)
contentLabel.tag = i
scrollView.addSubview(contentLabel)
}
scrollView.contentOffset.x = scrollView.frame.width
timerInit()
}
func timerInit() {
if canAutoRun {
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(autoSetCurrentContentOffset), userInfo: nil, repeats: true)
}
}
@objc func autoSetCurrentContentOffset() {
// let n = Int(scrollView.contentOffset.x / scrollView.frame.width) // 放开这句解决不能滚动整屏
let n = scrollView.contentOffset.x / scrollView.frame.width
let x = CGFloat(n) * scrollView.frame.width
scrollView.setContentOffset(CGPoint(x: x + scrollView.frame.width, y: scrollView.contentOffset.y), animated: true)
}
}
| mit | 209698fbaa3116d0f4f4242444044681 | 35.275862 | 151 | 0.583888 | 4.634361 | false | false | false | false |
huangboju/QMUI.swift | QMUI.swift/Demo/Modules/Demos/Components/QDAssetsManagerViewController.swift | 1 | 1321 | //
// QDAssetsManagerViewController.swift
// QMUI.swift
//
// Created by qd-hxt on 2018/5/15.
// Copyright © 2018年 伯驹 黄. All rights reserved.
//
import UIKit
class QDAssetsManagerViewController: QDCommonListViewController {
override func setNavigationItems(_ isInEditMode: Bool, animated: Bool) {
super.setNavigationItems(isInEditMode, animated: animated)
}
override func initDataSource() {
super.initDataSource()
dataSourceWithDetailText = QMUIOrderedDictionary(
dictionaryLiteral:
("保存图片到指定相册", "生成随机图片并保存到指定的相册"),
("保存视频到指定相册", "拍摄一个视频并保存到指定的相册"))
}
override func didSelectCell(_ title: String) {
var viewController: QMUICommonViewController?
if title == "保存图片到指定相册" {
viewController = QDSaveImageToSpecifiedAlbumViewController()
} else if title == "保存视频到指定相册" {
viewController = QDSaveVideoToSpecifiedAlbumViewController()
}
if let viewController = viewController {
viewController.title = title
navigationController?.pushViewController(viewController, animated: true)
}
}
}
| mit | 61203ae9e5af99b20e65390396d48b93 | 30.052632 | 84 | 0.660169 | 4.855967 | false | false | false | false |
maryamfekri/MFCameraManager | CustomCameraManagerClass/FocusLine.swift | 1 | 1715 | //
// FocusLine.swift
// sampleCameraManager
//
// Created by Maryam on 3/3/17.
// Copyright © 2017 Maryam. All rights reserved.
//
import UIKit
class FocusLine: CALayer {
open var strokeColor = UIColor.yellow.cgColor
open var strokeWidth: CGFloat = 1
open var drawingCornersArray = [[CGPoint]]()
open var corners = [[Any]]() {
willSet {
DispatchQueue.main.async(execute: {
self.setNeedsDisplay()
})
}
}
override open func draw(in ctx: CGContext) {
objc_sync_enter(self)
ctx.saveGState()
ctx.setShouldAntialias(true)
ctx.setAllowsAntialiasing(true)
ctx.setFillColor(UIColor.clear.cgColor)
ctx.setStrokeColor(self.strokeColor)
ctx.setLineWidth(self.strokeWidth)
for corners in self.corners {
for i in 0...corners.count {
var idx = i
if i == corners.count {
idx = 0
}
if let dict = corners[idx] as? NSDictionary,
let rawXPosition = dict.object(forKey: "X") as? NSNumber,
let rawYPosition = dict.object(forKey: "Y") as? NSNumber {
let x = CGFloat(truncating: rawXPosition)
let y = CGFloat(truncating: rawYPosition)
if i == 0 {
ctx.move(to: CGPoint(x: x, y: y))
} else {
ctx.addLine(to: CGPoint(x: x, y: y))
}
}
}
}
ctx.drawPath(using: CGPathDrawingMode.fillStroke)
ctx.restoreGState()
objc_sync_exit(self)
}
}
| mit | d9d08711d114ab857964217c6a60a1d3 | 26.645161 | 78 | 0.514002 | 4.522427 | false | false | false | false |
Ryan-Vanderhoef/Antlers | AppIdea/Frameworks/Bond/Bond/Bond+UIBarItem.swift | 1 | 3205 | //
// Bond+UIBarItem.swift
// Bond
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Srdan Rasic (@srdanrasic)
//
// 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
private var enabledDynamicHandleUIBarItem: UInt8 = 0;
private var titleDynamicHandleUIBarItem: UInt8 = 0;
private var imageDynamicHandleUIBarItem: UInt8 = 0;
extension UIBarItem: Bondable {
public var dynEnabled: Dynamic<Bool> {
if let d: AnyObject = objc_getAssociatedObject(self, &enabledDynamicHandleUIBarItem) {
return (d as? Dynamic<Bool>)!
} else {
let d = InternalDynamic<Bool>(self.enabled, faulty: false)
let bond = Bond<Bool>() { [weak self] v in if let s = self { s.enabled = v } }
d.bindTo(bond, fire: false, strongly: false)
d.retain(bond)
objc_setAssociatedObject(self, &enabledDynamicHandleUIBarItem, d, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
return d
}
}
public var dynTitle: Dynamic<String> {
if let d: AnyObject = objc_getAssociatedObject(self, &titleDynamicHandleUIBarItem) {
return (d as? Dynamic<String>)!
} else {
let d = InternalDynamic<String>(self.title ?? "", faulty: false)
let bond = Bond<String>() { [weak self] v in if let s = self { s.title = v } }
d.bindTo(bond, fire: false, strongly: false)
d.retain(bond)
objc_setAssociatedObject(self, &titleDynamicHandleUIBarItem, d, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
return d
}
}
public var dynImage: Dynamic<UIImage?> {
if let d: AnyObject = objc_getAssociatedObject(self, &imageDynamicHandleUIBarItem) {
return (d as? Dynamic<UIImage?>)!
} else {
let d = InternalDynamic<UIImage?>(self.image, faulty: false)
let bond = Bond<UIImage?>() { [weak self] img in if let s = self { s.image = img } }
d.bindTo(bond, fire: false, strongly: false)
d.retain(bond)
objc_setAssociatedObject(self, &imageDynamicHandleUIBarItem, d, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
return d
}
}
public var designatedBond: Bond<Bool> {
return self.dynEnabled.valueBond
}
}
| mit | f6bf2114b2453bd40eacb45c4bc1fe58 | 40.089744 | 130 | 0.702652 | 4.103713 | false | false | false | false |
plushcube/Learning | Swift/Stanford Swift Course/SU Happiness/Happiness/HappinessViewController.swift | 1 | 1468 | //
// HappinessViewController.swift
// Happiness
//
// Created by n0p and Mari on 2015-04-11.
// Copyright (c) 2015 Improve Digital. All rights reserved.
//
import UIKit
class HappinessViewController: UIViewController, FaceDataSource {
@IBOutlet weak var faceView: FaceView! {
didSet {
faceView.dataSource = self
faceView.addGestureRecognizer(UIPinchGestureRecognizer(target: faceView, action: "scale:"))
}
}
var happiness: Int = 10 { // 0 = very sad, 100 = ecstatic
didSet {
min(max(happiness, 0), 100)
println("Happiness = \(happiness)")
updateUI()
}
}
private struct Constants {
static let HappinessGestureScale: CGFloat = 6
}
@IBAction func changeHappiness(gesture: UIPanGestureRecognizer) {
switch gesture.state {
case .Ended: fallthrough
case .Changed:
let translation = gesture.translationInView(faceView)
let happinessChange = -Int(translation.y / Constants.HappinessGestureScale)
if happinessChange != 0 {
happiness += happinessChange
gesture.setTranslation(CGPointZero, inView: faceView)
}
default: break
}
}
private func updateUI() {
faceView.setNeedsDisplay()
}
func smilinessForFaceView(sender: FaceView) -> Double? {
return Double(happiness - 50) / 50
}
}
| mit | dfdd6eacc29698411492a22512c113f9 | 26.698113 | 103 | 0.609673 | 4.993197 | false | false | false | false |
bernardotc/Recordando | Recordando/Recordando/GameImagesViewController.swift | 1 | 7464 | //
// GameImagesViewController.swift
// Recordando
//
// Created by Bernardo Trevino on 10/17/16.
// Copyright © 2016 bernardo. All rights reserved.
//
import UIKit
class GameImagesViewController: UIViewController, UIPopoverPresentationControllerDelegate {
@IBOutlet weak var viewContainer: UIView!
@IBOutlet weak var btnLeftTopInfo: UIButton!
@IBOutlet weak var btnRightTopInfo: UIButton!
@IBOutlet weak var btnLeftBottomInfo: UIButton!
@IBOutlet weak var btnRightBottomInfo: UIButton!
@IBOutlet weak var btnLeftTopAnswer: UIButton!
@IBOutlet weak var btnRightTopAnswer: UIButton!
@IBOutlet weak var btnLeftBottomAnswer: UIButton!
@IBOutlet weak var btnRightBottomAnswer: UIButton!
@IBOutlet weak var lblIsCorrect: UILabel!
@IBOutlet weak var lblCategory: UILabel!
@IBOutlet weak var lblInstruction: UILabel!
@IBOutlet weak var barBtnNext: UIBarButtonItem!
var categories: [Categoria] = []
var generalCategory: Categoria!
var images: [Imagen] = []
var correctImage: Imagen!
var btnCorrectAnswer: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Select the categories that are set to be used.
if !categorias[0].usar {
for category in categorias {
if (category.usar) {
categories.append(category)
}
}
} else {
categories = categorias
}
viewContainer.isHidden = true
lblInstruction.text = "Selecciona la imagen que no va de acuerdo con las otras tres."
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
loadImages()
}
// Main function controller of the process of showing images
func loadImages() {
barBtnNext.isEnabled = false
generalCategory = selectCategory()
selectThreeImagesFromSameCategory(category: generalCategory)
getImageFromDifferentCategory()
images.shuffle()
setImages()
}
// Select the category of the iteration.
func selectCategory() -> Categoria {
let categoryCount = categories.count
while true {
let random = Int(arc4random_uniform(UInt32(categoryCount)))
// Make sure the category has at least 3 different images.
if categories[random].imagenes.count >= 3 {
return categories[random]
}
}
}
// From the category selected for this iteration, select 3 images.
func selectThreeImagesFromSameCategory(category: Categoria) {
let imageCount = category.imagenes.count
var threeRandomNumbers: [Int] = []
// Be sure that there are 3 different images.
while threeRandomNumbers.count < 3 {
let random = Int(arc4random_uniform(UInt32(imageCount)))
if !threeRandomNumbers.contains(random) {
threeRandomNumbers.append(random)
images.append(category.imagenes[random])
}
}
}
// Set the image that is from a different category
func getImageFromDifferentCategory() {
let categoryCount = categories.count
while images.count < 4 {
let random = Int(arc4random_uniform(UInt32(categoryCount)))
// Check that the category has at least 1 image.
if categories[random].imagenes.count >= 1 {
if categories[random].id != generalCategory.id {
let index = Int(arc4random_uniform(UInt32(categories[random].imagenes.count)))
correctImage = categories[random].imagenes[index]
images.append(correctImage)
}
}
}
}
// Put the images to their respective outlets.
func setImages() {
btnLeftTopAnswer.setImage(images[0].image, for: .normal)
btnRightTopAnswer.setImage(images[1].image, for: .normal)
btnLeftBottomAnswer.setImage(images[2].image, for: .normal)
btnRightBottomAnswer.setImage(images[3].image, for: .normal)
if correctImage.id == images[0].id {
btnCorrectAnswer = btnLeftTopAnswer
} else if correctImage.id == images[1].id {
btnCorrectAnswer = btnRightTopAnswer
} else if correctImage.id == images[2].id {
btnCorrectAnswer = btnLeftBottomAnswer
} else {
btnCorrectAnswer = btnRightBottomAnswer
}
}
// When a user does a tap to an image, this method is called.
@IBAction func chooseAnswer(_ sender: UIButton) {
barBtnNext.isEnabled = true
viewContainer.isHidden = false
lblInstruction.isHidden = true
btnLeftTopAnswer.alpha = 0.4
btnRightTopAnswer.alpha = 0.4
btnLeftBottomAnswer.alpha = 0.4
btnRightBottomAnswer.alpha = 0.4
if (sender == btnCorrectAnswer) {
lblIsCorrect.text = "¡Correcto!"
} else {
lblIsCorrect.text = "Incorrecto."
}
lblCategory.text = "Categoría: \(generalCategory.nombre!)."
}
// When the next button is clicked.
@IBAction func showNextSet(_ sender: AnyObject) {
viewContainer.isHidden = true
images = []
loadImages()
lblInstruction.isHidden = false
btnLeftTopAnswer.alpha = 1
btnRightTopAnswer.alpha = 1
btnLeftBottomAnswer.alpha = 1
btnRightBottomAnswer.alpha = 1
}
// 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?) {
// Show image info
if segue.identifier == "popoverImageInfo" {
let view = segue.destination as! ImageInformationViewController
let button = sender as! UIButton
// Check what was the image that made the call
if button == btnLeftTopInfo {
view.imageDescription = images[0].descripcion
} else if button == btnRightTopInfo {
view.imageDescription = images[1].descripcion
} else if button == btnLeftBottomInfo {
view.imageDescription = images[2].descripcion
} else {
view.imageDescription = images[3].descripcion
}
// Show popover
view.modalPresentationStyle = .popover
view.popoverPresentationController?.delegate = self
}
}
// Be sure the popover adapts.
func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
return .none
}
}
// An extension to make the images shuffle.
extension MutableCollection where Indices.Iterator.Element == Index {
/// Shuffles the contents of this collection.
mutating func shuffle() {
let c = count
guard c > 1 else { return }
for (unshuffledCount, firstUnshuffled) in zip(stride(from: c, to: 1, by: -1), indices) {
let d: IndexDistance = numericCast(arc4random_uniform(numericCast(unshuffledCount)))
guard d != 0 else { continue }
let i = index(firstUnshuffled, offsetBy: d)
swap(&self[firstUnshuffled], &self[i])
}
}
}
| mit | 078ed86895ede188f687a7bf7133094f | 35.573529 | 106 | 0.617209 | 5.014113 | false | false | false | false |
duliodenis/fruitycrush | Fruity Crush/Fruity Crush/PulsatingButton.swift | 1 | 2063 | //
// PulsatingButton.swift
// Fruity Crush
//
// Created by Dulio Denis on 3/22/16.
// Copyright © 2016 Dulio Denis. All rights reserved.
//
import UIKit
import pop
@IBDesignable
class PulsatingButton: UIButton {
@IBInspectable var cornerRadius: CGFloat = 4.0 {
didSet {
setupView()
}
}
@IBInspectable var fontColor: UIColor = UIColor.whiteColor() {
didSet {
tintColor = fontColor
}
}
override func awakeFromNib() {
setupView()
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
setupView()
}
func setupView() {
layer.cornerRadius = cornerRadius
addTarget(self, action: "scaleToSmall", forControlEvents: .TouchDown)
addTarget(self, action: "scaleToSmall", forControlEvents: .TouchDragEnter)
addTarget(self, action: "scaleAnimation", forControlEvents: .TouchUpInside)
addTarget(self, action: "scaleToDefault", forControlEvents: .TouchDragExit)
}
// MARK: Animation Functions
func scaleToSmall() {
let scaleAnimation = POPBasicAnimation(propertyNamed: kPOPLayerScaleXY)
scaleAnimation.toValue = NSValue(CGSize: CGSizeMake(0.95, 0.95))
layer.pop_addAnimation(scaleAnimation, forKey: "layerScaleSmallAnimation")
}
func scaleAnimation() {
let scaleAnimation = POPSpringAnimation(propertyNamed: kPOPLayerScaleXY)
scaleAnimation.velocity = NSValue(CGSize: CGSizeMake(3.0, 3.0))
scaleAnimation.toValue = NSValue(CGSize: CGSizeMake(1.0, 1.0))
scaleAnimation.springBounciness = 18
layer.pop_addAnimation(scaleAnimation, forKey: "layerScaleSpringAnimation")
}
func scaleDefault() {
let scaleAnimation = POPBasicAnimation(propertyNamed: kPOPLayerScaleXY)
scaleAnimation.toValue = NSValue(CGSize: CGSizeMake(1.0, 1.0))
layer.pop_addAnimation(scaleAnimation, forKey: "layerScaleDefaultAnimation")
}
}
| mit | 3e078012f18728e66795cdb09d2a1a4d | 28.884058 | 84 | 0.659554 | 5.029268 | false | false | false | false |
yarshure/Surf | Surf/SFTableViewController.swift | 1 | 10556 | //
// SFTableViewController.swift
// Surf
//
// Created by yarshure on 16/2/14.
// Copyright © 2016年 yarshure. All rights reserved.
//
import UIKit
import SFSocket
import XRuler
import SwiftyStoreKit
enum RegisteredPurchase: String {
case KCP
case HTTP
case Rule
case Analyze
case Pro
case VIP
case OneGB //1GB 不限流量
//case 30D
case nonConsumablePurchase
case consumablePurchase
case autoRenewablePurchase
case nonRenewingPurchase
}
open class SFTableViewController: UITableViewController {
let appBundleId = "com.yarshure.Surf"
func dataForShare(filePath:URL?) ->Data? {
guard let u = filePath else {
return nil
}
do {
let data = try Data.init(contentsOf: u)
return data
}catch let e {
print(e.localizedDescription)
}
return nil
}
func messageForProductRetrievalInfo(_ result: RetrieveResults) -> String {
if let product = result.retrievedProducts.first {
let priceString = product.localizedPrice!
return " \(product.localizedTitle) - \(priceString)"
} else if let invalidProductId = result.invalidProductIDs.first {
return "Could not retrieve product info" + " Invalid product identifier: \(invalidProductId)"
} else {
let errorString = result.error?.localizedDescription ?? "Unknown error. Please contact support"
return "Could not retrieve product info " + errorString
}
}
func alertMessageAction(_ message:String,complete:(() -> Void)?) {
var style:UIAlertController.Style = .alert
let deviceIdiom = UIScreen.main.traitCollection.userInterfaceIdiom
switch deviceIdiom {
case .pad:
style = .alert
default:
break
}
let alert = UIAlertController.init(title: "Alert", message: message, preferredStyle: style)
let action = UIAlertAction.init(title: "OK", style: .default) { (action:UIAlertAction) -> Void in
if let callback = complete {
callback()
}
}
let actionCancel = UIAlertAction.init(title: "Cancel", style: .default) { (action:UIAlertAction) -> Void in
}
alert.addAction(action)
alert.addAction(actionCancel)
self.present(alert, animated: true) { () -> Void in
}
}
func alertMessageAction(_ message:String) {
var style:UIAlertController.Style = .alert
let deviceIdiom = UIScreen.main.traitCollection.userInterfaceIdiom
switch deviceIdiom {
case .pad:
style = .alert
default:
break
}
let alert = UIAlertController.init(title: "Alert", message: message, preferredStyle: style)
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
alert.dismiss(animated: false, completion: nil)
}
self.present(alert, animated: true) { () -> Void in
}
}
open override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
func shareAirDropURL(_ u:URL,name:String) {
if !FileManager.default.fileExists(atPath: u.path) {
return
}
let dest = URL.init(fileURLWithPath: NSTemporaryDirectory()+name)
do {
try FileManager.default.copyItem(at: u, to: dest)
}catch let e {
print(e.localizedDescription)
}
let controller = UIActivityViewController(activityItems: [dest],applicationActivities:nil)
if let actv = controller.popoverPresentationController {
actv.barButtonItem = self.navigationItem.rightBarButtonItem
actv.sourceView = self.view
}
controller.completionWithItemsHandler = { (type,complete,items,error) in
do {
try FileManager.default.removeItem(at: dest)
}catch let e {
print(e.localizedDescription)
}
}
self.present(controller, animated: true) { () -> Void in
}
}
override open func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "themeChanged"), object: nil, queue: OperationQueue.main) {[weak self] (noti) in
if let strong = self {
strong.refreshTheme()
}
}
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
func refreshTheme(){
let blackStyle = ProxyGroupSettings.share.wwdcStyle
if blackStyle {
let color3 = UIColor.init(red: 0x26/255.0, green: 0x28/255.0, blue: 0x32/255.0, alpha: 1.0)
self.tableView.backgroundColor = color3
}else {
self.tableView.backgroundColor = UIColor.groupTableViewBackground
}
self.tableView.reloadData()
}
override open func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
refreshTheme()
}
// override public func didReceiveMemoryWarning() {
// super.didReceiveMemoryWarning()
// // Dispose of any resources that can be recreated.
// }
//
// // MARK: - Table view data source
//
// override public func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// // #warning Incomplete implementation, return the number of sections
// return 0
// }
//
// override public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// // #warning Incomplete implementation, return the number of rows
// return 0
// }
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// 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.destination.
// Pass the selected object to the new view controller.
}
*/
// override open func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
// return " "
// }
// override open func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
// return " "
// }
open override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let v = view as! UITableViewHeaderFooterView
if ProxyGroupSettings.share.wwdcStyle {
v.contentView.backgroundColor = UIColor.init(red: 0x2d/255.0, green: 0x30/255.0, blue: 0x3b/255.0, alpha: 1.0)
}else {
v.contentView.backgroundColor = UIColor.groupTableViewBackground
}
}
open override func tableView(_ tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int){
let v = view as! UITableViewHeaderFooterView
if ProxyGroupSettings.share.wwdcStyle {
v.contentView.backgroundColor = UIColor.init(red: 0x2d/255.0, green: 0x30/255.0, blue: 0x3b/255.0, alpha: 1.0)
}else {
v.contentView.backgroundColor = UIColor.groupTableViewBackground
}
}
func alertWithTitle(_ title: String, message: String) -> UIAlertController {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
return alert
}
func showAlert(_ alert: UIAlertController) {
guard self.presentedViewController != nil else {
self.present(alert, animated: true, completion: nil)
return
}
}
func alertForRestorePurchases(_ results: RestoreResults) -> UIAlertController {
if results.restoreFailedPurchases.count > 0 {
print("Restore Failed: \(results.restoreFailedPurchases)")
return alertWithTitle("Restore failed", message: "Unknown error. Please contact support")
} else if results.restoredPurchases.count > 0 {
print("Restore Success: \(results.restoredPurchases)")
return alertWithTitle("Purchases Restored", message: "All purchases have been restored")
} else {
print("Nothing to Restore")
return alertWithTitle("Nothing to restore", message: "No previous purchases were found")
}
}
}
| bsd-3-clause | 37abcfd20cc0b52887f39cd8319468ae | 36.393617 | 166 | 0.632243 | 5.004746 | false | false | false | false |
calkinssean/TIY-Assignments | Day 5/OutaTime/OutaTime/ViewController.swift | 1 | 2174 | //
// ViewController.swift
// OutaTime
//
// Created by Sean Calkins on 2/4/16.
// Copyright © 2016 Sean Calkins. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var timer: NSTimer?
var count: Int = 0
let speed: NSTimeInterval = 0.1
@IBOutlet weak var DestinationTimeLabel: UILabel!
@IBOutlet weak var PresentTimeLabel: UILabel!
@IBOutlet weak var LastTimeDeparted: UILabel!
@IBOutlet weak var SpeedLabel: UILabel!
@IBAction func travelBack(sender: UIButton) {
timer = NSTimer.scheduledTimerWithTimeInterval(speed, target: self, selector: "updateSpeed", userInfo: nil, repeats: true)
updateSpeed()
}
func updateSpeed() {
if count <= 88 {
SpeedLabel.text = "\(count) MPH"
count++
} else {
SpeedLabel.text = "LIGHTNING!"
performSegueWithIdentifier("JRBoy", sender: self)
timer?.invalidate()
}
}
override func viewDidLoad() {
super.viewDidLoad()
dates()
updateSpeed()
}
func dates() {
let today = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMM-dd-yyyy"
let todayString = dateFormatter.stringFromDate(today)
todayString.uppercaseString
PresentTimeLabel.text = todayString
}
@IBAction func getTheDate (segue: UIStoryboardSegue){
if segue.identifier == "getTheDateSegue" {
let dateFromView2 = segue.sourceViewController as! DatePickerViewController
let newStr = dateFromView2.destinationDate
DestinationTimeLabel.text = newStr
}
}
@IBAction func weNeedRoadsAgain (segue: UIStoryboardSegue) {
if segue.identifier == "onTheRoadAgain" {
LastTimeDeparted.text = PresentTimeLabel.text
PresentTimeLabel.text = DestinationTimeLabel.text
count = 0
SpeedLabel.text = "\(count)"
}
}
}
| cc0-1.0 | a5fd6da0b55ca3c0e74d20450da8e72b | 19.894231 | 130 | 0.581684 | 5.125 | false | false | false | false |
ayushn21/AvatarImageView | AvatarImageViewTests/AvatarImageViewTests.swift | 1 | 11979 | //
// AvatarImageViewTests.swift
// AvatarImageViewTests
//
// Created by Ayush Newatia on 10/08/2016.
// Copyright © 2016 Ayush Newatia. All rights reserved.
//
import XCTest
@testable import AvatarImageView
class AvatarImageViewTests: XCTestCase {
let imageRect = CGRect(x: 0, y: 0, width: 100, height: 100)
// MARK:- Avatar Tests
func testSquareImageWithConfiguredAvatar() {
var data = TestData(name: "John Appleseed")
data.avatar = UIImage(namedInTest: "profile_pic")!
var config = TestConfig()
config.shape = .square
let avatarImageView = AvatarImageView(frame: imageRect)
avatarImageView.dataSource = data
let imageData = UIImagePNGRepresentation(avatarImageView.image!)!
let testImageData = UIImagePNGRepresentation(UIImage(namedInTest: "profile_pic")!)!
XCTAssert(imageData == testImageData, "The image data should match")
}
func testRoundImageWithConfiguredAvatar() {
var data = TestData(name: "John Appleseed")
data.avatar = UIImage(namedInTest: "profile_pic")!
var config = TestConfig()
config.shape = .circle
let avatarImageView = AvatarImageView(frame: imageRect)
avatarImageView.configuration = config
avatarImageView.dataSource = data
let imageData = UIImagePNGRepresentation(avatarImageView.image!)!
let testImageData = UIImagePNGRepresentation(UIImage(namedInTest: "profile_pic")!)!
XCTAssert(imageData == testImageData, "The image data should match")
XCTAssert(avatarImageView.layer.cornerRadius == avatarImageView.bounds.width/2 ,"The corner radius should be half the width")
}
/// Incorrectly failing test. Needs fixing
// func testMaskImageWithConfiguredAvatar() {
// var data = TestData(name: "John Appleseed")
// data.avatar = UIImage(namedInTest: "profile_pic")!
//
// var config = TestConfig()
// config.shape = .mask(image: UIImage(namedInTest: "hexagon")!)
//
// let avatarImageView = AvatarImageView(frame: imageRect)
// avatarImageView.configuration = config
// avatarImageView.dataSource = data
//
// let imageData = UIImagePNGRepresentation(avatarImageView.asImage())!
// let testImageData = UIImagePNGRepresentation(UIImage(namedInTest: "profile_pic_hexagon")!)!
//
// avatarImageView.asImage().saveToDesktop()
// XCTAssert(imageData == testImageData, "The image data should match")
// }
// MARK:- Initials Tests With BgColor Set In Data Source
func testInitialsSquareImageWithBgColorConfiguredInDataSource() {
var data = TestData(name: "John Appleseed")
data.bgColor = .blue
var config = TestConfig()
config.shape = .square
let avatarImageView = AvatarImageView(frame: imageRect)
avatarImageView.configuration = config
avatarImageView.dataSource = data
let imageData = UIImagePNGRepresentation(avatarImageView.image!)!
let testImageData = UIImagePNGRepresentation(UIImage(namedInTest: "initials_square_blue")!)!
XCTAssert(imageData == testImageData, "The image data should match")
}
func testInitialsRoundImageWithBgColorConfiguredInDataSource() {
var data = TestData(name: "John Appleseed")
data.bgColor = .blue
var config = TestConfig()
config.shape = .circle
let avatarImageView = AvatarImageView(frame: imageRect)
avatarImageView.configuration = config
avatarImageView.dataSource = data
let imageData = UIImagePNGRepresentation(avatarImageView.image!)!
let testImageData = UIImagePNGRepresentation(UIImage(namedInTest: "initials_circle_blue")!)!
XCTAssert(imageData == testImageData, "The image data should match")
}
func testInitialsMaskImageWithBgColorConfiguredInDataSource() {
var data = TestData(name: "John Appleseed")
data.bgColor = .blue
var config = TestConfig()
config.shape = .mask(image: UIImage(namedInTest: "hexagon")!)
let avatarImageView = AvatarImageView(frame: imageRect)
avatarImageView.configuration = config
avatarImageView.dataSource = data
let imageData = UIImagePNGRepresentation(avatarImageView.asImage())!
let testImageData = UIImagePNGRepresentation(UIImage(namedInTest: "initials_mask_blue")!)!
XCTAssert(imageData == testImageData, "The image data should match")
}
// MARK:- Initials Tests With BgColor Set In Configuration
func testInitialsSquareImageWithBgColorConfiguredInConfiguration() {
let data = TestData(name: "John Appleseed")
var config = TestConfig()
config.shape = .square
let avatarImageView = AvatarImageView(frame: imageRect)
avatarImageView.configuration = config
avatarImageView.dataSource = data
let imageData = UIImagePNGRepresentation(avatarImageView.image!)!
let testImageData = UIImagePNGRepresentation(UIImage(namedInTest: "initials_square")!)!
XCTAssert(imageData == testImageData, "The image data should match")
}
func testInitialsRoundImageWithBgColorConfiguredInConfiguration() {
let data = TestData(name: "John Appleseed")
var config = TestConfig()
config.shape = .circle
let avatarImageView = AvatarImageView(frame: imageRect)
avatarImageView.configuration = config
avatarImageView.dataSource = data
let imageData = UIImagePNGRepresentation(avatarImageView.image!)!
let testImageData = UIImagePNGRepresentation(UIImage(namedInTest: "initials_circle")!)!
XCTAssert(imageData == testImageData, "The image data should match")
}
func testInitialsMaskImageWithBgColorConfiguredInConfiguration() {
let data = TestData(name: "John Appleseed")
var config = TestConfig()
config.shape = .mask(image: UIImage(namedInTest: "hexagon")!)
let avatarImageView = AvatarImageView(frame: imageRect)
avatarImageView.configuration = config
avatarImageView.dataSource = data
let imageData = UIImagePNGRepresentation(avatarImageView.asImage())!
let testImageData = UIImagePNGRepresentation(UIImage(namedInTest: "initials_mask")!)!
XCTAssert(imageData == testImageData, "The image data should match")
}
// MARK:- No Initials Configured Tests
func testSquareImageWithNoInitialsConfigured() {
let data = TestData(name: "")
var config = TestConfig()
config.shape = .square
let avatarImageView = AvatarImageView(frame: imageRect)
avatarImageView.configuration = config
avatarImageView.dataSource = data
let imageData = UIImagePNGRepresentation(avatarImageView.image!)!
let testImageData = UIImagePNGRepresentation(UIImage(namedInTest: "default_square")!)!
XCTAssert(imageData == testImageData, "The image data should match")
}
func testRoundImageWithNoInitialsConfigured() {
let data = TestData(name: "")
var config = TestConfig()
config.shape = .circle
let avatarImageView = AvatarImageView(frame: imageRect)
avatarImageView.configuration = config
avatarImageView.dataSource = data
let imageData = UIImagePNGRepresentation(avatarImageView.asImage())!
let testImageData = UIImagePNGRepresentation(UIImage(namedInTest: "default_circle")!)!
XCTAssert(imageData == testImageData, "The image data should match")
}
func testMaskImageWithNoInitialsConfigured() {
let data = TestData(name: "")
var config = TestConfig()
config.shape = .mask(image: UIImage(namedInTest: "hexagon")!)
let avatarImageView = AvatarImageView(frame: imageRect)
avatarImageView.configuration = config
avatarImageView.dataSource = data
let imageData = UIImagePNGRepresentation(avatarImageView.asImage())!
let testImageData = UIImagePNGRepresentation(UIImage(namedInTest: "default_mask")!)!
XCTAssert(imageData == testImageData, "The image data should match")
}
// MARK:- Test To Check Randomly Generated Color Is Constant Depending on name
func testRandomColorForUser() {
let dataOne = TestData(name: "John Appleseed")
var configOne = TestConfig()
configOne.bgColor = nil
let avatarImageView = AvatarImageView(frame: imageRect)
avatarImageView.configuration = configOne
avatarImageView.dataSource = dataOne
let imageData = UIImagePNGRepresentation(avatarImageView.asImage())!
let testImageData = UIImagePNGRepresentation(UIImage(namedInTest: "initials_random_color")!)!
XCTAssert(imageData == testImageData, "The image data should match")
}
// MARK:- Custom Font Tests
func testSquareImageWithCustomFont() {
let data = TestData(name: "John Appleseed")
var config = TestConfig()
config.shape = .square
config.fontName = "Futura-Medium"
let avatarImageView = AvatarImageView(frame: imageRect)
avatarImageView.configuration = config
avatarImageView.dataSource = data
let imageData = UIImagePNGRepresentation(avatarImageView.image!)!
let testImageData = UIImagePNGRepresentation(UIImage(namedInTest: "custom_font_square")!)!
XCTAssert(imageData == testImageData, "The image data should match")
}
func testCircleImageWithCustomFont() {
let data = TestData(name: "John Appleseed")
var config = TestConfig()
config.shape = .circle
config.fontName = "Futura-Medium"
let avatarImageView = AvatarImageView(frame: imageRect)
avatarImageView.configuration = config
avatarImageView.dataSource = data
let imageData = UIImagePNGRepresentation(avatarImageView.image!)!
let testImageData = UIImagePNGRepresentation(UIImage(namedInTest: "custom_font_circle")!)!
XCTAssert(imageData == testImageData, "The image data should match")
}
func testMaskImageWithCustomFont() {
let data = TestData(name: "John Appleseed")
var config = TestConfig()
config.shape = .mask(image: UIImage(namedInTest: "hexagon")!)
config.fontName = "Futura-Medium"
let avatarImageView = AvatarImageView(frame: imageRect)
avatarImageView.configuration = config
avatarImageView.dataSource = data
let imageData = UIImagePNGRepresentation(avatarImageView.asImage())!
let testImageData = UIImagePNGRepresentation(UIImage(namedInTest: "custom_font_mask")!)!
XCTAssert(imageData == testImageData, "The image data should match")
}
func testImageWithInvalidCustomFont() {
let data = TestData(name: "John Appleseed")
var config = TestConfig()
config.shape = .square
config.fontName = "invalid"
let avatarImageView = AvatarImageView(frame: imageRect)
avatarImageView.configuration = config
avatarImageView.dataSource = data
let imageData = UIImagePNGRepresentation(avatarImageView.image!)!
let testImageData = UIImagePNGRepresentation(UIImage(namedInTest: "invalid_font_square")!)!
XCTAssert(imageData == testImageData, "The image data should match")
}
}
| mit | 3bde3dfb879757a22be77120bf1128e2 | 37.514469 | 133 | 0.656287 | 5.894685 | false | true | false | false |
hoangdang1449/Spendy | Spendy/ReminderCell.swift | 1 | 1700 | //
// RemiderCell.swift
// Spendy
//
// Created by Dave Vo on 9/19/15.
// Copyright (c) 2015 Cheetah. All rights reserved.
//
import UIKit
import SevenSwitch
@objc protocol ReminderCellDelegate {
optional func reminderCell(reminderCell: ReminderCell, didChangeValue value: Bool)
}
class ReminderCell: UITableViewCell {
@IBOutlet weak var iconView: UIImageView!
@IBOutlet weak var categoryLabel: UILabel!
@IBOutlet weak var timesLabel: UILabel!
@IBOutlet weak var switchView: UIView!
var onSwitch: SevenSwitch!
var delegate: ReminderCellDelegate!
override func awakeFromNib() {
super.awakeFromNib()
onSwitch = SevenSwitch(frame: CGRect(x: 0, y: 0, width: 51, height: 31))
onSwitch.thumbTintColor = UIColor.whiteColor()
onSwitch.activeColor = UIColor.clearColor()
onSwitch.inactiveColor = UIColor.clearColor()
onSwitch.onTintColor = UIColor(netHex: 0x55AEED)
onSwitch.borderColor = UIColor(red: 220/255, green: 220/255, blue: 220/255, alpha: 1.0)
onSwitch.shadowColor = UIColor(red: 100/255, green: 100/255, blue: 100/255, alpha: 1.0)
switchView.addSubview(onSwitch)
onSwitch.addTarget(self, action: "switchValueChanged", forControlEvents: UIControlEvents.ValueChanged)
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func switchValueChanged() {
if delegate != nil {
delegate?.reminderCell?(self, didChangeValue: onSwitch.on)
}
}
}
| mit | daf823b9f7e3486572ce85b5a74e0ce9 | 27.813559 | 110 | 0.658824 | 4.509284 | false | false | false | false |
markspanbroek/Shhwift | ShhwiftTests/JsonRpcSpec.swift | 1 | 4233 | // Copyright © 2016 Shhwift. All rights reserved.
import Quick
import Nimble
import Mockingjay
import SwiftyJSON
@testable import Shhwift
class JsonRcpSpec: QuickSpec {
override func spec() {
let url = "http://some.rpc.json.server"
var jsonRpc: JsonRpc!
beforeEach {
jsonRpc = JsonRpc(url: url)
}
describe("call") {
it("connects to the correct url") {
waitUntil { done in
self.interceptRequests(to: url) { request in
expect(request.URL) == NSURL(string: url)
done()
}
jsonRpc.call(method: "") { _, _ in }
}
}
it("sends a JSON-RPC 2.0 request") {
waitUntil { done in
self.interceptJSONRequests(to: url) { json in
expect(json?["jsonrpc"]) == "2.0"
done()
}
jsonRpc.call(method: "") { _, _ in }
}
}
it("includes a JSON-RPC request id") {
waitUntil { done in
self.interceptJSONRequests(to: url) { json in
expect(json?["id"]).toNot(beNil())
done()
}
jsonRpc.call(method: "") { _, _ in }
}
}
it("calls the correct JSON-RPC method") {
waitUntil { done in
self.interceptJSONRequests(to: url) { json in
expect(json?["method"]) == "some_method"
done()
}
jsonRpc.call(method: "some_method") { _, _ in }
}
}
it("sends the correct parameters") {
let parameters = JSON(["some": "parameter"])
waitUntil { done in
self.interceptJSONRequests(to: url) { json in
expect(json?["params"]) == parameters
done()
}
jsonRpc.call(method: "", parameters: parameters) { _, _ in }
}
}
it("returns the correct result") {
self.stubRequests(to: url, result: json(["result": 42]))
waitUntil { done in
jsonRpc.call(method: "") { result, _ in
expect(result) == 42
done()
}
}
}
it("notifies about connection errors") {
let connectionError = NSError(
domain: NSURLErrorDomain,
code: NSURLErrorUnknown,
userInfo: nil
)
self.stubRequests(to: url, result: failure(connectionError))
waitUntil { done in
jsonRpc.call(method: "") { _, error in
expect(error).toNot(beNil())
done()
}
}
}
it("notifies about HTTP errors") {
self.stubRequests(to: url, result: json([], status:404))
waitUntil { done in
jsonRpc.call(method: "") { _, error in
expect(error).toNot(beNil())
done()
}
}
}
it("notifies about JSON-RPC errors") {
let code = -12345
let message = "Something went wrong"
self.stubRequests(
to: url,
result: json(["error": ["code": code, "message": message]])
)
let expectedError = JsonRpcError.CallFailed(
code: code,
message:message
)
waitUntil { done in
jsonRpc.call(method: "") { _, error in
expect(error) == expectedError
done()
}
}
}
}
}
}
| mit | 81c5fc11f28dabf977e0d9a567c03fe7 | 28.388889 | 80 | 0.390359 | 5.620186 | false | false | false | false |
CoderJChen/SWWB | CJWB/CJWB/Classes/Home/HomeModel/CJStatusModel.swift | 1 | 959 | //
// CJStatusModel.swift
// CJWB
//
// Created by 星驿ios on 2017/8/18.
// Copyright © 2017年 CJ. All rights reserved.
//
import UIKit
class CJStatusModel: NSObject {
//MARK:- 属性
var created_at : String?
var source : String?
var text : String?
var mid : Int = 0
var user : CJUserModel?
var pic_urls : [[String : String]]? // 微博的配图
var retweeted_status : CJStatusModel? // 微博对应的转发的微博
init(dict : [String : AnyObject]) {
super.init()
setValuesForKeys(dict)
if let userDict = dict["user"] as? [String : AnyObject] {
user = CJUserModel(dict: userDict)
}
if let retweetedStatusDict = dict["retweeted_status"] as?[String : AnyObject] {
retweeted_status = CJStatusModel(dict: retweetedStatusDict)
}
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {
}
}
| apache-2.0 | 54581e8ce0ac7b2ccb213f974b2f5a2f | 25.228571 | 87 | 0.591503 | 3.923077 | false | false | false | false |
ngageoint/mage-ios | Mage/Mixins/FeedsMap.swift | 1 | 7316 | //
// FeedsMap.swift
// MAGE
//
// Created by Daniel Barela on 2/9/22.
// Copyright © 2022 National Geospatial Intelligence Agency. All rights reserved.
//
import Foundation
import MapKit
protocol FeedItemDelegate {
func addFeedItem(_ feedItem: FeedItem)
func removeFeedItem(_ feedItem: FeedItem)
}
protocol FeedsMap {
var mapView: MKMapView? { get set }
var scheme: MDCContainerScheming? { get set }
var feedsMapMixin: FeedsMapMixin? { get set }
}
class FeedsMapMixin: NSObject, MapMixin {
var feedsMap: FeedsMap
let FEEDITEM_ANNOTATION_VIEW_REUSE_ID = "FEEDITEM_ANNOTATION"
var mapAnnotationFocusedObserver: AnyObject?
var enlargedFeedItem: MKAnnotationView?
var feedItemRetrievers: [String:FeedItemRetriever] = [:]
var currentFeeds: [String] = []
var enlargedAnnotationView: MKAnnotationView?
var userDefaultsEventName: String?
init(feedsMap: FeedsMap) {
self.feedsMap = feedsMap
}
func cleanupMixin() {
feedItemRetrievers.removeAll()
if let mapAnnotationFocusedObserver = mapAnnotationFocusedObserver {
NotificationCenter.default.removeObserver(mapAnnotationFocusedObserver, name: .MapAnnotationFocused, object: nil)
}
mapAnnotationFocusedObserver = nil
if let userDefaultsEventName = userDefaultsEventName {
UserDefaults.standard.removeObserver(self, forKeyPath: userDefaultsEventName)
}
}
func setupMixin() {
if let currentEventId = Server.currentEventId() {
userDefaultsEventName = "selectedFeeds-\(currentEventId)"
UserDefaults.standard.addObserver(self, forKeyPath: userDefaultsEventName!, options: [.new], context: nil)
}
mapAnnotationFocusedObserver = NotificationCenter.default.addObserver(forName: .MapAnnotationFocused, object: nil, queue: .main) { [weak self] notification in
if let notificationObject = (notification.object as? MapAnnotationFocusedNotification), notificationObject.mapView == self?.feedsMap.mapView {
self?.focusAnnotation(annotation: notificationObject.annotation)
} else if notification.object == nil {
self?.focusAnnotation(annotation: nil)
}
}
addFeeds()
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath?.starts(with: "selectedFeeds") == true {
addFeeds()
}
}
func addFeeds() {
guard let currentEventId = Server.currentEventId() else {
return
}
let feedIdsInEvent = UserDefaults.standard.currentEventSelectedFeeds
// remove any feeds that are no longer selected
currentFeeds.removeAll { feedId in
return feedIdsInEvent.contains(feedId)
}
// current feeds is now any that used to be selected but not any more
for feedId in currentFeeds {
feedItemRetrievers.removeValue(forKey: feedId)
if let items = FeedItem.getFeedItems(feedId: feedId, eventId: currentEventId.intValue) {
for item in items where item.isMappable {
feedsMap.mapView?.removeAnnotation(item)
}
}
}
// clear the current feeds
currentFeeds.removeAll()
for feedId in feedIdsInEvent {
guard let retriever = feedItemRetrievers[feedId] ?? {
return FeedItemRetriever.getMappableFeedRetriever(feedId: feedId, eventId: currentEventId, delegate: self)
}() else {
continue
}
feedItemRetrievers[feedId] = retriever
if let items = retriever.startRetriever() {
for item in items where item.isMappable {
feedsMap.mapView?.addAnnotation(item)
}
}
}
currentFeeds.append(contentsOf: feedIdsInEvent)
}
func viewForAnnotation(annotation: MKAnnotation, mapView: MKMapView) -> MKAnnotationView? {
guard let annotation = annotation as? FeedItem else {
return nil
}
let annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: FEEDITEM_ANNOTATION_VIEW_REUSE_ID) ?? {
let annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: FEEDITEM_ANNOTATION_VIEW_REUSE_ID)
annotationView.canShowCallout = false
annotationView.isEnabled = false
annotationView.isUserInteractionEnabled = false
annotation.view = annotationView
return annotationView
}()
FeedItemRetriever.setAnnotationImage(feedItem: annotation, annotationView: annotationView)
annotationView.annotation = annotation
annotationView.accessibilityLabel = "Feed \(annotation.feed?.remoteId ?? "") Item \(annotation.remoteId ?? "")"
annotation.view = annotationView
return annotationView
}
func focusAnnotation(annotation: MKAnnotation?) {
guard let annotation = annotation as? FeedItem,
let annotationView = annotation.view else {
if let enlargedAnnotationView = enlargedAnnotationView {
// shrink the old focused view
UIView.animate(withDuration: 0.5, delay: 0.0, options: .curveEaseInOut) {
enlargedAnnotationView.transform = enlargedAnnotationView.transform.scaledBy(x: 0.5, y: 0.5)
enlargedAnnotationView.centerOffset = CGPoint(x: 0, y: enlargedAnnotationView.centerOffset.y / 2.0)
} completion: { success in
}
self.enlargedAnnotationView = nil
}
return
}
if annotationView == enlargedAnnotationView {
// already focused ignore
return
} else if let enlargedAnnotationView = enlargedAnnotationView {
// shrink the old focused view
UIView.animate(withDuration: 0.5, delay: 0.0, options: .curveEaseInOut) {
enlargedAnnotationView.transform = enlargedAnnotationView.transform.scaledBy(x: 0.5, y: 0.5)
enlargedAnnotationView.centerOffset = CGPoint(x: 0, y: annotationView.centerOffset.y / 2.0)
} completion: { success in
}
}
enlargedAnnotationView = annotationView
UIView.animate(withDuration: 0.5, delay: 0.0, options: .curveEaseInOut) {
annotationView.transform = annotationView.transform.scaledBy(x: 2.0, y: 2.0)
annotationView.centerOffset = CGPoint(x: 0, y: annotationView.centerOffset.y * 2.0)
} completion: { success in
}
}
}
extension FeedsMapMixin : FeedItemDelegate {
func addFeedItem(_ feedItem: FeedItem) {
if (feedItem.isMappable) {
feedsMap.mapView?.addAnnotation(feedItem);
}
}
func removeFeedItem(_ feedItem: FeedItem) {
if (feedItem.isMappable) {
feedsMap.mapView?.removeAnnotation(feedItem);
}
}
}
| apache-2.0 | 766bbd140da1dc9101b175b5f7fdf19d | 39.414365 | 166 | 0.630485 | 5.504138 | false | false | false | false |
DivineDominion/mac-licensing-fastspring-cocoafob | No-Trial-Verify-at-Start/MyNewAppTests/PurchaseLicenseTests.swift | 1 | 1806 | // Copyright (c) 2015-2019 Christian Tietze
//
// See the file LICENSE for copying permission.
import Cocoa
import XCTest
@testable import MyNewApp
class PurchaseLicenseTests: XCTestCase {
var service: PurchaseLicense!
let storeDouble = TestStore()
let registerAppDouble = TestRegisterApp()
override func setUp() {
super.setUp()
service = PurchaseLicense(store: storeDouble, registerApplication: registerAppDouble)
}
func testPurchase_ShowsStore() {
service.purchase()
XCTAssert(storeDouble.didShowStore)
}
func testPurchaseCallback_DelegatesToRegisterApp() {
let name = "The Name!"
let licenseCode = "XXX-123-YYY"
let license = License(name: name, licenseCode: licenseCode)
service.didPurchase(license: license)
let values = registerAppDouble.didRegisterWith
XCTAssertNotNil(values)
if let values = values {
XCTAssertEqual(values.name, name)
XCTAssertEqual(values.licenseCode, licenseCode)
}
}
// MARK: -
class TestStore: Store {
convenience init() {
self.init(storeInfo: StoreInfo(storeId: "", productName: "", productId: "", storeMode: ""), storeWindowController: StoreWindowController())
}
var didShowStore = false
override func showStore() {
didShowStore = true
}
}
class TestRegisterApp: RegisterApplication {
var didRegisterWith: (name: String, licenseCode: String)?
override func register(name: String, licenseCode: String) {
didRegisterWith = (name, licenseCode)
}
}
}
| mit | 1beb8bc2395b261eb7da05060332691d | 24.8 | 151 | 0.596899 | 5.234783 | false | true | false | false |
IngmarStein/swift | stdlib/public/core/Repeat.swift | 4 | 3822 | //===--- Repeat.swift - A Collection that repeats a value N times ---------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A collection whose elements are all identical.
///
/// You create an instance of the `Repeated` collection by calling the
/// `repeatElement(_:count:)` function. The following example creates a
/// collection containing the name "Humperdinck" repeated five times:
///
/// let repeatedName = repeatElement("Humperdinck", count: 5)
/// for name in repeatedName {
/// print(name)
/// }
/// // "Humperdinck"
/// // "Humperdinck"
/// // "Humperdinck"
/// // "Humperdinck"
/// // "Humperdinck"
public struct Repeated<Element> : RandomAccessCollection {
public typealias Indices = CountableRange<Int>
/// A type that represents a valid position in the collection.
///
/// Valid indices consist of the position of every element and a "past the
/// end" position that's not valid for use as a subscript.
public typealias Index = Int
/// Creates an instance that contains `count` elements having the
/// value `repeatedValue`.
internal init(_repeating repeatedValue: Element, count: Int) {
_precondition(count >= 0, "Repetition count should be non-negative")
self.count = count
self.repeatedValue = repeatedValue
}
/// The position of the first element in a nonempty collection.
///
/// In a `Repeated` collection, `startIndex` is always equal to zero. If the
/// collection is empty, `startIndex` is equal to `endIndex`.
public var startIndex: Index {
return 0
}
/// The collection's "past the end" position---that is, the position one
/// greater than the last valid subscript argument.
///
/// In a `Repeated` collection, `endIndex` is always equal to `count`. If the
/// collection is empty, `endIndex` is equal to `startIndex`.
public var endIndex: Index {
return count
}
/// Accesses the element at the specified position.
///
/// - Parameter position: The position of the element to access. `position`
/// must be a valid index of the collection that is not equal to the
/// `endIndex` property.
public subscript(position: Int) -> Element {
_precondition(position >= 0 && position < count, "Index out of range")
return repeatedValue
}
/// The number of elements in this collection.
public let count: Int
/// The value of every element in this collection.
public let repeatedValue: Element
}
/// Creates a collection containing the specified number of the given element.
///
/// The following example creates a `Repeated<Int>` collection containing five
/// zeroes:
///
/// let zeroes = repeatElement(0, count: 5)
/// for x in zeroes {
/// print(x)
/// }
/// // 0
/// // 0
/// // 0
/// // 0
/// // 0
///
/// - Parameters:
/// - element: The element to repeat.
/// - count: The number of times to repeat `element`.
/// - Returns: A collection that contains `count` elements that are all
/// `element`.
public func repeatElement<T>(_ element: T, count n: Int) -> Repeated<T> {
return Repeated(_repeating: element, count: n)
}
@available(*, unavailable, renamed: "Repeated")
public struct Repeat<Element> {}
extension Repeated {
@available(*, unavailable, message: "Please use repeatElement(_:count:) function instead")
public init(count: Int, repeatedValue: Element) {
Builtin.unreachable()
}
}
| apache-2.0 | a42f9d36dc711713df7b69e6b01d9384 | 33.125 | 92 | 0.653846 | 4.333333 | false | false | false | false |
HTWDD/HTWDresden-iOS | HTWDD/Components/Dashboard/ViewModels/DashboardViewModel.swift | 1 | 5060 | //
// DashboardViewModel.swift
// HTWDD
//
// Created by Mustafa Karademir on 30.09.19.
// Copyright © 2019 HTW Dresden. All rights reserved.
//
import Foundation
import RxSwift
enum Dashboards {
case header(model: DashboardHeader)
case lesson(model: Lesson)
case freeDay
case grade(model: DashboardGrade)
case noAuthToken
case noStudyToken
case emptyGrade
case meals(models: [Meal])
}
class DashboardViewModel {
// MARK: - Properties
private let context: HasDashboard
// MARK: - Lifecycle
init(context: HasDashboard) {
self.context = context
}
// MARK: - Data Request
func load() -> Observable<[Dashboards]> {
return Observable
.combineLatest(
requestTimetable()
.observeOn(SerialDispatchQueueScheduler(qos: .background)),
requestGrades()
.observeOn(SerialDispatchQueueScheduler(qos: .background)),
requestMeals()
.observeOn(SerialDispatchQueueScheduler(qos: .background))
) { (timetable: [Dashboards], grades: [Dashboards], meals: [Dashboards]) -> [Dashboards] in
timetable + grades + meals
}
}
func requestTimetable() -> Observable<[Dashboards]> {
return context
.dashboardService
.requestTimetable()
.debug()
.map { (lessons: [Lesson]) -> [Dashboards] in
var result: [Dashboards] = []
result.append(.header(model: DashboardHeader(header: R.string.localizable.scheduleTitle(), subheader: Date().string(format: "EEEE, dd. MMMM"))))
if !lessons.isEmpty {
let currentLesson: Lesson? = lessons
.filter { $0.weeksOnly.contains(Date().weekNumber) }
.filter { $0.day == ((Date().weekDay - 1) % 7) }
.sorted(by: { (lhs, rhs) -> Bool in
lhs.beginTime < rhs.beginTime
})
.filter { $0.endTime >= Date().string(format: "HH:mm:ss") }
.first
if let lesson = currentLesson {
result.append(.lesson(model: lesson))
} else {
result.append(.freeDay)
}
} else {
result.append(.freeDay)
}
return result
}
.catchErrorJustReturn([.header(model: DashboardHeader(header: R.string.localizable.scheduleTitle(), subheader: Date().string(format: "EEEE, dd. MMMM"))), .noStudyToken])
}
private func requestGrades() -> Observable<[Dashboards]> {
return context
.dashboardService
.requestGrades()
.observeOn(SerialDispatchQueueScheduler(qos: .background))
.map { (grades: [Grade]) -> [Dashboards] in
var result: [Dashboards] = []
if !grades.isEmpty {
let totalCredits = grades.map { $0.credits }.reduce(0.0, +)
let totalGrades = grades.map { $0.credits * Double($0.grade ?? 0) }.reduce(0.0, +)
let totalAverage = totalGrades > 0 ? (totalGrades / totalCredits) / 100 : 0.0
let gradesCount = grades.compactMap { $0.grade }.count
let lastGrade = grades.sorted().filter { $0.grade != nil }.last
result.append(.header(model: DashboardHeader(header: R.string.localizable.gradesTitle(), subheader: R.string.localizable.gradesAverage(totalAverage))))
result.append(.grade(model: DashboardGrade(grades: gradesCount, credits: totalCredits, lastGrade: lastGrade)))
} else {
result.append(.header(model: DashboardHeader(header: R.string.localizable.gradesTitle(), subheader: R.string.localizable.gradesAverage(0.0))))
result.append(.emptyGrade)
}
return result
}.catchErrorJustReturn([.header(model: DashboardHeader(header: R.string.localizable.gradesTitle(), subheader: R.string.localizable.gradesAverage(0.0))), .noAuthToken])
}
private func requestMeals() -> Observable<[Dashboards]> {
return context
.dashboardService
.requestMeals()
.observeOn(SerialDispatchQueueScheduler(qos: .background))
.asObservable()
.map { (items: [Meal]) -> [Dashboards] in
var result: [Dashboards] = []
if !items.isEmpty {
result.append(.header(model: DashboardHeader(header: R.string.localizable.canteenTitle(), subheader: "⭐️ Reichenbachstraße")))
result.append(.meals(models: items))
}
return result
}
.catchErrorJustReturn([Dashboards]())
}
}
| gpl-2.0 | dfdacd6a1ff6dbbce168d717645060ea | 40.768595 | 181 | 0.542936 | 5.013889 | false | false | false | false |
Nibelungc/ios-ScrollBar | ios-ScrollBar/ScrollBar.swift | 1 | 10750 | //
// ScrollBar.swift
// ios-ScrollBar
//
// Created by Николай Кагала on 22/06/2017.
// Copyright © 2017 Николай Кагала. All rights reserved.
//
import UIKit
@objc protocol ScrollBarDataSource: class {
@objc optional func view(for scrollBar: ScrollBar) -> UIView
@objc optional func rightOffset(for scrollBarView: UIView, for scrollBar: ScrollBar) -> CGFloat
@objc optional func hintViewCenterXCoordinate(for scrollBar: ScrollBar) -> CGFloat
@objc optional func textForHintView(_ hintView: UIView, at point: CGPoint, for scrollBar: ScrollBar) -> String?
}
struct HintViewAttributes {
var minSize: CGSize
var cornerRadius: CGFloat
var backgroundColor: UIColor
var textColor: UIColor
var font: UIFont
var textPaddings: CGFloat
init(minSize: CGSize = CGSize(width: 76, height: 32),
cornerRadius: CGFloat = 5,
backgroundColor: UIColor = UIColor.black.withAlphaComponent(0.3),
textColor: UIColor = .black,
font: UIFont = .systemFont(ofSize: 15),
textPaddings: CGFloat = 8) {
self.minSize = minSize
self.cornerRadius = cornerRadius
self.backgroundColor = backgroundColor
self.textColor = textColor
self.font = font
self.textPaddings = textPaddings
}
}
struct ScrollBarAttributes {
var minStartSpeedInPoints: CGFloat
var rightOffset: CGFloat
var fadeOutAnimationDuration: TimeInterval
var fadeOutAnimationDelay: TimeInterval
init(minStartSpeedInPoints: CGFloat = 20.0,
rightOffset: CGFloat = 30.0,
fadeOutAnimationDuration: TimeInterval = 0.3,
fadeOutAnimationDelay: TimeInterval = 0.5) {
self.minStartSpeedInPoints = minStartSpeedInPoints
self.rightOffset = rightOffset
self.fadeOutAnimationDuration = fadeOutAnimationDuration
self.fadeOutAnimationDelay = fadeOutAnimationDelay
}
}
class ScrollBar: NSObject {
// MARK: - Public properties
weak var dataSource: ScrollBarDataSource? {
didSet { reload() }
}
private(set) var isFastScrollInProgress = false
var isHidden: Bool = false
var showsHintView = true
var hintViewAttributes = HintViewAttributes() {
didSet { updateHintViewAttributes() }
}
var attributes = ScrollBarAttributes()
// MARK: - Private properties
private var scrollView: UIScrollView
private var scrollBarView: UIView?
private var hintView: UILabel? {
didSet { updateHintViewAttributes() }
}
private var panGestureRecognizer: UIPanGestureRecognizer?
private var contentOffsetObserver: NSKeyValueObservation?
private var fadeOutWorkItem: DispatchWorkItem?
private var lastPanTranslation: CGFloat = 0.0
private var isScrollBarActive = false
private var topBottomInsets: CGFloat {
var insets = scrollView.contentInset.top + scrollView.contentInset.bottom
if #available(iOS 11.0, *) {
insets += scrollView.adjustedContentInset.top + scrollView.adjustedContentInset.bottom
}
return insets
}
// MARK: - Lifecycle
init(scrollView: UIScrollView) {
self.scrollView = scrollView
super.init()
setupObservation()
reload()
}
deinit {
contentOffsetObserver = nil
scrollBarView?.removeFromSuperview()
hintView?.removeFromSuperview()
}
// MARK: - Public
func reload() {
setupScrollBarView()
}
// MARK: - Update UI
private func updateScrollBarView(withYOffset offset: CGFloat, speedInPoints speed: CGFloat) {
guard let scrollBarView = scrollBarView else { return }
guard scrollView.contentSize.height > scrollView.bounds.height, !isHidden else { return }
bringSubviewsToFrontIfNeeded()
guard isScrollBarActive ||
(speed >= attributes.minStartSpeedInPoints) else { return }
isScrollBarActive = true
scrollBarView.alpha = 1.0
let rightOffset = dataSource?.rightOffset?(for: scrollBarView, for: self) ?? attributes.rightOffset
let x = scrollView.bounds.maxX - scrollBarView.bounds.width - rightOffset
let insets = topBottomInsets
let scrollableHeight = scrollView.bounds.height - scrollBarView.bounds.height - insets
let offsetWithInsets = offset + insets
let progress = offsetWithInsets / (scrollView.contentSize.height - scrollView.bounds.height + insets)
let y = offsetWithInsets + (scrollableHeight * progress)
scrollBarView.frame.origin = CGPoint(x: x, y: y)
updateHintView(forScrollBarView: scrollBarView)
scheduleFadeOutAnimation()
}
private func updateHintView(forScrollBarView scrollBarView: UIView) {
hintView?.alpha = (showsHintView && isFastScrollInProgress) ? 1.0 : 0.0
guard showsHintView else { return }
if hintView == nil {
setupHintView()
}
let _hintView = hintView!
let defaultXCoordinate = scrollView.bounds.midX
let x = dataSource?.hintViewCenterXCoordinate?(for: self) ?? defaultXCoordinate
let y = scrollBarView.center.y
let point = CGPoint(x: x, y: y)
if let text = dataSource?.textForHintView?(_hintView, at: point, for: self) {
_hintView.text = text
var size = _hintView.sizeThatFits(hintViewAttributes.minSize)
size.width += hintViewAttributes.textPaddings * 2
size.width = max(hintViewAttributes.minSize.width, size.width)
size.height = max(hintViewAttributes.minSize.height, size.height)
_hintView.frame.size = size
_hintView.center = point
} else {
hintView?.alpha = 0.0
}
}
// MARK: - Setup UI
private func setupScrollBarView() {
removeOldScrollBar()
let scrollBarView = dataSource?.view?(for: self) ?? createDefaultScrollBarView()
scrollBarView.isUserInteractionEnabled = true
scrollView.addSubview(scrollBarView)
scrollBarView.alpha = 0.0
self.scrollBarView = scrollBarView
let gestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(panGestureAction))
scrollBarView.addGestureRecognizer(gestureRecognizer)
scrollView.panGestureRecognizer.require(toFail: gestureRecognizer)
}
private func setupHintView() {
guard hintView == nil else { return }
let _hintView = createDefaultScrollBarHintView()
scrollView.addSubview(_hintView)
_hintView.alpha = 0.0
_hintView.isUserInteractionEnabled = false
hintView = _hintView
}
private func createDefaultScrollBarView() -> UIView {
let size = CGSize(width: 48, height: 48)
let view = UIView(frame: CGRect(origin: .zero, size: size))
view.layer.cornerRadius = size.width / 2.0
view.layer.masksToBounds = true
view.backgroundColor = UIColor.black.withAlphaComponent(0.3)
return view
}
private func createDefaultScrollBarHintView() -> UILabel {
let label = UILabel(frame: .zero)
label.layer.masksToBounds = true
label.textAlignment = .center
return label
}
// MARK: - Actions
@objc private func panGestureAction(gesture: UIPanGestureRecognizer) {
guard let scrollBarView = scrollBarView else { return }
switch gesture.state {
case .began:
lastPanTranslation = 0.0
isFastScrollInProgress = true
case .changed:
let insets = topBottomInsets
let deltaY = gesture.translation(in: scrollView).y - lastPanTranslation
lastPanTranslation = gesture.translation(in: scrollView).y
let scrollableHeight = scrollView.bounds.height - scrollBarView.bounds.height - insets
let contentHeight = scrollView.contentSize.height - scrollView.bounds.height + insets
let maxYOffset = scrollView.contentSize.height - scrollView.bounds.height
let deltaContentY = deltaY * (contentHeight / scrollableHeight)
var y = scrollView.contentOffset.y + deltaContentY
y = max(-insets, (min(maxYOffset, y)))
let newOffset = CGPoint(x: scrollView.contentOffset.x, y: y)
scrollView.setContentOffset(newOffset, animated: false)
case .ended, .cancelled, .failed:
isFastScrollInProgress = false
default:
return
}
}
// MARK: - Private
private func setupObservation() {
contentOffsetObserver = scrollView.observe(\.contentOffset, options: [.new, .old]) {
[unowned self] _, change in
guard let newOffset = change.newValue,
let oldOffset = change.oldValue else { return }
let speedInPoints = abs(oldOffset.y - newOffset.y)
self.updateScrollBarView(withYOffset: newOffset.y, speedInPoints: speedInPoints)
}
}
private func scheduleFadeOutAnimation() {
let views = [scrollBarView, hintView]
fadeOutWorkItem?.cancel()
fadeOutWorkItem = DispatchWorkItem {
[weak self] in
guard let sSelf = self else { return }
guard !sSelf.isFastScrollInProgress else { return }
UIView.animate(withDuration: sSelf.attributes.fadeOutAnimationDuration) {
views.forEach { $0?.alpha = 0.0 }
sSelf.isScrollBarActive = false
}
}
DispatchQueue.main.asyncAfter(deadline: .now() + attributes.fadeOutAnimationDelay,
execute: fadeOutWorkItem!)
}
private func removeOldScrollBar() {
guard let oldScrollBarView = scrollBarView else { return }
oldScrollBarView.removeFromSuperview()
if let oldGesture = panGestureRecognizer {
oldScrollBarView.removeGestureRecognizer(oldGesture)
}
}
private func updateHintViewAttributes() {
guard let hintView = hintView else { return }
hintView.backgroundColor = hintViewAttributes.backgroundColor
hintView.layer.cornerRadius = hintViewAttributes.cornerRadius
hintView.frame.size = hintViewAttributes.minSize
hintView.textColor = hintViewAttributes.textColor
hintView.font = hintViewAttributes.font
}
private func bringSubviewsToFrontIfNeeded() {
let views = [hintView, scrollBarView].compactMap { $0 }
views.forEach { scrollView.bringSubview(toFront: $0) }
}
}
| mit | 2fabee22ef2aab88b162377a01f02a07 | 36.890459 | 115 | 0.65187 | 5.223088 | false | false | false | false |
zjjzmw1/speedxSwift | speedxSwift/Pods/HanekeSwift/Haneke/String+Haneke.swift | 30 | 1728 | //
// String+Haneke.swift
// Haneke
//
// Created by Hermes Pique on 8/30/14.
// Copyright (c) 2014 Haneke. All rights reserved.
//
import Foundation
extension String {
func escapedFilename() -> String {
let originalString = self as NSString as CFString
let charactersToLeaveUnescaped = " \\" as NSString as CFString // TODO: Add more characters that are valid in paths but not in URLs
let legalURLCharactersToBeEscaped = "/:" as NSString as CFString
let encoding = CFStringBuiltInEncodings.UTF8.rawValue
let escapedPath = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, originalString, charactersToLeaveUnescaped, legalURLCharactersToBeEscaped, encoding)
return escapedPath as NSString as String
}
func MD5String() -> String {
guard let data = self.dataUsingEncoding(NSUTF8StringEncoding) else {
return self
}
let MD5Calculator = MD5(data)
let MD5Data = MD5Calculator.calculate()
let resultBytes = UnsafeMutablePointer<CUnsignedChar>(MD5Data.bytes)
let resultEnumerator = UnsafeBufferPointer<CUnsignedChar>(start: resultBytes, count: MD5Data.length)
let MD5String = NSMutableString()
for c in resultEnumerator {
MD5String.appendFormat("%02x", c)
}
return MD5String as String
}
func MD5Filename() -> String {
let MD5String = self.MD5String()
let pathExtension = (self as NSString).pathExtension
if pathExtension.characters.count > 0 {
return (MD5String as NSString).stringByAppendingPathExtension(pathExtension) ?? MD5String
} else {
return MD5String
}
}
} | mit | 0e6eda378c344ffa7b1ec37ca6a94792 | 35.020833 | 171 | 0.674769 | 5.067449 | false | false | false | false |
digipost/ios | Digipost/UploadGuideViewController.swift | 1 | 3130 | //
// Copyright (C) Posten Norge AS
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
class UploadGuideViewController: UIViewController {
@IBOutlet weak var uploadImage: UIImageView!
@IBOutlet weak var horizontalUploadImage: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = NSLocalizedString("upload guide navgationtiem title", comment: "title for navigation item on upload")
self.uploadImage.accessibilityLabel = NSLocalizedString("upload guide image accessability hint", comment: "when user taps on image, this text should be read")
self.uploadImage.isAccessibilityElement = true
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "kFolderViewControllerNavigatedInList"), object: nil, queue: nil) { note in
self.dismiss(animated: false, completion: nil)
}
if (UIDevice.current.userInterfaceIdiom == .pad ){
uploadImage.image = UIImage.localizedImage(UIInterfaceOrientation.portrait)
} else {
uploadImage.image = UIImage.localizedImage(UIApplication.shared.statusBarOrientation)
self.setImageForOrientation(UIApplication.shared.statusBarOrientation)
}
view.updateConstraints()
}
deinit {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "kFolderViewControllerNavigatedInList"), object: nil)
}
func setImageForOrientation(_ forOrientation: UIInterfaceOrientation){
if let horizontalImage = horizontalUploadImage {
if (UIInterfaceOrientationIsLandscape(forOrientation)){
horizontalImage.isHidden = false
} else {
horizontalImage.isHidden = true
}
}
if let verticalImage = uploadImage {
if (UIInterfaceOrientationIsLandscape(forOrientation)){
verticalImage.isHidden = true
} else {
verticalImage.isHidden = false
}
}
}
override func willRotate(to toInterfaceOrientation: UIInterfaceOrientation, duration: TimeInterval) {
if (UIDevice.current.userInterfaceIdiom == .pad ){
uploadImage.image = UIImage.localizedImage(UIInterfaceOrientation.portrait)
}else {
uploadImage.image = UIImage.localizedImage(toInterfaceOrientation)
horizontalUploadImage.image = UIImage.localizedImage(toInterfaceOrientation)
setImageForOrientation(toInterfaceOrientation)
}
}
}
| apache-2.0 | 949ec2388fab48ccf53afd63e8aec8fe | 43.084507 | 166 | 0.692652 | 5.481611 | false | false | false | false |
cornerstonecollege/402 | boyoung_chae/DebuggingAndViews/DebuggingAndViews/ViewController.swift | 1 | 1704 | //
// ViewController.swift
// DebuggingAndViews
//
// Created by Boyoung on 2016-10-12.
// Copyright © 2016 Boyoung. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// for _ in 1...10 {
// something()
// }
createView()
}
// func something() {
// print("aaa")
// }
func createView() {
// let rect = CGRect(x: 0, y: 0, width: 100, height: 100)
// let label = UILabel(frame: rect)
// label.backgroundColor = UIColor.red
// label.text = "I'm a label."
// label.center = self.view.center
// self.view.addSubview(label)
// Root view is window. Inside window, each one is subview.
let label = UILabel()
label.text = "I'm a label."
label.sizeToFit() // The size will fit the text.
label.center = CGPoint(x: 50, y: 50)
label.backgroundColor = UIColor.blue
self.view.addSubview(label)
let btnRect = CGRect(x: 100, y: 100, width: 100, height: 100)
let button = UIButton(frame: btnRect)
button.backgroundColor = UIColor.green
// Right way
button.setTitle("I'm a button.", for: UIControlState.normal)
// Wrong way
// button.titleLabel?.text = "I'm a button."
self.view.addSubview(button)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| gpl-3.0 | 25adf0ba7ecb15adef1e3c5651b543e9 | 26.467742 | 80 | 0.56606 | 4.163814 | false | false | false | false |
AchillesWang/Swift | TypeCasting/TypeCasting/main.swift | 1 | 3106 | //
// main.swift
// TypeCasting
//
// Created by WangXiaoXiang on 14-7-22.
// Copyright (c) 2014年 Next. All rights reserved.
//
import Foundation
class MediaItem{
var name:String
init(name:String){
self.name = name;
}
}
class Movie:MediaItem{
var director: String
init(name: String, director: String) {
self.director = director
super.init(name: name)
}
}
class Song: MediaItem {
var artist: String
init(name: String, artist: String) {
self.artist = artist
super.init(name: name)
}
}
let library = [
Movie(name: "花瓶", director: "汪潇翔"),
Song(name: "七里香", artist: "周杰伦"),
Movie(name: "变形金刚4", director: "汪潇翔"),
Song(name: "bili", artist: "潘玮柏"),
Song(name: "打呼", artist: "潘玮柏")
]
var movieCount = 0
var songCount = 0
for item in library{
if item is Song{
++songCount;
}else if item is Movie{
++movieCount;
}
}
println("电影:\(movieCount),歌曲:\(songCount)")
println("\n\n")
for item in library{
if let movie = item as? Movie{
println("电影:\(movie.name),导演:\(movie.director)")
}else if let song = item as? Song{
println("歌名:\(song.name),演唱者:\(song.artist)")
}
}
let someObjects:[AnyObject] = [
Song(name: "小苹果", artist: "筷子兄弟"),
//平凡之路 朴树
Song(name: "平凡之路", artist: "朴树"),
//想唱就唱 TFBOYS
Song(name: "想唱就唱", artist: "TFBOYS")
]
println("\n\n")
for object in someObjects[0...1]{
let song = object as Song
println("歌名:\(song.name),演唱者:\(song.artist)")
// let movie = object as Movie
// println("电影:\(movie.name),导演:\(movie.director)")
}
println("\n\nsong in someObjects as [Song]")
for song in someObjects as [Song]{
println("歌名:\(song.name),演唱者:\(song.artist)")
}
var things = [Any]();
things.append(0)
things.append(0.0)
things.append(42)
things.append(3.14159)
things.append("hello")
things.append((3.0, 5.0))
things.append(Movie(name: "一路向西", director: "Ivan Reitman"))
things.append(Song(name: "小苹果", artist: "筷子兄弟"))
println("\n\n")
for thing in things{
switch thing{
// case 0 as Int:
// println("zero as an Int")
// case 0 as Double:
// println("zero as an Double")
case let someInt as Int:
println("an integer value of \(someInt)")
case let someDouble as Double where someDouble>0:
println("a positive double value of \(someDouble)")
case is Double:
println("some other double value that I don't want to print")
case let someString as String:
println("a string value of \"\(someString)\"")
case let (x, y) as (Double, Double):
println("an (x, y) point at \(x), \(y)")
case let movie as Movie:
println("a movie called '\(movie.name)', dir. \(movie.director)")
case let song as Song:
println("歌名:\(song.name),演唱者:\(song.artist)")
default:
println("其他类型")
}
}
| apache-2.0 | 0cfb58dfdc49df4c629c83cf0acc5e14 | 21.167939 | 73 | 0.598829 | 3.132686 | false | false | false | false |
dclelland/AudioKit | AudioKit/Common/User Interface/AKRollingOutputPlot.swift | 1 | 2676 | //
// AKRollingOutputPlot.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright © 2016 AudioKit. All rights reserved.
//
import Foundation
/// Wrapper class for plotting audio from the final mix in a rolling plot
@IBDesignable
public class AKRollingOutputPlot: EZAudioPlot {
internal func setupNode() {
AudioKit.engine.outputNode.installTapOnBus(0, bufferSize: bufferSize, format: nil) { [weak self] (buffer, time) -> Void in
if let strongSelf = self {
buffer.frameLength = strongSelf.bufferSize
let offset = Int(buffer.frameCapacity - buffer.frameLength)
let tail = buffer.floatChannelData[0]
strongSelf.updateBuffer(&tail[offset],
withBufferSize: strongSelf.bufferSize)
}
}
}
internal var bufferSize: UInt32 = 1024
deinit {
AudioKit.engine.outputNode.removeTapOnBus(0)
}
/// Initialize the plot in a frame
///
/// - parameter frame: CGRect in which to draw the plot
///
override public init(frame: CGRect) {
super.init(frame: frame)
setupNode()
}
/// Initialize the plot in a frame with a different buffer size
///
/// - parameter frame: CGRect in which to draw the plot
/// - parameter bufferSize: size of the buffer - raise this number if the device struggles with generating the waveform
///
public init(frame: CGRect, bufferSize: Int) {
super.init(frame: frame)
self.bufferSize = UInt32(bufferSize)
setupNode()
}
/// Required coder-based initialization (for use with Interface Builder)
///
/// - parameter coder: NSCoder
///
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupNode()
}
/// Create a View with the plot (usually for playgrounds)
///
/// - returns: AKView
/// - parameter width: Width of the view
/// - parameter height: Height of the view
///
public static func createView(width: CGFloat = 1000.0, height: CGFloat = 500.0) -> AKView {
let frame = CGRect(x: 0.0, y: 0.0, width: width, height: height)
let plot = AKRollingOutputPlot(frame: frame)
plot.plotType = .Rolling
plot.backgroundColor = AKColor.whiteColor()
plot.color = AKColor.greenColor()
plot.shouldFill = true
plot.shouldMirror = true
plot.shouldCenterYAxis = true
let containerView = AKView(frame: frame)
containerView.addSubview(plot)
return containerView
}
}
| mit | 118d090d0058054892fa2b19fc24c7f8 | 31.228916 | 130 | 0.620561 | 4.660279 | false | false | false | false |
TheTekton/Malibu | MalibuTests/Specs/Request/MethodRequestableSpec.swift | 1 | 3465 | @testable import Malibu
import Quick
import Nimble
class MethodRequestableSpec: QuickSpec {
override func spec() {
describe("GETRequestable") {
var request: GETRequestable!
beforeEach {
request = GETRequest()
}
describe("#method") {
it("is .GET") {
expect(request.method).to(equal(Method.GET))
}
}
describe("#contentType") {
it("is .Query") {
expect(request.contentType).to(equal(ContentType.Query))
}
}
describe("#etagPolicy") {
it("is .Enabled") {
expect(request.etagPolicy).to(equal(ETagPolicy.Enabled))
}
}
}
describe("POSTRequestable") {
var request: POSTRequestable!
beforeEach {
request = POSTRequest()
}
describe("#method") {
it("is .POST") {
expect(request.method).to(equal(Method.POST))
}
}
describe("#contentType") {
it("is .JSON") {
expect(request.contentType).to(equal(ContentType.JSON))
}
}
describe("#etagPolicy") {
it("is .Disabled") {
expect(request.etagPolicy).to(equal(ETagPolicy.Disabled))
}
}
}
describe("PUTRequestable") {
var request: PUTRequestable!
beforeEach {
request = PUTRequest()
}
describe("#method") {
it("is .PUT") {
expect(request.method).to(equal(Method.PUT))
}
}
describe("#contentType") {
it("is .JSON") {
expect(request.contentType).to(equal(ContentType.JSON))
}
}
describe("#etagPolicy") {
it("is .Enabled") {
expect(request.etagPolicy).to(equal(ETagPolicy.Enabled))
}
}
}
describe("PATCHRequestable") {
var request: PATCHRequestable!
beforeEach {
request = PATCHRequest()
}
describe("#method") {
it("is .PATCH") {
expect(request.method).to(equal(Method.PATCH))
}
}
describe("#contentType") {
it("is .JSON") {
expect(request.contentType).to(equal(ContentType.JSON))
}
}
describe("#etagPolicy") {
it("is .Enabled") {
expect(request.etagPolicy).to(equal(ETagPolicy.Enabled))
}
}
}
describe("DELETERequestable") {
var request: DELETERequestable!
beforeEach {
request = DELETERequest()
}
describe("#method") {
it("is .DELETE") {
expect(request.method).to(equal(Method.DELETE))
}
}
describe("#contentType") {
it("is .Query") {
expect(request.contentType).to(equal(ContentType.Query))
}
}
describe("#etagPolicy") {
it("is .Disabled") {
expect(request.etagPolicy).to(equal(ETagPolicy.Disabled))
}
}
}
describe("HEADRequestable") {
var request: HEADRequestable!
beforeEach {
request = HEADRequest()
}
describe("#method") {
it("is .HEAD") {
expect(request.method).to(equal(Method.HEAD))
}
}
describe("#contentType") {
it("is .Query") {
expect(request.contentType).to(equal(ContentType.Query))
}
}
describe("#etagPolicy") {
it("is .Disabled") {
expect(request.etagPolicy).to(equal(ETagPolicy.Disabled))
}
}
}
}
}
| mit | da291e9a7af2666a1de04944fd032c0c | 20.128049 | 67 | 0.522078 | 4.402795 | false | false | false | false |
vmanot/swift-package-manager | Sources/Utility/Git.swift | 1 | 3095 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import class Foundation.ProcessInfo
import Basic
extension Version {
static func vprefix(_ string: String) -> Version? {
if string.first == "v" {
return Version(string: String(string.dropFirst()))
} else {
return nil
}
}
}
public class Git {
/// Compute the version -> tag mapping from a list of input `tags`.
public static func convertTagsToVersionMap(_ tags: [String]) -> [Version: String] {
// First, check if we need to restrict the tag set to version-specific tags.
var knownVersions: [Version: String] = [:]
for versionSpecificKey in Versioning.currentVersionSpecificKeys {
for tag in tags where tag.hasSuffix(versionSpecificKey) {
let specifier = String(tag.dropLast(versionSpecificKey.count))
if let version = Version(string: specifier) ?? Version.vprefix(specifier) {
knownVersions[version] = tag
}
}
// If we found tags at this version-specific key, we are done.
if !knownVersions.isEmpty {
return knownVersions
}
}
// Otherwise, look for normal tags.
for tag in tags {
if let version = Version(string: tag) {
knownVersions[version] = tag
}
}
// If we didn't find any versions, look for 'v'-prefixed ones.
//
// FIXME: We should match both styles simultaneously.
if knownVersions.isEmpty {
for tag in tags {
if let version = Version.vprefix(tag) {
knownVersions[version] = tag
}
}
}
return knownVersions
}
/// A shell command to run for Git. Can be either a name or a path.
public static var tool: String = "git"
/// Returns true if the git reference name is well formed.
public static func checkRefFormat(ref: String) -> Bool {
do {
let result = try Process.popen(args: "git", "check-ref-format", "--allow-onelevel", ref)
return result.exitStatus == .terminated(code: 0)
} catch {
return false
}
}
/// Returns the environment variables for launching the git subprocess.
///
/// This contains the current environment with custom overrides for using
/// git from swift build.
public static var environment: [String: String] {
var env = ProcessInfo.processInfo.environment
// Disable terminal prompts in git. This will make git error out and return
// when it needs a user/pass etc instead of hanging the terminal (SR-3981).
env["GIT_TERMINAL_PROMPT"] = "0"
return env
}
}
| apache-2.0 | 33eaf371666b80f590101ab38c937788 | 34.574713 | 100 | 0.603231 | 4.689394 | false | false | false | false |
anatoliyv/InfoView | Example/InfoView/ViewController.swift | 1 | 6245 | //
// ViewController.swift
// InfoView
//
// Created by Anatoliy Voropay on 05/11/2016.
// Copyright (c) 2016 Anatoliy Voropay. All rights reserved.
//
import UIKit
import InfoView
class ViewController: UIViewController {
@IBOutlet var segmentedControl: UISegmentedControl!
@IBOutlet var button1: UIButton!
@IBOutlet var button2: UIButton!
@IBOutlet var button3: UIButton!
@IBOutlet var button4: UIButton!
@IBOutlet var button5: UIButton!
@IBOutlet var button6: UIButton!
@IBOutlet var button7: UIButton!
@IBOutlet var button8: UIButton!
private lazy var buttons: [UIButton] = {
return [ self.button1, self.button2, self.button3, self.button4, self.button5, self.button6, self.button7, self.button8 ]
}()
private let gradient: CAGradientLayer = CAGradientLayer()
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
gradient.frame = view.bounds
}
override func viewDidLoad() {
super.viewDidLoad()
let colorTop = UIColor(red: 178.0/255.0, green: 219.0/255.0, blue: 191.0/255.0, alpha: 1.0)
let colorBottom = UIColor(red: 36.0/255.0, green: 123.0/255.0, blue: 160.0/255.0, alpha: 1.0)
gradient.colors = [colorTop.CGColor, colorBottom.CGColor]
gradient.locations = [0.0 , 1.0]
gradient.startPoint = CGPoint(x: 0.0, y: 0.0)
gradient.endPoint = CGPoint(x: 0.0, y: 1.0)
gradient.frame = CGRect(x: 0.0, y: 0.0, width: self.view.frame.size.width, height: self.view.frame.size.height)
view.layer.insertSublayer(gradient, atIndex: 0)
segmentedControl.tintColor = .whiteColor()
segmentedControl.setTitle("None", forSegmentAtIndex: 0)
segmentedControl.setTitle("FadeIn", forSegmentAtIndex: 1)
segmentedControl.setTitle("Fade & Scale", forSegmentAtIndex: 2)
segmentedControl.setTitle("Custom", forSegmentAtIndex: 3)
view.backgroundColor = .grayColor()
let image = UIImage(named: "Info")
for button in buttons {
button.setImage(image!, forState: .Normal)
button.adjustsImageWhenHighlighted = false
}
}
@IBAction func pressedButton(button: UIButton) {
var text = ""
var arrowPosition: InfoViewArrowPosition = .Automatic
var animation: InfoViewAnimation = .FadeIn
switch segmentedControl.selectedSegmentIndex {
case 0:
text = "Animation: None"
animation = .None
case 1:
text = "Animation: Fade In"
animation = .FadeIn
case 2:
text = "Animation: Fade In and Scale"
animation = .FadeInAndScale
case 3:
text = "Animation: Fade In"
animation = .FadeIn
default:
break
}
let infoView = InfoView(text: text, arrowPosition: arrowPosition, animation: animation, delegate: self)
switch button {
case button1:
text += "\nArrow: left side."
arrowPosition = .Left
if segmentedControl.selectedSegmentIndex == 3 {
text += "\nCustom font and corner radius."
infoView.font = UIFont.boldSystemFontOfSize(18)
infoView.layer.cornerRadius = 15
}
case button2:
text += "\nArrow: right side."
arrowPosition = .Right
if segmentedControl.selectedSegmentIndex == 3 {
text += "\nCustom font and color."
infoView.font = UIFont(name: "AvenirNextCondensed-Regular", size: 16)
infoView.textColor = UIColor.grayColor()
}
case button3:
text += "\nArrow: on the top."
arrowPosition = .Top
if segmentedControl.selectedSegmentIndex == 3 {
text += "\nCustom background and shadow colors."
text += "\nWill hide after 5 seconds delay automatically"
infoView.backgroundColor = UIColor.blackColor()
infoView.textColor = UIColor.whiteColor()
infoView.layer.shadowColor = UIColor.whiteColor().CGColor
infoView.hideAfterDelay = 5
}
case button4:
text += "\nArrow from a bottom and much more text.\n\nLorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book."
arrowPosition = .Bottom
case button5:
text += "\nAutomaticaly selected arrow position"
arrowPosition = .Automatic
case button6:
text += "\nAutomaticaly selected arrow position and much more text.\n\nLorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book."
arrowPosition = .Automatic
case button7:
text += "\nAutomaticaly selected arrow position"
arrowPosition = .Automatic
case button8:
text += "\nAutomaticaly selected arrow position and much more text.\n\nLorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book."
arrowPosition = .Automatic
default:
break
}
infoView.text = text
infoView.show(onView: view, centerView: button)
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
extension ViewController: InfoViewDelegate {
func infoViewDidHide(view: InfoView) {
print("infoViewDidHide")
}
func infoViewDidShow(view: InfoView) {
print("infoViewDidShow")
}
func infoViewWillHide(view: InfoView) {
print("infoViewWillHide")
}
func infoViewWillShow(view: InfoView) {
print("infoViewWillShow")
}
}
| mit | 958c4a1484b300644170e1b533da7e16 | 35.30814 | 329 | 0.629143 | 4.720333 | false | false | false | false |
B-Lach/PocketCastsKit | SharedSource/Model/PCKEpisode.swift | 1 | 2608 | //
// PCKEpisode.swift
// PocketCastsKit
//
// Created by Benny Lach on 17.08.17.
// Copyright © 2017 Benny Lach. All rights reserved.
//
import Foundation
/// Represents an Episode of a Podcast in PocketCasts
public struct PCKEpisode {
public let id: Int
public let uuid: UUID
public let url: URL
public let publishedAt: Date
public let duration: Int
public let fileType: String
public let title: String
public let size: Int
public let podcastId: Int
public let podcastUUID: UUID?
public var playingStatus: Int
public var playedUpTo: Int
public var isDeleted: Bool?
public var starred: Bool?
}
extension PCKEpisode: Decodable {
private enum CodingKeys: String, CodingKey {
case id
case uuid
case url
case publishedAt = "published_at"
case duration
case fileType = "file_type"
case title
case size
case podcastId = "podcast_id"
case podcastUUID = "podcast_uuid"
case playingStatus = "playing_status"
case playedUpTo = "played_up_to"
case isDeleted = "is_deleted"
case starred
}
public init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
id = try values.decodeIfPresent(Int.self, forKey: .id) ?? -1
uuid = try values.decode(UUID.self, forKey: .uuid)
url = try values.decode(URL.self, forKey: .url)
publishedAt = try values.decode(Date.self, forKey: .publishedAt)
// Sometimes duration is a String sometimes it's an Integer and it can be null as well - oh boy 😒
if let durationString = try? values.decode(String.self, forKey: .duration) {
duration = Int(durationString) ?? -1
} else {
duration = try values.decodeIfPresent(Int.self, forKey: .duration) ?? -1
}
fileType = try values.decode(String.self, forKey: .fileType)
title = try values.decode(String.self, forKey: .title)
size = try values.decode(Int.self, forKey: .size)
podcastId = try values.decodeIfPresent(Int.self, forKey: .podcastId) ?? -1
podcastUUID = try values.decodeIfPresent(UUID.self, forKey: .podcastUUID)
playingStatus = try values.decodeIfPresent(Int.self, forKey: .playingStatus) ?? -1
playedUpTo = try values.decodeIfPresent(Int.self, forKey: .playedUpTo) ?? -1
isDeleted = try values.decodeIfPresent(Bool.self, forKey: .isDeleted)
starred = try values.decodeIfPresent(Bool.self, forKey: .starred)
}
}
| mit | 05992a37d2aa1ab610ce6ea26cc73a8d | 35.166667 | 106 | 0.646313 | 4.146497 | false | false | false | false |
iAugux/TinderSwipeCardsSwift | TinderSwipeCardsSwift/DraggableViewBackground.swift | 2 | 4711 | //
// DraggableViewBackground.swift
// TinderSwipeCardsSwift
//
// Created by Gao Chao on 4/30/15.
// Copyright (c) 2015 gcweb. All rights reserved.
//
import Foundation
import UIKit
class DraggableViewBackground: UIView, DraggableViewDelegate {
var exampleCardLabels: [String]!
var allCards: [DraggableView]!
let MAX_BUFFER_SIZE = 2
let CARD_HEIGHT: CGFloat = 386
let CARD_WIDTH: CGFloat = 290
var cardsLoadedIndex: Int!
var loadedCards: [DraggableView]!
var menuButton: UIButton!
var messageButton: UIButton!
var checkButton: UIButton!
var xButton: UIButton!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
super.layoutSubviews()
self.setupView()
exampleCardLabels = ["first", "second", "third", "fourth", "last"]
allCards = []
loadedCards = []
cardsLoadedIndex = 0
self.loadCards()
}
func setupView() -> Void {
self.backgroundColor = UIColor(red: 0.92, green: 0.93, blue: 0.95, alpha: 1)
xButton = UIButton(frame: CGRectMake((self.frame.size.width - CARD_WIDTH)/2 + 35, self.frame.size.height/2 + CARD_HEIGHT/2 + 10, 59, 59))
xButton.setImage(UIImage(named: "xButton"), forState: UIControlState.Normal)
xButton.addTarget(self, action: "swipeLeft", forControlEvents: UIControlEvents.TouchUpInside)
checkButton = UIButton(frame: CGRectMake(self.frame.size.width/2 + CARD_WIDTH/2 - 85, self.frame.size.height/2 + CARD_HEIGHT/2 + 10, 59, 59))
checkButton.setImage(UIImage(named: "checkButton"), forState: UIControlState.Normal)
checkButton.addTarget(self, action: "swipeRight", forControlEvents: UIControlEvents.TouchUpInside)
self.addSubview(xButton)
self.addSubview(checkButton)
}
func createDraggableViewWithDataAtIndex(index: NSInteger) -> DraggableView {
let draggableView = DraggableView(frame: CGRectMake((self.frame.size.width - CARD_WIDTH)/2, (self.frame.size.height - CARD_HEIGHT)/2, CARD_WIDTH, CARD_HEIGHT))
draggableView.information.text = exampleCardLabels[index]
draggableView.delegate = self
return draggableView
}
func loadCards() -> Void {
if exampleCardLabels.count > 0 {
let numLoadedCardsCap = exampleCardLabels.count > MAX_BUFFER_SIZE ? MAX_BUFFER_SIZE : exampleCardLabels.count
for var i = 0; i < exampleCardLabels.count; i++ {
let newCard: DraggableView = self.createDraggableViewWithDataAtIndex(i)
allCards.append(newCard)
if i < numLoadedCardsCap {
loadedCards.append(newCard)
}
}
for var i = 0; i < loadedCards.count; i++ {
if i > 0 {
self.insertSubview(loadedCards[i], belowSubview: loadedCards[i - 1])
} else {
self.addSubview(loadedCards[i])
}
cardsLoadedIndex = cardsLoadedIndex + 1
}
}
}
func cardSwipedLeft(card: UIView) -> Void {
loadedCards.removeAtIndex(0)
if cardsLoadedIndex < allCards.count {
loadedCards.append(allCards[cardsLoadedIndex])
cardsLoadedIndex = cardsLoadedIndex + 1
self.insertSubview(loadedCards[MAX_BUFFER_SIZE - 1], belowSubview: loadedCards[MAX_BUFFER_SIZE - 2])
}
}
func cardSwipedRight(card: UIView) -> Void {
loadedCards.removeAtIndex(0)
if cardsLoadedIndex < allCards.count {
loadedCards.append(allCards[cardsLoadedIndex])
cardsLoadedIndex = cardsLoadedIndex + 1
self.insertSubview(loadedCards[MAX_BUFFER_SIZE - 1], belowSubview: loadedCards[MAX_BUFFER_SIZE - 2])
}
}
func swipeRight() -> Void {
if loadedCards.count <= 0 {
return
}
let dragView: DraggableView = loadedCards[0]
dragView.overlayView.setMode(GGOverlayViewMode.GGOverlayViewModeRight)
UIView.animateWithDuration(0.2, animations: {
() -> Void in
dragView.overlayView.alpha = 1
})
dragView.rightClickAction()
}
func swipeLeft() -> Void {
if loadedCards.count <= 0 {
return
}
let dragView: DraggableView = loadedCards[0]
dragView.overlayView.setMode(GGOverlayViewMode.GGOverlayViewModeLeft)
UIView.animateWithDuration(0.2, animations: {
() -> Void in
dragView.overlayView.alpha = 1
})
dragView.leftClickAction()
}
} | mit | ede6f8ec129bd4cb5b8bf9c63f74a8a1 | 34.969466 | 167 | 0.623222 | 4.614104 | false | false | false | false |
lastobelus/eidolon | Kiosk/Sale Artwork Details/SaleArtworkDetailsViewController.swift | 5 | 17202 | import UIKit
import ORStackView
import Artsy_UILabels
import Artsy_UIFonts
import ReactiveCocoa
import Artsy_UIButtons
import Swift_RAC_Macros
import SDWebImage
class SaleArtworkDetailsViewController: UIViewController {
var allowAnimations = true
var auctionID = AppSetup.sharedState.auctionID
var saleArtwork: SaleArtwork!
var showBuyersPremiumCommand = { () -> RACCommand in
appDelegate().showBuyersPremiumCommand()
}
class func instantiateFromStoryboard(storyboard: UIStoryboard) -> SaleArtworkDetailsViewController {
return storyboard.viewControllerWithID(.SaleArtworkDetail) as! SaleArtworkDetailsViewController
}
lazy var artistInfoSignal: RACSignal = {
let signal = XAppRequest(.Artwork(id: self.saleArtwork.artwork.id)).filterSuccessfulStatusCodes().mapJSON()
return signal.replayLast()
}()
@IBOutlet weak var metadataStackView: ORTagBasedAutoStackView!
@IBOutlet weak var additionalDetailScrollView: ORStackScrollView!
var buyersPremium: () -> (BuyersPremium?) = { appDelegate().sale.buyersPremium }
override func viewDidLoad() {
super.viewDidLoad()
setupMetadataView()
setupAdditionalDetailStackView()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue == .ZoomIntoArtwork {
let nextViewController = segue.destinationViewController as! SaleArtworkZoomViewController
nextViewController.saleArtwork = saleArtwork
}
}
enum MetadataStackViewTag: Int {
case LotNumberLabel = 1
case ArtistNameLabel
case ArtworkNameLabel
case ArtworkMediumLabel
case ArtworkDimensionsLabel
case ImageRightsLabel
case EstimateTopBorder
case EstimateLabel
case EstimateBottomBorder
case CurrentBidLabel
case CurrentBidValueLabel
case NumberOfBidsPlacedLabel
case BidButton
case BuyersPremium
}
@IBAction func backWasPressed(sender: AnyObject) {
navigationController?.popViewControllerAnimated(true)
}
private func setupMetadataView() {
enum LabelType {
case Serif
case SansSerif
case ItalicsSerif
case Bold
}
func label(type: LabelType, tag: MetadataStackViewTag, fontSize: CGFloat = 16.0) -> UILabel {
let label: UILabel = { () -> UILabel in
switch type {
case .Serif:
return ARSerifLabel()
case .SansSerif:
return ARSansSerifLabel()
case .ItalicsSerif:
return ARItalicsSerifLabel()
case .Bold:
let label = ARSerifLabel()
label.font = UIFont.sansSerifFontWithSize(label.font.pointSize)
return label
}
}()
label.lineBreakMode = .ByWordWrapping
label.font = label.font.fontWithSize(fontSize)
label.tag = tag.rawValue
label.preferredMaxLayoutWidth = 276
return label
}
let hasLotNumber = (saleArtwork.lotNumber != nil)
if let _ = saleArtwork.lotNumber {
let lotNumberLabel = label(.SansSerif, tag: .LotNumberLabel)
lotNumberLabel.font = lotNumberLabel.font.fontWithSize(12)
metadataStackView.addSubview(lotNumberLabel, withTopMargin: "0", sideMargin: "0")
RAC(lotNumberLabel, "text") <~ saleArtwork.viewModel.lotNumberSignal
}
if let artist = artist() {
let artistNameLabel = label(.SansSerif, tag: .ArtistNameLabel)
artistNameLabel.text = artist.name
metadataStackView.addSubview(artistNameLabel, withTopMargin: hasLotNumber ? "10" : "0", sideMargin: "0")
}
let artworkNameLabel = label(.ItalicsSerif, tag: .ArtworkNameLabel)
artworkNameLabel.text = "\(saleArtwork.artwork.title), \(saleArtwork.artwork.date)"
metadataStackView.addSubview(artworkNameLabel, withTopMargin: "10", sideMargin: "0")
if let medium = saleArtwork.artwork.medium {
if medium.isNotEmpty {
let mediumLabel = label(.Serif, tag: .ArtworkMediumLabel)
mediumLabel.text = medium
metadataStackView.addSubview(mediumLabel, withTopMargin: "22", sideMargin: "0")
}
}
if saleArtwork.artwork.dimensions.count > 0 {
let dimensionsLabel = label(.Serif, tag: .ArtworkDimensionsLabel)
dimensionsLabel.text = (saleArtwork.artwork.dimensions as NSArray).componentsJoinedByString("\n")
metadataStackView.addSubview(dimensionsLabel, withTopMargin: "5", sideMargin: "0")
}
retrieveImageRights().filter { (imageRights) -> Bool in
return (imageRights as? String).isNotNilNotEmpty
}.subscribeNext { [weak self] (imageRights) -> Void in
if (imageRights as! String).isNotEmpty {
let rightsLabel = label(.Serif, tag: .ImageRightsLabel)
rightsLabel.text = imageRights as? String
self?.metadataStackView.addSubview(rightsLabel, withTopMargin: "22", sideMargin: "0")
}
}
let estimateTopBorder = UIView()
estimateTopBorder.constrainHeight("1")
estimateTopBorder.tag = MetadataStackViewTag.EstimateTopBorder.rawValue
metadataStackView.addSubview(estimateTopBorder, withTopMargin: "22", sideMargin: "0")
let estimateLabel = label(.Serif, tag: .EstimateLabel)
estimateLabel.text = saleArtwork.viewModel.estimateString
metadataStackView.addSubview(estimateLabel, withTopMargin: "15", sideMargin: "0")
let estimateBottomBorder = UIView()
estimateBottomBorder.constrainHeight("1")
estimateBottomBorder.tag = MetadataStackViewTag.EstimateBottomBorder.rawValue
metadataStackView.addSubview(estimateBottomBorder, withTopMargin: "10", sideMargin: "0")
rac_signalForSelector("viewDidLayoutSubviews").subscribeNext { [weak estimateTopBorder, weak estimateBottomBorder] (_) -> Void in
estimateTopBorder?.drawDottedBorders()
estimateBottomBorder?.drawDottedBorders()
}
let hasBidsSignal = RACObserve(saleArtwork, "highestBidCents").map{ (cents) -> AnyObject! in
return (cents != nil) && ((cents as? NSNumber ?? 0) > 0)
}
let currentBidLabel = label(.Serif, tag: .CurrentBidLabel)
RAC(currentBidLabel, "text") <~ RACSignal.`if`(hasBidsSignal, then: RACSignal.`return`("Current Bid:"), `else`: RACSignal.`return`("Starting Bid:"))
metadataStackView.addSubview(currentBidLabel, withTopMargin: "22", sideMargin: "0")
let currentBidValueLabel = label(.Bold, tag: .CurrentBidValueLabel, fontSize: 27)
RAC(currentBidValueLabel, "text") <~ saleArtwork.viewModel.currentBidSignal()
metadataStackView.addSubview(currentBidValueLabel, withTopMargin: "10", sideMargin: "0")
let numberOfBidsPlacedLabel = label(.Serif, tag: .NumberOfBidsPlacedLabel)
RAC(numberOfBidsPlacedLabel, "text") <~ saleArtwork.viewModel.numberOfBidsWithReserveSignal
metadataStackView.addSubview(numberOfBidsPlacedLabel, withTopMargin: "10", sideMargin: "0")
let bidButton = ActionButton()
bidButton.rac_signalForControlEvents(.TouchUpInside).subscribeNext { [weak self] (_) -> Void in
if let strongSelf = self {
strongSelf.bid(strongSelf.auctionID, saleArtwork: strongSelf.saleArtwork, allowAnimations: strongSelf.allowAnimations)
}
}
saleArtwork.viewModel.forSaleSignal.subscribeNext { [weak bidButton] (forSale) -> Void in
let forSale = forSale as! Bool
let title = forSale ? "BID" : "SOLD"
bidButton?.setTitle(title, forState: .Normal)
}
RAC(bidButton, "enabled") <~ saleArtwork.viewModel.forSaleSignal
bidButton.tag = MetadataStackViewTag.BidButton.rawValue
metadataStackView.addSubview(bidButton, withTopMargin: "40", sideMargin: "0")
if let _ = buyersPremium() {
let buyersPremiumView = UIView()
buyersPremiumView.tag = MetadataStackViewTag.BuyersPremium.rawValue
let buyersPremiumLabel = ARSerifLabel()
buyersPremiumLabel.font = buyersPremiumLabel.font.fontWithSize(16)
buyersPremiumLabel.text = "This work has a "
buyersPremiumLabel.textColor = .artsyHeavyGrey()
let buyersPremiumButton = ARButton()
let title = "buyers premium"
let attributes: [String: AnyObject] = [ NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue, NSFontAttributeName: buyersPremiumLabel.font ];
let attributedTitle = NSAttributedString(string: title, attributes: attributes)
buyersPremiumButton.setTitle(title, forState: .Normal)
buyersPremiumButton.titleLabel?.attributedText = attributedTitle;
buyersPremiumButton.setTitleColor(.artsyHeavyGrey(), forState: .Normal)
buyersPremiumButton.rac_command = showBuyersPremiumCommand()
buyersPremiumView.addSubview(buyersPremiumLabel)
buyersPremiumView.addSubview(buyersPremiumButton)
buyersPremiumLabel.alignTop("0", leading: "0", bottom: "0", trailing: nil, toView: buyersPremiumView)
buyersPremiumLabel.alignBaselineWithView(buyersPremiumButton, predicate: nil)
buyersPremiumButton.alignAttribute(.Left, toAttribute: .Right, ofView: buyersPremiumLabel, predicate: "0")
metadataStackView.addSubview(buyersPremiumView, withTopMargin: "30", sideMargin: "0")
}
metadataStackView.bottomMarginHeight = CGFloat(NSNotFound)
}
private func setupImageView(imageView: UIImageView) {
if let image = saleArtwork.artwork.defaultImage {
// We'll try to retrieve the thumbnail image from the cache. If we don't have it, we'll set the background colour to grey to indicate that we're downloading it.
let key = SDWebImageManager.sharedManager().cacheKeyForURL(image.thumbnailURL())
let thumbnailImage = SDImageCache.sharedImageCache().imageFromDiskCacheForKey(key)
if thumbnailImage == nil {
imageView.backgroundColor = .artsyLightGrey()
}
imageView.sd_setImageWithURL(image.fullsizeURL(), placeholderImage: thumbnailImage, completed: { (image, _, _, _) -> Void in
// If the image was successfully downloaded, make sure we aren't still displaying grey.
if image != nil {
imageView.backgroundColor = .clearColor()
}
})
let heightConstraintNumber = { () -> CGFloat in
if let aspectRatio = image.aspectRatio {
if aspectRatio != 0 {
return min(400, CGFloat(538) / aspectRatio)
}
}
return 400
}()
imageView.constrainHeight( "\(heightConstraintNumber)" )
imageView.contentMode = .ScaleAspectFit
imageView.userInteractionEnabled = true
let recognizer = UITapGestureRecognizer()
imageView.addGestureRecognizer(recognizer)
recognizer.rac_gestureSignal().subscribeNext() { [weak self] (_) in
self?.performSegue(.ZoomIntoArtwork)
return
}
}
}
private func setupAdditionalDetailStackView() {
enum LabelType {
case Header
case Body
}
func label(type: LabelType, layoutSignal: RACSignal? = nil) -> UILabel {
let (label, fontSize) = { () -> (UILabel, CGFloat) in
switch type {
case .Header:
return (ARSansSerifLabel(), 14)
case .Body:
return (ARSerifLabel(), 16)
}
}()
label.font = label.font.fontWithSize(fontSize)
label.lineBreakMode = .ByWordWrapping
layoutSignal?.take(1).subscribeNext { [weak label] (_) -> Void in
if let label = label {
label.preferredMaxLayoutWidth = CGRectGetWidth(label.frame)
}
}
return label
}
additionalDetailScrollView.stackView.bottomMarginHeight = 40
let imageView = UIImageView()
additionalDetailScrollView.stackView.addSubview(imageView, withTopMargin: "0", sideMargin: "40")
setupImageView(imageView)
let additionalInfoHeaderLabel = label(.Header)
additionalInfoHeaderLabel.text = "Additional Information"
additionalDetailScrollView.stackView.addSubview(additionalInfoHeaderLabel, withTopMargin: "20", sideMargin: "40")
if let blurb = saleArtwork.artwork.blurb {
let blurbLabel = label(.Body, layoutSignal: additionalDetailScrollView.stackView.rac_signalForSelector("layoutSubviews"))
blurbLabel.attributedText = MarkdownParser().attributedStringFromMarkdownString( blurb )
additionalDetailScrollView.stackView.addSubview(blurbLabel, withTopMargin: "22", sideMargin: "40")
}
let additionalInfoLabel = label(.Body, layoutSignal: additionalDetailScrollView.stackView.rac_signalForSelector("layoutSubviews"))
additionalInfoLabel.attributedText = MarkdownParser().attributedStringFromMarkdownString( saleArtwork.artwork.additionalInfo )
additionalDetailScrollView.stackView.addSubview(additionalInfoLabel, withTopMargin: "22", sideMargin: "40")
retrieveAdditionalInfo().filter { (info) -> Bool in
return (info as? String).isNotNilNotEmpty
}.subscribeNext { (info) -> Void in
additionalInfoLabel.attributedText = MarkdownParser().attributedStringFromMarkdownString( info as! String )
}
if let artist = artist() {
retrieveArtistBlurb().filter { (blurb) -> Bool in
return (blurb as? String).isNotNilNotEmpty
}.subscribeNext { [weak self] (blurb) -> Void in
if self == nil {
return
}
let aboutArtistHeaderLabel = label(.Header)
aboutArtistHeaderLabel.text = "About \(artist.name)"
self?.additionalDetailScrollView.stackView.addSubview(aboutArtistHeaderLabel, withTopMargin: "22", sideMargin: "40")
let aboutAristLabel = label(.Body, layoutSignal: self?.additionalDetailScrollView.stackView.rac_signalForSelector("layoutSubviews"))
aboutAristLabel.attributedText = MarkdownParser().attributedStringFromMarkdownString( blurb as? String )
self?.additionalDetailScrollView.stackView.addSubview(aboutAristLabel, withTopMargin: "22", sideMargin: "40")
}
}
}
private func artist() -> Artist? {
return saleArtwork.artwork.artists?.first
}
private func retrieveImageRights() -> RACSignal {
let artwork = saleArtwork.artwork
if let imageRights = artwork.imageRights {
return RACSignal.`return`(imageRights)
} else {
return artistInfoSignal.map{ (json) -> AnyObject! in
return json["image_rights"]
}.filter({ (imageRights) -> Bool in
imageRights != nil
}).doNext{ (imageRights) -> Void in
artwork.imageRights = imageRights as? String
return
}
}
}
private func retrieveAdditionalInfo() -> RACSignal {
let artwork = saleArtwork.artwork
if let additionalInfo = artwork.additionalInfo {
return RACSignal.`return`(additionalInfo)
} else {
return artistInfoSignal.map{ (json) -> AnyObject! in
return json["additional_information"]
}.filter({ (info) -> Bool in
info != nil
}).doNext{ (info) -> Void in
artwork.additionalInfo = info as? String
return
}
}
}
private func retrieveArtistBlurb() -> RACSignal {
if let artist = artist() {
if let blurb = artist.blurb {
return RACSignal.`return`(blurb)
} else {
let artistSignal = XAppRequest(.Artist(id: artist.id)).filterSuccessfulStatusCodes().mapJSON()
return artistSignal.map{ (json) -> AnyObject! in
return json["blurb"]
}.filter({ (blurb) -> Bool in
blurb != nil
}).doNext{ (blurb) -> Void in
artist.blurb = blurb as? String
return
}
}
} else {
return RACSignal.empty()
}
}
}
| mit | abdccbfb72cffa1b564108ecda533f76 | 42.112782 | 172 | 0.628241 | 5.866985 | false | false | false | false |
Ricky-Choi/IUExtensions | IUExtensions/StringExtension.swift | 1 | 1591 | //
// StringExtension.swift
//
//
// Created by Jaeyoung Choi on 2015. 10. 20..
// Copyright © 2015년 Appcid. All rights reserved.
//
import Foundation
extension String {
public func trim() -> String {
return trimmingCharacters(in: .whitespacesAndNewlines)
}
public func filter(predicate: (Character) -> Bool) -> String {
var res = String()
for c in self {
if (predicate(c)) {
res.append(c)
}
}
return res
}
public func trimInside() -> String {
let trimString = self.trim()
return trimString.filter { return $0 != Character(" ") }
}
public func uppercasedFirstCharacterOnly() -> String {
guard count > 1 else {
return uppercased()
}
let secondIndex = index(after: startIndex)
return self[..<secondIndex].uppercased() + self[secondIndex...]
}
}
extension NSAttributedString {
public func addingAttribute(_ name: NSAttributedString.Key, value: Any, range: NSRange) -> NSAttributedString {
let mutable = mutableCopy() as! NSMutableAttributedString
mutable.addAttribute(name, value: value, range: range)
return mutable.copy() as! NSAttributedString
}
public func addingAttributes(_ attrs: [NSAttributedString.Key : Any], range: NSRange) -> NSAttributedString {
let mutable = mutableCopy() as! NSMutableAttributedString
mutable.addAttributes(attrs, range: range)
return mutable.copy() as! NSAttributedString
}
}
| mit | bb580d67b6991414f60b4cdadaa1520e | 28.407407 | 115 | 0.612091 | 4.871166 | false | false | false | false |
mozilla-mobile/firefox-ios | Client/Application/AppContainer.swift | 2 | 3963 | // 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 os.log
import Dip
import Storage
/// This is our concrete dependency container. It holds all dependencies / services the app would need through
/// a session.
class AppContainer: ServiceProvider {
static let shared: ServiceProvider = AppContainer()
/// The item holding registered services.
private var container: DependencyContainer?
private init() {
container = bootstrapContainer()
}
/// Any services needed by the client can be resolved by calling this.
func resolve<T>() -> T {
do {
return try container?.resolve(T.self) as! T
} catch {
/// If a service we thought was registered can't be resolved, this is likely an issue within
/// bootstrapping. Double check your registrations and their types.
os_log(.error, "Could not resolve the requested type!")
/// We've made bad assumptions, and there's something very wrong with container setup! This is fatal.
fatalError("\(error)")
}
}
// MARK: - Misc helpers
/// Prepares the container by registering all services for the app session.
/// Insert a dependency when needed, otherwise it floats in memory.
/// - Returns: A bootstrapped `DependencyContainer`.
private func bootstrapContainer() -> DependencyContainer {
return DependencyContainer { container in
do {
unowned let container = container
/// Since Profile's usage is at the very beginning (and is a dependency for others in this container)
/// we give this an `eagerSingleton` scope, forcing the instance to exist ON container boostrap.
container.register(.eagerSingleton) { () -> Profile in
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
return appDelegate.profile
} else {
return BrowserProfile(
localName: "profile",
syncDelegate: UIApplication.shared.syncDelegate
) as Profile
}
}
container.register(.singleton) { () -> TabManager in
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
return appDelegate.tabManager
} else {
return TabManager(
profile: try container.resolve(),
imageStore: DiskImageStore(
files: (try container.resolve() as Profile).files,
namespace: "TabManagerScreenshots",
quality: UIConstants.ScreenshotQuality)
)
}
}
container.register(.singleton) { () -> ThemeManager in
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
return appDelegate.themeManager
} else {
return DefaultThemeManager(appDelegate: UIApplication.shared.delegate)
}
}
container.register(.singleton) {
return RatingPromptManager(profile: try container.resolve())
}
try container.bootstrap()
} catch {
os_log(.error, "We couldn't resolve something inside the container!")
/// If resolution of one item fails, the entire object graph won't be resolved. This is a fatal error.
fatalError("\(error)")
}
}
}
}
| mpl-2.0 | 21e246c9321d408a43fedf9d7bfc6a1e | 40.28125 | 118 | 0.559425 | 5.888559 | false | false | false | false |
loudnate/LoopKit | LoopKit/InsulinKit/InsulinDeliveryStore.swift | 1 | 17448 | //
// InsulinDeliveryStore.swift
// InsulinKit
//
// Copyright © 2017 LoopKit Authors. All rights reserved.
//
import HealthKit
import CoreData
import os.log
enum InsulinDeliveryStoreResult<T> {
case success(T)
case failure(Error)
}
/// Manages insulin dose data from HealthKit
///
/// Scheduled doses (e.g. a bolus or temporary basal) shouldn't be written to HealthKit until they've
/// been delivered into the patient, which means its common for the HealthKit data to slightly lag
/// behind the dose data used for algorithmic calculation.
///
/// HealthKit data isn't a substitute for an insulin pump's diagnostic event history, but doses fetched
/// from HealthKit can reduce the amount of repeated communication with an insulin pump.
public class InsulinDeliveryStore: HealthKitSampleStore {
/// Notification posted when cached data was modifed.
static let cacheDidChange = NSNotification.Name(rawValue: "com.loopkit.InsulinDeliveryStore.cacheDidChange")
private let insulinType = HKQuantityType.quantityType(forIdentifier: .insulinDelivery)!
private let queue = DispatchQueue(label: "com.loopkit.InsulinKit.InsulinDeliveryStore.queue", qos: .utility)
private let log = OSLog(category: "InsulinDeliveryStore")
/// The most-recent end date for a basal sample written by LoopKit
/// Should only be accessed on dataAccessQueue
private var lastBasalEndDate: Date? {
didSet {
test_lastBasalEndDateDidSet?()
}
}
internal var test_lastBasalEndDateDidSet: (() -> Void)?
/// The interval of insulin delivery data to keep in cache
public let cacheLength: TimeInterval
public let cacheStore: PersistenceController
public init(
healthStore: HKHealthStore,
cacheStore: PersistenceController,
observationEnabled: Bool = true,
cacheLength: TimeInterval = 24 /* hours */ * 60 /* minutes */ * 60 /* seconds */,
test_currentDate: Date? = nil
) {
self.cacheStore = cacheStore
self.cacheLength = cacheLength
super.init(
healthStore: healthStore,
type: insulinType,
observationStart: (test_currentDate ?? Date()).addingTimeInterval(-cacheLength),
observationEnabled: observationEnabled,
test_currentDate: test_currentDate
)
cacheStore.onReady { (error) in
// Should we do something here?
}
}
public override func processResults(from query: HKAnchoredObjectQuery, added: [HKSample], deleted: [HKDeletedObject], error: Error?) {
guard error == nil else {
return
}
queue.async {
// Added samples
let samples = ((added as? [HKQuantitySample]) ?? []).filterDateRange(self.earliestCacheDate, nil)
var cacheChanged = false
if self.addCachedObjects(for: samples) {
cacheChanged = true
}
// Deleted samples
for sample in deleted {
if self.deleteCachedObject(forSampleUUID: sample.uuid) {
cacheChanged = true
}
}
let cachePredicate = NSPredicate(format: "startDate < %@", self.earliestCacheDate as NSDate)
self.purgeCachedObjects(matching: cachePredicate)
if cacheChanged || self.lastBasalEndDate == nil {
self.updateLastBasalEndDate()
}
// New data not written by LoopKit (see `MetadataKeyHasLoopKitOrigin`) should be assumed external to what could be fetched as PumpEvent data.
// That external data could be factored into dose computation with some modification:
// An example might be supplemental injections in cases of extended exercise periods without a pump
if cacheChanged {
NotificationCenter.default.post(name: InsulinDeliveryStore.cacheDidChange, object: self)
}
}
}
public override var preferredUnit: HKUnit! {
return super.preferredUnit
}
}
// MARK: - Adding data
extension InsulinDeliveryStore {
func addReconciledDoses(_ doses: [DoseEntry], from device: HKDevice?, syncVersion: Int, completion: @escaping (_ result: InsulinDeliveryStoreResult<Bool>) -> Void) {
let unit = HKUnit.internationalUnit()
var samples: [HKQuantitySample] = []
cacheStore.managedObjectContext.performAndWait {
samples = doses.compactMap { (dose) -> HKQuantitySample? in
guard let syncIdentifier = dose.syncIdentifier else {
log.error("Attempted to add a dose with no syncIdentifier: %{public}@", String(reflecting: dose))
return nil
}
guard self.cacheStore.managedObjectContext.cachedInsulinDeliveryObjectsWithSyncIdentifier(syncIdentifier, fetchLimit: 1).count == 0 else {
log.default("Skipping adding dose due to existing cached syncIdentifier: %{public}@", syncIdentifier)
return nil
}
return HKQuantitySample(
type: insulinType,
unit: unit,
dose: dose,
device: device,
syncVersion: syncVersion
)
}
}
guard samples.count > 0 else {
completion(.success(true))
return
}
healthStore.save(samples) { (success, error) in
if let error = error {
completion(.failure(error))
} else {
self.queue.async {
if samples.count > 0 {
self.addCachedObjects(for: samples)
if self.lastBasalEndDate != nil {
self.updateLastBasalEndDate()
}
}
completion(.success(true))
}
}
}
}
}
extension InsulinDeliveryStore {
/// Returns the end date of the most recent basal sample
///
/// - Parameters:
/// - completion: A closure called when the date has been retrieved
/// - result: The date
func getLastBasalEndDate(_ completion: @escaping (_ result: InsulinDeliveryStoreResult<Date>) -> Void) {
queue.async {
switch self.lastBasalEndDate {
case .some(let date):
completion(.success(date))
case .none:
// TODO: send a proper error
completion(.failure(DoseStore.DoseStoreError.configurationError))
}
}
}
/// Returns doses from HealthKit, or the Core Data cache if unavailable
///
/// - Parameters:
/// - start: The earliest dose startDate to include
/// - end: The latest dose startDate to include
/// - isChronological: Whether the doses should be returned in chronological order
/// - completion: A closure called when the doses have been retrieved
/// - doses: An ordered array of doses
func getCachedDoses(start: Date, end: Date? = nil, isChronological: Bool = true, _ completion: @escaping (_ doses: [DoseEntry]) -> Void) {
// If we were asked for an unbounded query, or we're within our cache duration, only return what's in the cache
guard start > .distantPast, start <= earliestCacheDate else {
self.queue.async {
completion(self.getCachedDoseEntries(start: start, end: end, isChronological: isChronological))
}
return
}
getDoses(start: start, end: end, isChronological: isChronological) { (result) in
switch result {
case .success(let doses):
completion(doses)
case .failure:
// Expected when database is inaccessible
self.queue.async {
completion(self.getCachedDoseEntries(start: start, end: end, isChronological: isChronological))
}
}
}
}
}
// MARK: - HealthKit
extension InsulinDeliveryStore {
private func getDoses(start: Date, end: Date? = nil, isChronological: Bool = true, _ completion: @escaping (_ result: InsulinDeliveryStoreResult<[DoseEntry]>) -> Void) {
getSamples(start: start, end: end, isChronological: isChronological) { (result) in
switch result {
case .failure(let error):
completion(.failure(error))
case .success(let samples):
completion(.success(samples.compactMap { $0.dose }))
}
}
}
private func getSamples(start: Date, end: Date? = nil, isChronological: Bool = true, _ completion: @escaping (_ result: InsulinDeliveryStoreResult<[HKQuantitySample]>) -> Void) {
let predicate = HKQuery.predicateForSamples(withStart: start, end: end, options: [])
getSamples(matching: predicate, isChronological: isChronological, completion)
}
private func getSamples(matching predicate: NSPredicate, isChronological: Bool, _ completion: @escaping (_ result: InsulinDeliveryStoreResult<[HKQuantitySample]>) -> Void) {
let sort = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: isChronological)
let query = HKSampleQuery(sampleType: insulinType, predicate: predicate, limit: HKObjectQueryNoLimit, sortDescriptors: [sort]) { (query, samples, error) in
if let error = error {
completion(.failure(error))
} else if let samples = samples as? [HKQuantitySample] {
completion(.success(samples))
} else {
assertionFailure("Unknown return configuration from query \(query)")
}
}
healthStore.execute(query)
}
}
// MARK: - Core Data
extension InsulinDeliveryStore {
private var earliestCacheDate: Date {
return currentDate(timeIntervalSinceNow: -cacheLength)
}
/// Creates new cached insulin delivery objects from samples if they're not already cached and within the date interval
///
/// - Parameter samples: The samples to cache
/// - Returns: Whether new cached objects were created
@discardableResult
private func addCachedObjects(for samples: [
HKQuantitySample]) -> Bool {
dispatchPrecondition(condition: .onQueue(queue))
var created = false
cacheStore.managedObjectContext.performAndWait {
for sample in samples {
guard
sample.startDate.timeIntervalSince(currentDate()) > -self.cacheLength,
self.cacheStore.managedObjectContext.cachedInsulinDeliveryObjectsWithUUID(sample.uuid, fetchLimit: 1).count == 0
else {
continue
}
let object = CachedInsulinDeliveryObject(context: self.cacheStore.managedObjectContext)
object.update(from: sample)
created = true
}
if created {
self.cacheStore.save()
}
}
return created
}
private func updateLastBasalEndDate() {
dispatchPrecondition(condition: .onQueue(queue))
var endDate: Date?
cacheStore.managedObjectContext.performAndWait {
let request: NSFetchRequest<CachedInsulinDeliveryObject> = CachedInsulinDeliveryObject.fetchRequest()
let basalPredicate = NSPredicate(format: "reason == %d", HKInsulinDeliveryReason.basal.rawValue)
let sourcePredicate = NSPredicate(format: "hasLoopKitOrigin == true")
let predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [basalPredicate, sourcePredicate])
request.predicate = predicate
request.sortDescriptors = [NSSortDescriptor(key: "endDate", ascending: false)]
request.fetchLimit = 1
do {
let objects = try self.cacheStore.managedObjectContext.fetch(request)
endDate = objects.first?.endDate
} catch let error {
self.log.error("Unable to fetch latest insulin delivery objects: %@", String(describing: error))
}
}
self.lastBasalEndDate = endDate ?? healthStore.earliestPermittedSampleDate()
}
/// Fetches doses from the cache that occur on or after a given start date
///
/// - Parameters:
/// - start: The earliest endDate to retrieve
/// - end: The latest startDate to retrieve
/// - isChronological: Whether the sort order is ascending by start date
/// - Returns: An ordered array of dose entries
private func getCachedDoseEntries(start: Date, end: Date? = nil, isChronological: Bool = true) -> [DoseEntry] {
dispatchPrecondition(condition: .onQueue(queue))
let startPredicate = NSPredicate(format: "endDate >= %@", start as NSDate)
let predicate: NSPredicate
if let end = end {
let endPredicate = NSPredicate(format: "startDate <= %@", end as NSDate)
predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [startPredicate, endPredicate])
} else {
predicate = startPredicate
}
return getCachedDoseEntries(matching: predicate, isChronological: isChronological)
}
/// Fetches doses from the cache that match the given predicate
///
/// - Parameters:
/// - predicate: The predicate to apply to the objects
/// - isChronological: Whether the sort order is ascending by start date
/// - Returns: An ordered array of dose entries
private func getCachedDoseEntries(matching predicate: NSPredicate? = nil, isChronological: Bool = true) -> [DoseEntry] {
dispatchPrecondition(condition: .onQueue(queue))
var doses: [DoseEntry] = []
cacheStore.managedObjectContext.performAndWait {
let request: NSFetchRequest<CachedInsulinDeliveryObject> = CachedInsulinDeliveryObject.fetchRequest()
request.predicate = predicate
request.sortDescriptors = [NSSortDescriptor(key: "startDate", ascending: isChronological)]
do {
let objects = try self.cacheStore.managedObjectContext.fetch(request)
doses = objects.compactMap { $0.dose }
} catch let error {
self.log.error("Error fetching CachedInsulinDeliveryObjects: %{public}@", String(describing: error))
}
}
return doses
}
/// Deletes objects from the cache that match the given sample UUID
///
/// - Parameter uuid: The UUID of the sample to delete
/// - Returns: Whether the deletion was made
private func deleteCachedObject(forSampleUUID uuid: UUID) -> Bool {
dispatchPrecondition(condition: .onQueue(queue))
var deleted = false
cacheStore.managedObjectContext.performAndWait {
for object in self.cacheStore.managedObjectContext.cachedInsulinDeliveryObjectsWithUUID(uuid) {
self.cacheStore.managedObjectContext.delete(object)
self.log.default("Deleted CachedInsulinDeliveryObject with UUID %{public}@", uuid.uuidString)
deleted = true
}
if deleted {
self.cacheStore.save()
}
}
return deleted
}
private func purgeCachedObjects(matching predicate: NSPredicate) {
dispatchPrecondition(condition: .onQueue(queue))
cacheStore.managedObjectContext.performAndWait {
do {
let count = try cacheStore.managedObjectContext.purgeObjects(of: CachedInsulinDeliveryObject.self, matching: predicate)
self.log.default("Purged %d CachedInsulinDeliveryObjects", count)
} catch let error {
self.log.error("Unable to purge CachedInsulinDeliveryObjects: %@", String(describing: error))
}
}
}
}
extension InsulinDeliveryStore {
/// Generates a diagnostic report about the current state
///
/// This operation is performed asynchronously and the completion will be executed on an arbitrary background queue.
///
/// - parameter completion: The closure takes a single argument of the report string.
public func generateDiagnosticReport(_ completion: @escaping (_ report: String) -> Void) {
self.queue.async {
var report: [String] = [
"### InsulinDeliveryStore",
"* cacheLength: \(self.cacheLength)",
super.debugDescription,
"* lastBasalEndDate: \(String(describing: self.lastBasalEndDate))",
"",
"#### cachedDoseEntries",
]
for sample in self.getCachedDoseEntries() {
report.append(String(describing: sample))
}
report.append("")
completion(report.joined(separator: "\n"))
}
}
}
// MARK: - Unit Testing
extension InsulinDeliveryStore {
public var test_lastBasalEndDate: Date? {
get {
var date: Date?
queue.sync {
date = self.lastBasalEndDate
}
return date
}
set {
queue.sync {
self.lastBasalEndDate = newValue
}
}
}
}
| mit | 64e9f30c24bcb3d3a0e6567bd43a003e | 37.260965 | 182 | 0.616897 | 5.489931 | false | false | false | false |
lennet/proNotes | app/proNotes/Document/PageView/Drawing/SketchView.swift | 1 | 5460 | //
// SketchView.swift
// proNotes
//
// Created by Leo Thomas on 28/11/15.
// Copyright © 2015 leonardthomas. All rights reserved.
//
import UIKit
class SketchView: UIImageView, PageSubView, SketchSettingsDelegate {
// MARK - Properties
var penObject: Pen = Pencil() {
didSet {
strokeBuffer?.alpha = penObject.alphaValue
}
}
private var undoImage: UIImage?
weak var sketchLayer: SketchLayer? {
didSet {
image = sketchLayer?.image
}
}
weak var strokeBuffer: StrokeBufferView?
// MARK - Init
init(sketchLayer: SketchLayer, frame: CGRect) {
self.sketchLayer = sketchLayer
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func commonInit() {
isUserInteractionEnabled = false
image = sketchLayer?.image
}
private func setUpStrokeBuffer() {
guard self.strokeBuffer == nil else {
return
}
let strokeBuffer = StrokeBufferView(frame: bounds)
strokeBuffer.alpha = penObject.alphaValue
addSubview(strokeBuffer)
self.strokeBuffer = strokeBuffer
}
// MARK: - Touch Handling
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
undoImage = image
if penObject.isEraser {
eraseForTouches(touches, withEvent: event)
} else {
strokeBuffer?.handleTouches(touches, withEvent: event)
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if penObject.isEraser {
eraseForTouches(touches, withEvent: event)
} else {
strokeBuffer?.handleTouches(touches, withEvent: event)
}
}
override func touchesEnded(_ touches: Set<UITouch>,
with event: UIEvent?) {
handleTouchesEnded()
}
override func touchesCancelled(_ touches: Set<UITouch>,
with event: UIEvent?) {
handleTouchesEnded()
}
func handleTouchesEnded() {
// merge current Stroke
if let newStrokeImage = strokeBuffer?.image {
UIGraphicsBeginImageContextWithOptions(bounds.size, false, 0.0)
image?.draw(in: bounds)
newStrokeImage.draw(in: bounds, blendMode: .normal, alpha: strokeBuffer?.alpha ?? 1)
image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
strokeBuffer?.reset()
updateImage(image)
}
func updateImage(_ image: UIImage?) {
self.image = image
if sketchLayer != nil && sketchLayer?.docPage != nil {
DocumentInstance.sharedInstance.registerUndoAction(undoImage, pageIndex: sketchLayer!.docPage.index, layerIndex: sketchLayer!.index)
undoImage = nil
}
saveChanges()
}
private func eraseForTouches(_ touches: Set<UITouch>, withEvent event: UIEvent?) {
guard let touch = touches.first else {
return
}
UIGraphicsBeginImageContextWithOptions(bounds.size, false, 0.0)
let context = UIGraphicsGetCurrentContext()
image?.draw(in: bounds)
for touch in event?.coalescedTouches(for: touch) ?? [touch] {
drawEraseStroke(context, touch: touch)
}
image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
private func drawEraseStroke(_ context: CGContext?, touch: UITouch) {
let previousLocation = touch.previousLocation(in: self)
let location = touch.location(in: self)
context?.setBlendMode(.clear)
context?.setLineWidth(penObject.lineWidth)
context?.setLineCap(.round)
context?.move(to: previousLocation)
context?.addLine(to: location)
context?.strokePath()
}
func removeLayer() {
clearSketch()
removeFromSuperview()
sketchLayer?.removeFromPage()
sketchLayer = nil
SettingsViewController.sharedInstance?.currentType = .pageInfo
}
// MARK: - PageSubViewProtocol
func undoAction(_ oldObject: Any?) {
if let oldImage = oldObject as? UIImage {
updateImage(oldImage)
}
}
func setSelected() {
SettingsViewController.sharedInstance?.currentType = .sketch
SketchSettingsViewController.delegate = self
setUpStrokeBuffer()
isUserInteractionEnabled = true
}
func setDeselected() {
strokeBuffer?.removeFromSuperview()
strokeBuffer = nil
isUserInteractionEnabled = false
}
func saveChanges() {
if image != nil && sketchLayer != nil {
sketchLayer?.image = image
}
if let pageIndex = sketchLayer?.docPage.index {
DocumentInstance.sharedInstance.didUpdatePage(pageIndex)
}
}
// MARK: - DrawingSettingsDelegate
func didSelectColor(_ color: UIColor) {
strokeBuffer?.strokeColor = color
}
func didSelectDrawingObject(_ object: Pen) {
penObject = object
}
func didSelectLineWidth(_ width: CGFloat) {
penObject.lineWidth = width
}
func clearSketch() {
image = nil
strokeBuffer?.reset()
}
}
| mit | a67f238439339777ca9e5d535ff069ef | 27.284974 | 144 | 0.60762 | 5.269305 | false | false | false | false |
wwczwt/sdfad | PageController/PageControllerExtensions.swift | 1 | 5757 | //
// PageControllerExtensions.swift
// PageController
//
// Created by Hirohisa Kawasaki on 6/26/15.
// Copyright (c) 2015 Hirohisa Kawasaki. All rights reserved.
//
import Foundation
import UIKit
public extension PageController {
func viewControllerForCurrentPage() -> UIViewController? {
if let view = scrollView.viewForCurrentPage() {
var responder: UIResponder? = view
while responder != nil {
if let responder = responder where responder is UIViewController {
return responder as? UIViewController
}
responder = responder?.nextResponder()
}
}
return nil
}
}
// TODO: swift 2.0 allows extensions to generic types, use Array
public extension NSArray {
func swapByIndex<T>(index: Int) -> [T] {
if index >= self.count {
return []
}
var a = [T]()
var b = [T]()
var hit = false
for (i, obj) in enumerate(self) {
if i == index {
hit = true
}
if hit {
a.append(obj as! T)
} else {
b.append(obj as! T)
}
}
return a + b
}
class func indexesBetween(#from: Int, to: Int, count: Int, asc: Bool) -> [Int] {
var indexes = [Int]()
var from = from
var to = to
if !asc {
swap(&from, &to)
}
if from > to {
to += count
}
for index in from ... to {
indexes.append(index.relative(count))
}
if asc {
return indexes
}
return indexes.reverse()
}
}
public extension MenuBar {
func createMenuCells(#from: CGFloat, distance: CGFloat, index: Int, asc: Bool) -> [MenuCell] {
if asc {
return createMenuCellsByIncreasing(from: from, distance: distance, index: index)
}
return createMenuCellsByDecreasing(from: from, distance: distance, index: index)
}
func distanceBetweenCells(#from: Int, to: Int, asc: Bool) -> CGFloat {
var indexes = NSArray.indexesBetween(from: from, to: to, count: items.count, asc: asc)
indexes.removeAtIndex(0)
return indexes.reduce(0) { (a: CGFloat, b: Int) -> CGFloat in a + self.sizes[b.relative(self.items.count)].width }
}
}
extension MenuBar {
func createMenuCellsByIncreasing(#from: CGFloat, distance: CGFloat, index: Int) -> [MenuCell] {
var cells = [MenuCell]()
var offsetX = from
var index = index
while offsetX <= from + distance {
let size = sizes[index.relative(items.count)]
let cell = createMenuCell(AtIndex: index.relative(items.count))
cell.frame = CGRect(x: offsetX, y: 0, width: size.width, height: size.height)
cells.append(cell)
offsetX = cell.frame.maxX
index++
}
return cells
}
func createMenuCellsByDecreasing(#from: CGFloat, distance: CGFloat, index: Int) -> [MenuCell] {
var cells = [MenuCell]()
var maxX = from
var index = index
while maxX >= from - distance {
let size = sizes[index.relative(items.count)]
let cell = createMenuCell(AtIndex: index.relative(items.count))
cell.frame = CGRect(x: maxX - size.width, y: 0, width: size.width, height: size.height)
cells.append(cell)
maxX = cell.frame.minX
index--
}
return cells
}
}
public extension UIView {
func include(#frame: CGRect) -> Bool {
return frame.contains(self.frame) || frame.intersects(self.frame)
}
func removeIfExcluded(#frame: CGRect) -> Bool {
if !include(frame: frame) {
removeFromSuperview()
return true
}
return false
}
}
public extension Int {
func relative(max: Int) -> Int {
let denominator: Int = max != 0 ? max : 1
var index = self % denominator
if index < 0 {
index = max - abs(index)
}
return index
}
}
public extension UIViewController {
func childViewControllerOrderedByX(#asc: Bool) -> [UIViewController] {
let viewControllers = childViewControllers as! [UIViewController]
return viewControllers.sorted {
if asc {
return $0.view.frame.origin.x < $1.view.frame.origin.x
}
return $0.view.frame.origin.x > $1.view.frame.origin.x
}
}
}
public extension UIScrollView {
func needsRecenter() -> Bool {
let centerOffsetX = (contentSize.width - frame.width) / 2
let currentOffset = contentOffset
let distanceFromCenter = fabs(contentOffset.x - centerOffsetX)
return distanceFromCenter >= bounds.width
}
func viewForCurrentPage() -> UIView? {
let center = centerForVisibleFrame()
return subviews.filter { $0.frame.contains(center) }.first as? UIView
}
func centerForVisibleFrame() -> CGPoint {
var center = contentOffset
center.x += frame.width / 2
center.y += frame.height / 2
return center
}
func recenter(relativeView view: UIView) {
let centerOffsetX = (contentSize.width - frame.width) / 2
let currentOffset = contentOffset
contentOffset = CGPoint(x: centerOffsetX, y: currentOffset.y)
for subview in subviews as! [UIView] {
var center = convertPoint(subview.center, toView: view)
center.x += centerOffsetX - currentOffset.x
subview.center = view.convertPoint(center, toView: self)
}
}
} | mit | b327881672291ad1b45179c1ce649732 | 25.292237 | 122 | 0.568004 | 4.44556 | false | false | false | false |
david1mdavis/IOS-nRF-Toolbox | nRF Toolbox/BGM/ContinuousGlucoseMonitoring/NORCGMViewController.swift | 1 | 23296 | /*
* Copyright (c) 2015, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
import CoreBluetooth
enum viewActionTypes : Int {
case action_START_SESSION = 0
case action_STOP_SESSION = 1
case action_SET_TIME = 2
}
class NORCGMViewController : NORBaseViewController, CBCentralManagerDelegate, CBPeripheralDelegate, NORScannerDelegate, UITableViewDataSource, UIActionSheetDelegate {
//MARK: - Class porperties
var bluetoothManager : CBCentralManager?
var dateFormat : DateFormatter
var cbgmServiceUUID : CBUUID
var cgmGlucoseMeasurementCharacteristicUUID : CBUUID
var cgmGlucoseMeasurementContextCharacteristicUUID : CBUUID
var cgmRecordAccessControlPointCharacteristicUUID : CBUUID
var cgmFeatureCharacteristicUUID : CBUUID
var cgmStatusCharacteristicUUID : CBUUID
var cgmSessionStartTimeCharacteristicUUID : CBUUID
var cgmSessionRunTimeCharacteristicUUID : CBUUID
var cgmSpecificOpsControlPointCharacteristicUUID : CBUUID
var batteryServiceUUID : CBUUID
var batteryLevelCharacteristicUUID : CBUUID
/*!
* This property is set when the device successfully connects to the peripheral. It is used to cancel the connection
* after user press Disconnect button.
*/
var connectedPeripheral : CBPeripheral?
var cgmRecordAccessControlPointCharacteristic : CBCharacteristic?
var cgmFeatureCharacteristic : CBCharacteristic?
var cgmSpecificOpsControlPointCharacteristic : CBCharacteristic?
var readings : NSMutableArray?
var cgmFeatureData : NORCGMFeatureData?
//MARK: View Outlets / Actions
@IBOutlet weak var verticalLabel: UILabel!
@IBOutlet weak var battery: UIButton!
@IBOutlet weak var deviceName : UILabel!
@IBOutlet weak var connectionButton : UIButton!
@IBOutlet weak var recordButton : UIButton!
@IBOutlet weak var cbgmTableView : UITableView!
@IBOutlet weak var cgmActivityIndicator : UIActivityIndicatorView!
@IBAction func connectionButtonTapped(_ sender: AnyObject) {
self.handleConnectionButtonTapped()
}
@IBAction func actionButtonTapped(_ sender: AnyObject) {
self.handleActionButtonTapped()
}
@IBAction func aboutButtonTapped(_ sender: AnyObject) {
self.handleAboutButtonTapped()
}
//MARK: - UIViewController methods
// Custom initialization
required init?(coder aDecoder: NSCoder) {
readings = NSMutableArray(capacity: 20)
dateFormat = DateFormatter()
dateFormat.dateFormat = "dd.MM.yyyy, hh:mm"
cbgmServiceUUID = CBUUID(string: NORServiceIdentifiers.cgmServiceUUIDString)
cgmGlucoseMeasurementCharacteristicUUID = CBUUID(string: NORServiceIdentifiers.cgmGlucoseMeasurementCharacteristicUUIDString)
cgmGlucoseMeasurementContextCharacteristicUUID = CBUUID(string: NORServiceIdentifiers.bgmGlucoseMeasurementContextCharacteristicUUIDString)
cgmRecordAccessControlPointCharacteristicUUID = CBUUID(string: NORServiceIdentifiers.bgmRecordAccessControlPointCharacteristicUUIDString)
cgmFeatureCharacteristicUUID = CBUUID(string: NORServiceIdentifiers.cgmFeatureCharacteristicUUIDString)
cgmStatusCharacteristicUUID = CBUUID(string: NORServiceIdentifiers.cgmStatusCharacteristicUUIDString)
cgmSessionStartTimeCharacteristicUUID = CBUUID(string: NORServiceIdentifiers.cgmSessionStartTimeCharacteristicUUIDString)
cgmSessionRunTimeCharacteristicUUID = CBUUID(string: NORServiceIdentifiers.cgmSessionRunTimeCharacteristicUUIDString)
cgmSpecificOpsControlPointCharacteristicUUID = CBUUID(string: NORServiceIdentifiers.cgmSpecificOpsControlPointCharacteristicUUIDString)
batteryServiceUUID = CBUUID(string: NORServiceIdentifiers.batteryServiceUUIDString)
batteryLevelCharacteristicUUID = CBUUID(string: NORServiceIdentifiers.batteryLevelCharacteristicUUIDString)
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
// Rotate the vertical label
self.verticalLabel.transform = CGAffineTransform(translationX: -(verticalLabel.frame.width/2) + (verticalLabel.frame.height / 2), y: 0.0).rotated(by: CGFloat(-M_PI_2))
cbgmTableView.dataSource = self
}
func appdidEnterBackground() {
let name = connectedPeripheral?.name ?? "peripheral"
NORAppUtilities.showBackgroundNotification(message: "You are still connected to \(name). It will collect data also in background.")
}
func appDidBecomeActiveBackground(_ aNotification : Notification) {
UIApplication.shared.cancelAllLocalNotifications()
}
func handleActionButtonTapped() {
let actionSheet = UIActionSheet()
actionSheet.delegate = self
actionSheet.addButton(withTitle: "Start Session")
actionSheet.addButton(withTitle: "Stop Session")
actionSheet.addButton(withTitle: "Set Update Interval")
actionSheet.destructiveButtonIndex = 1
actionSheet.show(in: self.view)
}
func handleAboutButtonTapped() {
self.showAbout(message: NORAppUtilities.cgmHelpText)
}
func handleConnectionButtonTapped() {
if connectedPeripheral != nil {
bluetoothManager?.cancelPeripheralConnection(connectedPeripheral!)
}
}
func parseCGMFeatureCharacteristic() {
guard cgmFeatureCharacteristic?.value != nil else{
return
}
let data = cgmFeatureCharacteristic!.value
let arrayBytes = ((data as NSData?)?.bytes)!.assumingMemoryBound(to: UInt8.self)
cgmFeatureData = NORCGMFeatureData(withBytes: UnsafeMutablePointer<UInt8>(mutating:arrayBytes))
}
func enableRecordButton() {
recordButton.isEnabled = true
recordButton.backgroundColor = UIColor.black
recordButton.setTitleColor(UIColor.white, for: UIControlState())
}
func disableRecordButton() {
recordButton.isEnabled = false
recordButton.backgroundColor = UIColor.lightGray
recordButton.setTitleColor(UIColor.lightText, for: UIControlState())
}
func clearUI() {
readings?.removeAllObjects()
cbgmTableView.reloadData()
deviceName.text = "DEFAULT CGM"
battery.tag = 0
battery.setTitle("n/a", for:UIControlState())
}
func showErrorAlert(withMessage aMessage : String) {
DispatchQueue.main.async(execute: {
let alertView = UIAlertView(title: "Error", message: aMessage, delegate: nil, cancelButtonTitle: "Ok")
alertView.show()
})
}
//MARK: - Scanner Delegate methods
func centralManagerDidSelectPeripheral(withManager aManager: CBCentralManager, andPeripheral aPeripheral: CBPeripheral) {
// We may not use more than one Central Manager instance. Let's just take the one returned from Scanner View Controller
bluetoothManager = aManager
bluetoothManager?.delegate = self
// The sensor has been selected, connect to it
aPeripheral.delegate = self
let connectionOptions = NSDictionary(object: NSNumber(value: true as Bool), forKey: CBConnectPeripheralOptionNotifyOnNotificationKey as NSCopying)
bluetoothManager?.connect(aPeripheral, options: connectionOptions as? [String : AnyObject])
}
//MARK: - Table View Datasource delegate methods
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (readings?.count)!
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let aReading = readings?.object(at: (indexPath as NSIndexPath).row) as? NORCGMReading
let aCell = tableView.dequeueReusableCell(withIdentifier: "CGMCell", for: indexPath) as! NORCGMItemCell
aCell.type.text = aReading?.typeAsString()
aCell.timestamp.text = dateFormat.string(from: Date.init(timeIntervalSinceNow: Double((aReading?.timeOffsetSinceSessionStart)!)))
aCell.value.text = String(format: "%.0f", (aReading?.glucoseConcentration)!)
aCell.unit.text = "mg/DL"
return aCell
}
func showUserInputAlert(withMessage aMessage: String) {
DispatchQueue.main.async(execute: {
let alert = UIAlertView(title: "Input", message: aMessage, delegate: self, cancelButtonTitle: "Cancel", otherButtonTitles: "Set")
alert.alertViewStyle = .plainTextInput
alert.textField(at: 0)!.keyboardType = .numberPad
alert.show()
})
}
//MARK: - Segue navigation
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
// The 'scan' seque will be performed only if connectedPeripheral == nil (if we are not connected already).
return identifier == "scan" && connectedPeripheral == nil
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard segue.identifier == "scan" || segue.identifier == "details" else {
return
}
if segue.identifier == "scan" {
// Set this contoller as scanner delegate
let nc = segue.destination
let controller = nc.childViewControllerForStatusBarHidden as! NORScannerViewController
controller.filterUUID = cbgmServiceUUID
controller.delegate = self
}
if segue.identifier == "details" {
let controller = segue.destination as! NORCGMDetailsViewController
let aReading = readings!.object(at: ((cbgmTableView.indexPathForSelectedRow as NSIndexPath?)?.row)!)
controller.reading = aReading as? NORCGMReading
}
}
//MARK: - Action Sheet delegate methods
func actionSheet(_ actionSheet: UIActionSheet, clickedButtonAt buttonIndex: Int) {
var accessParam : [UInt8] = []
var size : NSInteger = 0
var clearList :Bool = true
var targetCharacteristic : CBCharacteristic?
switch viewActionTypes(rawValue:buttonIndex)! {
case .action_START_SESSION:
accessParam.append(NORCGMOpCode.start_SESSION.rawValue)
size = 1
targetCharacteristic = cgmSpecificOpsControlPointCharacteristic
cgmActivityIndicator.startAnimating()
clearList = false
break
case .action_STOP_SESSION:
accessParam.append(NORCGMOpCode.stop_SESSION.rawValue)
size = 1
targetCharacteristic = cgmSpecificOpsControlPointCharacteristic
cgmActivityIndicator.stopAnimating()
clearList = false
break
case .action_SET_TIME:
self.showUserInputAlert(withMessage: "Enter update interval in minutes")
clearList = false
break
}
if clearList {
readings!.removeAllObjects()
cbgmTableView.reloadData()
}
if size > 0 {
let data = Data(bytes: &accessParam, count: size)
print("Writing data: \(data) to \(targetCharacteristic!)")
connectedPeripheral?.writeValue(data, for: targetCharacteristic!, type:.withResponse)
}
}
//MARK: - UIAlertViewDelegate / Helpers
func alertView(_ alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
if buttonIndex != 0 {
var accessParam : [UInt8] = []
let timeValue = Int(alertView.textField(at: 0)!.text!)
accessParam.append(NORCGMOpCode.set_COMMUNICATION_INTERVAL.rawValue)
accessParam.append(UInt8(timeValue!))
let data = Data(bytes: &accessParam, count: 2)
print("Writing data : \(data) to characteristic: \(cgmSpecificOpsControlPointCharacteristic)")
connectedPeripheral?.writeValue(data, for: cgmSpecificOpsControlPointCharacteristic!, type: .withResponse)
}
}
//MARK: - Central Manager delegate methods
func centralManagerDidUpdateState(_ central: CBCentralManager) {
if central.state == .poweredOff {
print("Bluetooth powered off")
} else {
print("Bluetooth powered on")
}
}
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
// Scanner uses other queue to send events. We must edit UI in the main queue
DispatchQueue.main.async(execute: {
self.deviceName.text = peripheral.name
self.connectionButton.setTitle("DISCONNECT", for: UIControlState())
self.enableRecordButton()
//Following if condition display user permission alert for background notification
if UIApplication.instancesRespond(to: #selector(UIApplication.registerUserNotificationSettings(_:))) {
UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.alert, .sound], categories: nil))
}
NotificationCenter.default.addObserver(self, selector: #selector(self.appdidEnterBackground), name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.appDidBecomeActiveBackground), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
});
// Peripheral has connected. Discover required services
connectedPeripheral = peripheral
peripheral.discoverServices([cbgmServiceUUID, batteryServiceUUID])
}
func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
// Scanner uses other queue to send events. We must edit UI in the main queue
DispatchQueue.main.async(execute: {
NORAppUtilities.showAlert(title: "Error", andMessage: "Connecting to the peripheral failed. Try again")
self.connectionButton.setTitle("CONNCET", for: UIControlState())
self.connectedPeripheral = nil
self.disableRecordButton()
self.clearUI()
});
}
func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
// Scanner uses other queue to send events. We must edit UI in the main queue
DispatchQueue.main.async(execute: {
self.connectionButton.setTitle("CONNECT", for: UIControlState())
if NORAppUtilities.isApplicationInactive() {
let name = peripheral.name ?? "Peripheral"
NORAppUtilities.showBackgroundNotification(message: "\(name) is disconnected.")
}
self.connectedPeripheral = nil
self.disableRecordButton()
self.clearUI()
NotificationCenter.default.removeObserver(self, name:NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
NotificationCenter.default.removeObserver(self, name:NSNotification.Name.UIApplicationDidEnterBackground, object: nil)
})
}
//MARK: - CBPeripheralDelegate methods
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
guard error == nil else {
print("An error occured while discovering services: \(error!.localizedDescription)")
bluetoothManager!.cancelPeripheralConnection(peripheral)
return
}
for aService in peripheral.services! {
// Discovers the characteristics for a given service
if aService.uuid == cbgmServiceUUID {
peripheral.discoverCharacteristics(
[ cgmGlucoseMeasurementCharacteristicUUID,
cgmGlucoseMeasurementContextCharacteristicUUID,
cgmRecordAccessControlPointCharacteristicUUID,
cgmFeatureCharacteristicUUID,
cgmStatusCharacteristicUUID,
cgmSessionStartTimeCharacteristicUUID,
cgmSessionRunTimeCharacteristicUUID,
cgmSpecificOpsControlPointCharacteristicUUID
], for: aService)
} else if aService.uuid == batteryServiceUUID {
peripheral.discoverCharacteristics([batteryLevelCharacteristicUUID], for: aService)
}
}
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
guard error == nil else {
print("Error occurred while discovering characteristic: \(error!.localizedDescription)")
bluetoothManager!.cancelPeripheralConnection(peripheral)
return
}
// Characteristics for one of those services has been found
if service.uuid == cbgmServiceUUID {
for characteristic in service.characteristics! {
peripheral.setNotifyValue(true, for: characteristic)
if characteristic.uuid == cgmFeatureCharacteristicUUID {
cgmFeatureCharacteristic = characteristic
peripheral.readValue(for: cgmFeatureCharacteristic!)
}
if characteristic.uuid == cgmRecordAccessControlPointCharacteristicUUID {
cgmRecordAccessControlPointCharacteristic = characteristic
}
if characteristic.uuid == cgmSpecificOpsControlPointCharacteristicUUID {
cgmSpecificOpsControlPointCharacteristic = characteristic
}
}
} else if service.uuid == batteryServiceUUID {
for characteristic in service.characteristics! {
if characteristic.uuid == batteryLevelCharacteristicUUID {
peripheral.readValue(for: characteristic)
break
}
}
}
}
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
guard error == nil else {
print("Error occurred while updating characteristic value: \(error!.localizedDescription)")
return
}
// Decode the characteristic data
let data = characteristic.value
var array = UnsafeMutablePointer<UInt8>(mutating: (data! as NSData).bytes.bindMemory(to: UInt8.self, capacity: data!.count))
if characteristic.uuid == batteryLevelCharacteristicUUID {
let batteryLevel = NORCharacteristicReader.readUInt8Value(ptr: &array)
let text = "\(batteryLevel)%"
// Scanner uses other queue to send events. We must edit UI in the main queue
DispatchQueue.main.async(execute: {
self.battery.setTitle(text, for: .disabled)
})
if battery.tag == 0 {
// If battery level notifications are available, enable them
if characteristic.properties.contains(CBCharacteristicProperties.notify) {
self.battery.tag = 1 // mark that we have enabled notifications
// Enable notification on data characteristic
peripheral.setNotifyValue(true, for: characteristic)
}
}
}
if characteristic.uuid == cgmGlucoseMeasurementCharacteristicUUID {
DispatchQueue.main.async(execute: {
let reading = NORCGMReading(withBytes: array)
if self.cgmFeatureData != nil {
reading.cgmFeatureData = self.cgmFeatureData
}
if self.readings!.contains(reading) {
// If the reading has been found (the same reading has the same sequence number), replace it with the new one
// The indexIfObjext method uses isEqual method from GlucodeReading (comparing by sequence number only)
self.readings!.replaceObject(at: self.readings!.index(of: reading), with: reading)
} else {
// If not, just add the new one to the array
self.readings!.add(reading)
}
self.cbgmTableView.reloadData()
})
}
if characteristic.uuid == cgmSpecificOpsControlPointCharacteristicUUID {
let responseCode = array[2]
switch NORCGMOpcodeResponseCodes(rawValue: responseCode)! {
case .op_CODE_NOT_SUPPORTED:
self.showErrorAlert(withMessage:"Operation not supported")
break;
case .success:
print("Success")
break;
case .invalid_OPERAND:
self.showErrorAlert(withMessage:"Invalid Operand")
break
case .procedure_NOT_COMPLETED:
self.showErrorAlert(withMessage:"Procedure not completed")
break
case .parameter_OUT_OF_RANGE:
self.showErrorAlert(withMessage:"Parameter out of range")
break;
default:
break
}
}
if characteristic.uuid == cgmFeatureCharacteristicUUID {
self.parseCGMFeatureCharacteristic()
}
if characteristic.uuid == cgmSessionStartTimeCharacteristicUUID {
print("Start time did update")
}
if characteristic.uuid == cgmSessionRunTimeCharacteristicUUID {
print("runtime did update")
}
}
}
| bsd-3-clause | 52a24b3d4ba9c14830c720e8036df17d | 45.314115 | 181 | 0.667625 | 5.951967 | false | false | false | false |
LipliStyle/Liplis-iOS | Liplis/ViewWidgetTopicSetting.swift | 1 | 19638 | //
// ViewWidgetTopicSetting.swift
// Liplis
//
// Liplis ウィジェット話題設定
//
//アップデート履歴
// 2015/05/05 ver0.1.0 作成
// 2015/05/13 ver1.2.0 ログの送りバグ修正
// 2015/05/16 ver1.4.0 swift1.2対応
// リファクタリング
// 2015/05/19 ver1.4.1 話題2ch1を凍結
//
// Created by sachin on 2015/05/05.
// Copyright (c) 2015年 sachin. All rights reserved.
//
import UIKit
class ViewWidgetTopicSetting : UIViewController, UITableViewDelegate, UITableViewDataSource{
///=============================
///ウィジェットインスタンス
private var widget : LiplisWidget!
///=============================
///テーブル要素
private var tblItems : Array<MsgSettingViewCell>! = []
///=============================
///ビュータイトル
private var viewTitle = "話題設定"
///=============================
///画面要素
private var lblTitle : UILabel!
private var btnBack : UIButton!
private var tblSetting: UITableView!
//============================================================
//
//初期化処理
//
//============================================================
/*
コンストラクター
*/
convenience init(widget : LiplisWidget) {
self.init(nibName: nil, bundle: nil)
self.widget = widget
self.initView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
required override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
/*
アクティビティの初期化
*/
private func initView()
{
//ビューの初期化
self.view.opaque = true //背景透過許可
self.view.backgroundColor = UIColor(red:255,green:255,blue:255,alpha:255) //白透明背景
//タイトルラベルの作成
self.createLblTitle()
//閉じるボタン作成
self.createBtnClose()
//テーブル作成
self.createTableView()
//サイズ調整
self.setSize()
}
/*
タイトルラベルの初期化
*/
private func createLblTitle()
{
self.lblTitle = UILabel(frame: CGRectMake(0,0,0,0))
self.lblTitle.backgroundColor = UIColor.hexStr("ffa500", alpha: 255)
self.lblTitle.text = self.viewTitle
self.lblTitle.textColor = UIColor.whiteColor()
self.lblTitle.shadowColor = UIColor.grayColor()
self.lblTitle.textAlignment = NSTextAlignment.Center
self.view.addSubview(self.lblTitle)
}
/*
閉じるボタンの初期化
*/
private func createBtnClose()
{
self.btnBack = UIButton()
self.btnBack.titleLabel?.font = UIFont.systemFontOfSize(12)
self.btnBack.backgroundColor = UIColor.hexStr("DF7401", alpha: 255)
self.btnBack.layer.masksToBounds = true
self.btnBack.setTitle("閉じる", forState: UIControlState.Normal)
self.btnBack.addTarget(self, action: "closeMe:", forControlEvents: .TouchDown)
self.btnBack.layer.cornerRadius = 3.0
self.view.addSubview(btnBack)
}
/*
設定要素テーブルの初期化
*/
private func createTableView()
{
//TableViewの生成
self.tblSetting = UITableView()
self.tblSetting.frame = CGRectMake(0,0,0,0)
self.tblSetting.registerClass(UITableViewCell.self, forCellReuseIdentifier: "MyCell")
self.tblSetting.dataSource = self
self.tblSetting.delegate = self
self.tblSetting.allowsSelection = false
self.tblSetting.rowHeight = 20
self.tblSetting.registerClass(CtvCellWidgetTopicTitle.self, forCellReuseIdentifier: "CtvCellWidgetTopicTitle")
self.tblSetting.registerClass(CtvCellWidgetTopicCheck.self, forCellReuseIdentifier: "CtvCellWidgetTopicCheck")
self.tblSetting.registerClass(CtvCellWidgetTopicRadio.self, forCellReuseIdentifier: "CtvCellWidgetTopicRadio")
self.view.addSubview(tblSetting)
//テーブルビューアイテム作成
self.tblItems = Array<MsgSettingViewCell>()
self.tblItems.append(
MsgSettingViewCell(
title: "おしゃべりジャンル",
content: "",
partsType: LiplisDefine.PARTS_TYPE_TITLE,settingIdx: -1,
initValue : 0,
trueValue: 0,
rowHeight: CGFloat(26)
)
)
self.tblItems.append(
MsgSettingViewCell(
title: "ニュース",
content: "",
partsType: LiplisDefine.PARTS_TYPE_CHECK,settingIdx: 12,
initValue : widget.os.lpsTopicNews,
trueValue: 1,
rowHeight: CGFloat(45)
)
)
//1.4.1 2chは一時的に凍結
// self.tblItems.append(
// MsgSettingViewCell(
// title: "2ch",
// content: "",
// partsType: LiplisDefine.PARTS_TYPE_CHECK,
// settingIdx: 13,
// initValue : widget.os.lpsTopic2ch,
// trueValue: 1,
// rowHeight: CGFloat(45)
// )
// )
self.tblItems.append(
MsgSettingViewCell(
title: "ニコニコ",
content: "",
partsType: LiplisDefine.PARTS_TYPE_CHECK,
settingIdx: 14,
initValue : widget.os.lpsTopicNico,
trueValue: 1,
rowHeight: CGFloat(45)
)
)
// self.tblItems.append(
// MsgSettingViewCell(
// title: "RSS",
// content: "",
// partsType: LiplisDefine.PARTS_TYPE_CHECK,
// settingIdx: 15,
// initValue : widget.os.lpsTopicRss,
// trueValue: 1,
// rowHeight: CGFloat(45)
// )
// )
// self.tblItems.append(
// MsgSettingViewCell(
// title: "Twitter マイタイムライン",
// content: "",
// partsType: LiplisDefine.PARTS_TYPE_CHECK,
// settingIdx: 18,
// initValue : widget.os.lpsTopicTwitterMy,
// trueValue: 1,
// rowHeight: CGFloat(45)
// )
// )
//
self.tblItems.append(
MsgSettingViewCell(
title: "Twitter パブリックタイムライン",
content: "",
partsType: LiplisDefine.PARTS_TYPE_CHECK,settingIdx: 17,
initValue : widget.os.lpsTopicTwitterPu,
trueValue: 1,
rowHeight: CGFloat(45)
)
)
// self.tblItems.append(
// MsgSettingViewCell(
// title: "Twitter 設定ユーザーツイート",
// content: "",
// partsType: LiplisDefine.PARTS_TYPE_CHECK,
// settingIdx: 16,
// initValue : widget.os.lpsTopicTwitter,
// trueValue: 1,
// rowHeight: CGFloat(45)
// )
// )
self.tblItems.append(
MsgSettingViewCell(
title: "話題の取得範囲",
content: "",
partsType: LiplisDefine.PARTS_TYPE_TITLE,settingIdx: -1,
initValue : 0,
trueValue: 0,
rowHeight: CGFloat(26)
)
)
let lpsNewsRange : MsgSettingViewCell = MsgSettingViewCell(
title: "",
content: "",
partsType: LiplisDefine.PARTS_TYPE_RADIO,
settingIdx: 9,
initValue : widget.os.lpsNewsRange,
trueValue: 0,
rowHeight: CGFloat(0)
)
lpsNewsRange.appendChild(
MsgSettingViewCell(
title: "1時間",
content: "",partsType: LiplisDefine.PARTS_TYPE_RADIO_CHILD,
settingIdx: 9,
initValue : 0,
trueValue: 0,
rowHeight: CGFloat(45)
)
)
lpsNewsRange.appendChild(
MsgSettingViewCell(
title: "3時間",
content: "",
partsType: LiplisDefine.PARTS_TYPE_RADIO_CHILD,
settingIdx: 9,
initValue : 0,
trueValue: 1,
rowHeight: CGFloat(45)
)
)
lpsNewsRange.appendChild(
MsgSettingViewCell(
title: "6時間",content: "",partsType: LiplisDefine.PARTS_TYPE_RADIO_CHILD,settingIdx: 9,initValue : 0, trueValue: 2, rowHeight: CGFloat(45)
)
)
lpsNewsRange.appendChild(
MsgSettingViewCell(
title: "12時間",
content: "",
partsType: LiplisDefine.PARTS_TYPE_RADIO_CHILD,settingIdx: 9,
initValue : 0,
trueValue: 3,
rowHeight: CGFloat(45)))
lpsNewsRange.appendChild(MsgSettingViewCell(
title: "1日",
content: "",
partsType: LiplisDefine.PARTS_TYPE_RADIO_CHILD,settingIdx: 9,
initValue : 0,
trueValue: 4,
rowHeight: CGFloat(45)
)
)
lpsNewsRange.appendChild(
MsgSettingViewCell(
title: "3日",
content: "",
partsType: LiplisDefine.PARTS_TYPE_RADIO_CHILD,
settingIdx: 9,
initValue : 0,
trueValue: 5,
rowHeight: CGFloat(45)
)
)
lpsNewsRange.appendChild(
MsgSettingViewCell(
title: "7日",
content: "",
partsType: LiplisDefine.PARTS_TYPE_RADIO_CHILD,settingIdx: 9,
initValue : 0,
trueValue: 6,
rowHeight: CGFloat(45)
)
)
lpsNewsRange.appendChild(
MsgSettingViewCell(
title: "無制限",
content: "",
partsType: LiplisDefine.PARTS_TYPE_RADIO_CHILD,
settingIdx: 9,
initValue : 0,
trueValue: 7,
rowHeight: CGFloat(45)
)
)
self.tblItems.append(lpsNewsRange)
self.tblItems.append(
MsgSettingViewCell(
title: "既読の話題設定",
content: "",
partsType: LiplisDefine.PARTS_TYPE_TITLE,settingIdx: -1,
initValue : 0,
trueValue: 0,
rowHeight: CGFloat(26)
)
)
self.tblItems.append(
MsgSettingViewCell(
title: "既読の話題はおしゃべりしない",
content: "",
partsType: LiplisDefine.PARTS_TYPE_CHECK,settingIdx: 10,
initValue : widget.os.lpsNewsAlready,
trueValue: 1,
rowHeight: CGFloat(45)
)
)
self.tblItems.append(
MsgSettingViewCell(
title: "話題が尽きたときのふるまい",
content: "",
partsType: LiplisDefine.PARTS_TYPE_TITLE,settingIdx: -1,
initValue : 0,
trueValue: 0,
rowHeight: CGFloat(26)
)
)
let lpsNewsRunOut : MsgSettingViewCell =
MsgSettingViewCell(
title: "",
content: "",
partsType: LiplisDefine.PARTS_TYPE_RADIO,settingIdx: 11,
initValue : widget.os.lpsNewsRunOut,
trueValue: 0,
rowHeight: CGFloat(0)
)
lpsNewsRunOut.appendChild(
MsgSettingViewCell(
title: "ランダムおしゃべり",
content: "",
partsType: LiplisDefine.PARTS_TYPE_RADIO_CHILD,
settingIdx: 11,
initValue : 0,
trueValue: 0,
rowHeight: CGFloat(45)
)
)
lpsNewsRunOut.appendChild(
MsgSettingViewCell(
title: "何もしない",
content: "",
partsType: LiplisDefine.PARTS_TYPE_RADIO_CHILD,
settingIdx: 11,
initValue : 0,
trueValue: 1,
rowHeight: CGFloat(45)
)
)
self.tblItems.append(lpsNewsRunOut)
}
//============================================================
//
//イベントハンドラ
//
//============================================================
internal override func viewDidLoad() {
super.viewDidLoad()
}
internal override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
/*
ビュー呼び出し時
*/
internal override func viewWillAppear(animated: Bool) {
self.setSize()
}
/*
画面を閉じる
*/
internal func closeMe(sender: AnyObject) {
self.widget.setWindow()
dismissViewControllerAnimated(true, completion: nil)
}
/*
Cellが選択された際に呼び出される.
*/
internal func tableView(tableView: UITableView, indexPath: NSIndexPath)->NSIndexPath? {
print("Num: \(indexPath.row)")
print("Value: \(tblItems[indexPath.row].title)")
return nil;
}
/*
Cellの総数を返す.
*/
internal func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print("numberOfRowsInSection")
return tblItems.count
}
/*
Editableの状態にする.
*/
internal func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
print("canEditRowAtIndexPath")
return true
}
/*
特定の行のボタン操作を有効にする.
*/
internal func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
print("commitEdittingStyle:\(editingStyle)")
}
/*
Cellに値を設定する.
*/
internal func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
print("cellForRowAtIndexPath")
return settingCell(indexPath)
}
/*
セル設定
*/
internal func settingCell(indexPath : NSIndexPath) -> UITableViewCell!
{
let cellSetting : MsgSettingViewCell = tblItems[indexPath.row]
switch(cellSetting.partsType)
{
case 0://タイトル
let cell : CtvCellWidgetTopicTitle = self.tblSetting.dequeueReusableCellWithIdentifier("CtvCellWidgetTopicTitle", forIndexPath: indexPath) as! CtvCellWidgetTopicTitle
cell.lblTitle.text = cellSetting.title
return cell
case 1://チェックボタン
let cell : CtvCellWidgetTopicCheck = self.tblSetting.dequeueReusableCellWithIdentifier("CtvCellWidgetTopicCheck", forIndexPath: indexPath) as! CtvCellWidgetTopicCheck
cell.setView(self)
cell.lblTitle.text = cellSetting.title
cell.lblContent.text = cellSetting.content
cell.setSize(self.view.frame.width)
cell.setVal(cellSetting.settingIdx,val: cellSetting.initValue)
return cell
case 3://ラジオボタン
let cell : CtvCellWidgetTopicRadio = self.tblSetting.dequeueReusableCellWithIdentifier("CtvCellWidgetTopicRadio", forIndexPath: indexPath) as! CtvCellWidgetTopicRadio
cell.setView(self)
cell.setRadio(self.view.frame.width, childList: cellSetting.childList)
cell.setVal(cellSetting.settingIdx,val: cellSetting.initValue)
return cell
default:
let cell : CtvCellWidgetTopicTitle = self.tblSetting.dequeueReusableCellWithIdentifier("CtvCellSettingTitle", forIndexPath: indexPath) as! CtvCellWidgetTopicTitle
cell.lblTitle.text = cellSetting.title
return cell
}
}
internal func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
print("estimatedHeightForRowAtIndexPath" + String(indexPath.row))
return CGFloat(30)
}
internal func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
print("estimatedHeightForRowAtIndexPath" + String(indexPath.row))
let cellSetting : MsgSettingViewCell = tblItems[indexPath.row]
return cellSetting.rowHeight
}
/*
チェックとスイッチの操作
*/
internal func selectCheck(settingIdx : Int, val : Bool)
{
print("チェック選択 idx:" + String(settingIdx) + " val:" + String(LiplisUtil.bit2Int(val)))
widget.os.saveDataFromIdx(settingIdx, val: LiplisUtil.bit2Int(val))
}
internal func selectVal(settingIdx : Int, val : Int)
{
print("ラジオ選択 idx:" + String(settingIdx) + " val:" + String(val))
widget.os.saveDataFromIdx(settingIdx, val: val)
}
//============================================================
//
//アクティビティ操作
//
//============================================================
/*
サイズ設定
*/
private func setSize()
{
// 現在のデバイスの向きを取得.
let deviceOrientation: UIDeviceOrientation! = UIDevice.currentDevice().orientation
// 向きの判定.
if UIDeviceOrientationIsLandscape(deviceOrientation) {
//横向きの判定
} else if UIDeviceOrientationIsPortrait(deviceOrientation){
//縦向きの判定
}
let displayWidth: CGFloat = self.view.frame.width
let displayHeight: CGFloat = self.view.frame.height
//let barHeight: CGFloat = UIApplication.sharedApplication().statusBarFrame.size.height
self.lblTitle.frame = CGRectMake(0, 0, displayWidth, LiplisDefine.labelHight)
self.btnBack.frame = CGRectMake(self.lblTitle.frame.origin.x + 5,self.lblTitle.frame.origin.y + 25, displayWidth/6, 30)
self.tblSetting.frame = CGRectMake(0, self.lblTitle.frame.height, displayWidth, displayHeight - self.lblTitle.frame.height)
//テーブルのリロード
self.tblSetting.reloadData()
}
//============================================================
//
//回転ハンドラ
//
//============================================================
/*
画面の向き変更時イベント
*/
internal override func viewDidAppear(animated: Bool) {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "onOrientationChange:", name: UIDeviceOrientationDidChangeNotification, object: nil)
}
internal func onOrientationChange(notification: NSNotification){
self.setSize()
}
}
| mit | 968b4be19caf2139861eecf8a1a4b8b0 | 31.828924 | 178 | 0.532825 | 5.067792 | false | false | false | false |
weipin/jewzruxin | Jewzruxin/Source/HTTP/URITemplate.swift | 1 | 24267 | //
// URITemplate.swift
//
// Copyright (c) 2015 Weipin Xia
//
// 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
/**
Expand a URITemplate. This is a convenient version of the method `process` for the class `URITemplate`
- Parameter template: The URITemplate to expand.
- Parameter values: The object to provide values when the function expands the URI Template. It can be a Swift Dictionary, a NSDictionary, a NSDictionary subclass, or any object has method `objectForKey`.
- Returns: The expanded URITemplate.
*/
public func ExpandURITemplate(template: String, values: [String: AnyObject] = [:]) -> String {
let (URLString, errors) = URITemplate().process(template, values: values)
if errors.count > 0 {
NSLog("ExpandURITemplate error for template: \(template)")
for (error, position) in errors {
NSLog("ExpandURITemplate error: \(error), position: \(position).")
}
}
return URLString
}
/**
This class is an implementation of URI Template (RFC6570). You probably wouldn't need to use this class directly but the convenient function `ExpandURITemplate`.
*/
public class URITemplate {
public enum Error {
case MalformedPctEncodedInLiteral
case NonLiteralsCharacterFoundInLiteral
case ExpressionEndedWithoutClosing
case NonExpressionFound
case InvalidOperator
case MalformedVarSpec
}
enum State {
case ScanningLiteral
case ScanningExpression
}
enum ExpressionState {
case ScanningVarName
case ScanningModifier
}
enum BehaviorAllow {
case U // any character not in the unreserved set will be encoded
case UR // any character not in the union of (unreserved / reserved / pct-encoding) will be encoded
}
struct Behavior {
var first: String
var sep: String
var named: Bool
var ifemp: String
var allow: BehaviorAllow
}
struct Constants {
static let BehaviorTable = [
"NUL": Behavior(first: "", sep: ",", named: false, ifemp: "", allow: .U),
"+" : Behavior(first: "", sep: ",", named: false, ifemp: "", allow: .UR),
"." : Behavior(first: ".", sep: ".", named: false, ifemp: "", allow: .U),
"/" : Behavior(first: "/", sep: "/", named: false, ifemp: "", allow: .U),
";" : Behavior(first: ";", sep: ";", named: true, ifemp: "", allow: .U),
"?" : Behavior(first: "?", sep: "&", named: true, ifemp: "=", allow: .U),
"&" : Behavior(first: "&", sep: "&", named: true, ifemp: "=", allow: .U),
"#" : Behavior(first: "#", sep: ",", named: false, ifemp: "", allow: .UR),
]
static let LEGAL = "!*'();:@&=+$,/?%#[]" // Legal URL characters (based on RFC 3986)
static let HEXDIG = "0123456789abcdefABCDEF"
static let DIGIT = "0123456789"
static let RESERVED = ":/?#[]@!$&'()*+,;="
static let UNRESERVED = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~" // 66
static let VARCHAR = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_" // exclude pct-encoded
}
// Pct-encoded ignored
func encodeLiteralString(string: String) -> String {
let charactersToLeaveUnescaped = Constants.RESERVED + Constants.UNRESERVED
let set = NSCharacterSet(charactersInString: charactersToLeaveUnescaped)
guard let s = string.stringByAddingPercentEncodingWithAllowedCharacters(set) else {
NSLog("encodeLiteralString failed: \(string)")
return ""
}
return s
}
func encodeLiteralCharacter(character: Character) -> String {
return encodeLiteralString(String(character))
}
func encodeStringWithBehaviorAllowSet(string: String, allow: BehaviorAllow) -> String {
var result = ""
switch allow {
case .U:
let s = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, string, Constants.UNRESERVED as NSString, Constants.LEGAL as NSString, CFStringBuiltInEncodings.UTF8.rawValue)
result = s as String
case .UR:
result = encodeLiteralString(string)
}
return result
}
func stringOfAnyObject(object: AnyObject?) -> String? {
if object == nil {
return nil
}
if let str = object as? String {
return str
}
if let str = object?.stringValue {
return str
}
return nil
}
func findOperatorInExpression(expression: String) -> (op: Character?, error: URITemplate.Error?) {
if expression.isEmpty {
return (nil, .InvalidOperator)
}
let c = expression.characters.count
var op: Character? = nil
let startCharacher = expression[expression.startIndex]
if startCharacher == "%" {
if c < 3 {
return (nil, .InvalidOperator)
}
let c1 = expression[expression.startIndex.advancedBy(1)]
let c2 = expression[expression.startIndex.advancedBy(2)]
if Constants.HEXDIG.characters.indexOf(c1) == nil {
return (nil, .InvalidOperator)
}
if Constants.HEXDIG.characters.indexOf(c2) == nil {
return (nil, .InvalidOperator)
}
var str = "%" + String(c1) + String(c2)
str = str.stringByRemovingPercentEncoding ?? ""
op = str[str.startIndex]
} else {
op = startCharacher
}
if op != nil {
if (Constants.BehaviorTable[String(op!)] == nil) {
if Constants.VARCHAR.characters.indexOf(op!) == nil {
return (nil, .InvalidOperator)
} else {
return (nil, nil)
}
}
}
return (op, nil)
}
func expandVarSpec(varName: String, modifier: Character?, prefixLength :Int, behavior: Behavior, values: AnyObject) -> String {
var result = ""
if varName == "" {
return result
}
var value: AnyObject?
if let d = values as? [String: AnyObject] {
value = d[varName]
} else {
value = values.objectForKey?(varName)
}
if let str = stringOfAnyObject(value) {
if behavior.named {
result += encodeLiteralString(varName)
if str == "" {
result += behavior.ifemp
return result
} else {
result += "="
}
}
if modifier == ":" && prefixLength < str.characters.count {
let prefix = str[str.startIndex ..< str.startIndex.advancedBy(prefixLength)]
result += encodeStringWithBehaviorAllowSet(prefix, allow: behavior.allow)
} else {
result += encodeStringWithBehaviorAllowSet(str, allow: behavior.allow)
}
} else {
if modifier == "*" {
if behavior.named {
if let ary = value as? [AnyObject] {
var c = 0
for v in ary {
let str = stringOfAnyObject(v)
if str == nil {
continue
}
if c > 0 {
result += behavior.sep
}
result += encodeLiteralString(varName)
if str! == "" {
result += behavior.ifemp
} else {
result += "="
result += encodeStringWithBehaviorAllowSet(str!, allow: behavior.allow)
}
++c
}
} else if let dict = value as? Dictionary<String, AnyObject> {
var keys = Array(dict.keys)
keys = keys.sort {
$0.localizedCaseInsensitiveCompare($1) == NSComparisonResult.OrderedDescending
}
var c = 0
for k in keys {
var str: String? = nil
if let v: AnyObject = dict[k] {
str = stringOfAnyObject(v)
}
if str == nil {
continue
}
if c > 0 {
result += behavior.sep
}
result += encodeLiteralString(k)
if str == "" {
result += behavior.ifemp
} else {
result += "="
result += encodeStringWithBehaviorAllowSet(str!, allow: behavior.allow)
}
++c
}
} else {
NSLog("Value for varName %@ is not a list or a pair", varName)
}
} else {
if let ary = value as? [AnyObject] {
var c = 0
for v in ary {
let str = stringOfAnyObject(v)
if str == nil {
continue
}
if c > 0 {
result += behavior.sep
}
result += encodeStringWithBehaviorAllowSet(str!, allow: behavior.allow)
++c
}
} else if let dict = value as? Dictionary<String, AnyObject> {
var keys = Array(dict.keys)
keys = keys.sort() {
$0.localizedCaseInsensitiveCompare($1) == NSComparisonResult.OrderedDescending
}
var c = 0
for k in keys {
var str: String? = nil
if let v: AnyObject = dict[k] {
str = stringOfAnyObject(v)
}
if str == nil {
continue
}
if c > 0 {
result += behavior.sep
}
result += encodeLiteralString(k)
result += "="
result += encodeStringWithBehaviorAllowSet(str!, allow: behavior.allow)
++c
}
} else {
NSLog("Value for varName %@ is not a list or a pair", varName)
}
} // if behavior.named
} else {
// no explode modifier is given
var flag = true
if behavior.named {
result += encodeLiteralString(varName)
if value == nil {
result += behavior.ifemp
flag = false
} else {
result += "="
}
if flag {
}
} // if behavior.named
if let ary = value as? [AnyObject] {
var c = 0
for v in ary {
guard let str = stringOfAnyObject(v) else {
continue
}
if c > 0 {
result += ","
}
result += encodeStringWithBehaviorAllowSet(str, allow: behavior.allow)
++c
}
} else if let dict = value as? Dictionary<String, AnyObject> {
var keys = Array(dict.keys)
keys = keys.sort() {
$0.localizedCaseInsensitiveCompare($1) == NSComparisonResult.OrderedDescending
}
var c = 0
for k in keys {
var str: String? = nil
if let v: AnyObject = dict[k] {
str = stringOfAnyObject(v)
}
if str == nil {
continue
}
if c > 0 {
result += ","
}
result += encodeStringWithBehaviorAllowSet(k, allow: behavior.allow)
result += ","
result += encodeStringWithBehaviorAllowSet(str!, allow: behavior.allow)
++c
}
} else {
}
} // if modifier == "*"
}
return result
}
/**
Expand a URITemplate.
- Parameter template: The URITemplate to expand
- Parameter values: The object to provide values when the method expands the URITemplate. It can be a Swift Dictionary, a NSDictionary, a NSDictionary subclass, or any object has method `objectForKey`.
- Returns: (result, errors)
- result: The expanded URITemplate
- errors: An array of tuple (URITemplateError, Int) which represents the errors this method recorded in expanding the URITemplate. The first element indicates the type of error, the second element indicates the position (index) of the error in the URITemplate.
*/
public func process(template: String, values: AnyObject) -> (String, [(URITemplate.Error, Int)]) {
var state: State = .ScanningLiteral
var result = ""
var pctEncoded = ""
var expression = ""
var expressionCount = 0
var errors = [(Error, Int)]()
for (index, c) in template.characters.enumerate() {
switch state {
case .ScanningLiteral:
if c == "{" {
state = .ScanningExpression
++expressionCount
} else if (!pctEncoded.isEmpty) {
switch pctEncoded.characters.count {
case 1:
if Constants.HEXDIG.characters.indexOf(c) != nil {
pctEncoded += String(c)
} else {
errors.append((.MalformedPctEncodedInLiteral, index))
result += encodeLiteralString(pctEncoded)
result += encodeLiteralCharacter(c)
state = .ScanningLiteral
pctEncoded = ""
}
case 2:
if Constants.HEXDIG.characters.indexOf(c) != nil {
pctEncoded += String(c)
result += pctEncoded
state = .ScanningLiteral
pctEncoded = ""
} else {
errors.append((.MalformedPctEncodedInLiteral, index))
result += encodeLiteralString(pctEncoded)
result += encodeLiteralCharacter(c)
state = .ScanningLiteral
pctEncoded = ""
}
default:
assert(false)
}
} else if c == "%" {
pctEncoded += String(c)
state = .ScanningLiteral
} else if Constants.UNRESERVED.characters.indexOf(c) != nil || Constants.RESERVED.characters.indexOf(c) != nil {
result += String(c)
} else {
errors.append((.NonLiteralsCharacterFoundInLiteral, index))
result += String(c)
}
case .ScanningExpression:
if c == "}" {
state = .ScanningLiteral
// Process expression
let (op, error) = findOperatorInExpression(expression)
if error != nil {
errors.append((.MalformedPctEncodedInLiteral, index))
result = result + "{" + expression + "}"
} else {
let operatorString = (op != nil) ? String(op!) : "NUL"
let behavior = Constants.BehaviorTable[operatorString]!;
// Skip the operator
var skipCount = 0
if op != nil {
if expression.hasPrefix("%") {
skipCount = 3
} else {
skipCount = 1
}
}
// Process varspec-list
var varCount = 0
var eError: URITemplate.Error?
var estate = ExpressionState.ScanningVarName
var varName = ""
var modifier: Character?
var prefixLength :Int = 0
var str = expression[expression.startIndex.advancedBy(skipCount) ..< expression.endIndex]
str = str.stringByRemovingPercentEncoding ?? ""
var jIndex = 0
for (index, j) in str.characters.enumerate() {
jIndex = index
if j == "," {
// Process VarSpec
if varCount == 0 {
result += behavior.first
} else {
result += behavior.sep
}
let expanded = expandVarSpec(varName, modifier:modifier, prefixLength:prefixLength, behavior:behavior, values:values)
result += expanded
++varCount
// Reset for next VarSpec
eError = nil
estate = .ScanningVarName
varName = ""
modifier = nil
prefixLength = 0
continue
}
switch estate {
case .ScanningVarName:
if (j == "*" || j == ":") {
if varName.isEmpty {
eError = .MalformedVarSpec
break;
}
modifier = j
estate = .ScanningModifier
continue
}
if Constants.VARCHAR.characters.indexOf(j) != nil || j == "." {
varName += String(j)
} else {
eError = .MalformedVarSpec
break;
}
case .ScanningModifier:
if modifier == "*" {
eError = .MalformedVarSpec
break;
} else if modifier == ":" {
if Constants.DIGIT.characters.indexOf(j) != nil {
let intValue = Int(String(j))
prefixLength = prefixLength * 10 + intValue!
if prefixLength >= 1000 {
eError = .MalformedVarSpec
break;
}
} else {
eError = .MalformedVarSpec
break;
}
} else {
assert(false)
}
}
} // for expression
if (eError != nil) {
let e = eError!
let ti = index + jIndex
errors.append((e, ti))
let remainingExpression = str[str.startIndex.advancedBy(jIndex) ..< str.endIndex]
if op != nil {
result = result + "{" + String(op!) + remainingExpression + "}"
} else {
result = result + "{" + remainingExpression + "}"
}
} else {
// Process VarSpec
if varCount == 0 {
result += behavior.first
} else {
result += behavior.sep
}
let expanded = expandVarSpec(varName, modifier: modifier, prefixLength: prefixLength, behavior: behavior, values: values)
result += expanded
}
} // varspec-list
} else {
expression += String(c)
}
} // switch
} // for
// Handle ending
let endingIndex: Int = template.characters.count
switch state {
case .ScanningLiteral:
if !pctEncoded.isEmpty {
errors.append((.MalformedPctEncodedInLiteral, endingIndex))
result += encodeLiteralString(pctEncoded)
}
case .ScanningExpression:
errors.append((.ExpressionEndedWithoutClosing, endingIndex))
result = result + "{" + expression
}
if expressionCount == 0 {
errors.append((.NonExpressionFound, endingIndex))
}
return (result, errors)
} // process
} // URITemplate
| mit | 921ff4a70b54c1e570802328bee914ad | 39.784874 | 266 | 0.433881 | 6.262452 | false | false | false | false |
ali-zahedi/AZViewer | AZViewer/AZSegmentControl.swift | 1 | 1834 | //
// AZSegmentControl.swift
// AZViewer
//
// Created by Ali Zahedi on 3/23/1396 AP.
// Copyright © 1396 AP Ali Zahedi. All rights reserved.
//
import UIKit
public class AZSegmentControl: UISegmentedControl {
// MARK: Public
public var aZConstraints: AZConstraint!
public var font: UIFont = AZStyle.shared.sectionSegmentControlFont {
didSet{
self.updateFont()
}
}
public var titleColor: UIColor = AZStyle.shared.sectionSegmentContrlTitleColor{
didSet{
self.updateFont()
}
}
// MARK: Private
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
// MARK: Init
public override init(frame: CGRect) {
super.init(frame: frame)
self.defaultInit()
}
public override init(items: [Any]?) {
super.init(items: items)
self.defaultInit()
if let v = items, v.count > 0 {
self.selectedSegmentIndex = v.count - 1
}
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.defaultInit()
}
// MARK: Function
fileprivate func defaultInit(){
self.aZConstraints = AZConstraint(view: self)
self.tintColor = AZStyle.shared.sectionSegmentContrlTintColor
self.updateFont()
}
// update font
fileprivate func updateFont(){
let attr: [NSObject : AnyObject] = [
NSForegroundColorAttributeName as NSObject: self.titleColor,
NSFontAttributeName as NSObject: self.font
]
self.setTitleTextAttributes(attr, for: .normal)
}
}
| apache-2.0 | 4491decebf66be4c1f6d010a411a1f59 | 24.816901 | 83 | 0.602837 | 4.617128 | false | false | false | false |
dmitryrybakov/19test | 19testTests/_9testTests.swift | 1 | 2601 | //
// _9testTests.swift
// 19testTests
//
// Created by Dmitry Rybakov on 5/8/16.
// Copyright © 2016 Dmitry Rybakov. All rights reserved.
//
import XCTest
@testable import _9test
class _9testTests: XCTestCase {
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 testModelMapping() {
let item = MarvelCharacter.marvelCharacterWithDictionary(["id": 1111, "name": "3DMan", "description": "LongDescription"])
XCTAssertTrue(item.name == "3DMan")
XCTAssertTrue(item.characterId == 1111)
XCTAssertTrue(item.characterDescription == "LongDescription")
}
// This is just a demo. The project does not contian fixture MarvelCharactersResponse.json
func testNetworkingManager() {
let baseURL = NSURL(string:Constants.Common.BaseAPIURL)
OHHTTPStubs.stubRequestsPassingTest({ (request) -> Bool in
return request.URL!.host == baseURL!.host && request.URL!.path == baseURL!.path
}) { (request) -> OHHTTPStubsResponse in
// Stub it with our stub file
let fixture = OHPathForFile("MarvelCharactersResponse.json", self.dynamicType)
return OHHTTPStubsResponse(fileAtPath:fixture!,
statusCode:200, headers:["Content-Type": "application/json"])
}
let man = NetworkManager()
let expectation = self.expectationWithDescription("NetworkManager async testing")
man.getCharactersWithName("", offset: 0, completionBlock: { (characters, total) -> (Void) in
expectation.fulfill()
}) { (error) -> (Void) in
XCTFail("Request failed with error: \(error?.description)")
}
self.waitForExpectationsWithTimeout(5.0) { (error) -> Void in
if let errorObject = error {
XCTFail("Expectation Failed with error: \(errorObject.description)")
}
}
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
UIImage(named:"placeholder")!.imageWithSizeKeepAspect(CGSizeMake(100.0, 100.0), fitToRect:false)
}
}
}
| artistic-2.0 | b84d0713f14a8c2b90a742e0609eeaab | 34.135135 | 129 | 0.598846 | 5.019305 | false | true | false | false |
yuxiuyu/TrendBet | TrendBetting_0531换首页/Pods/Charts/Source/Charts/Jobs/ZoomViewJob.swift | 4 | 2128 | //
// ZoomViewJob.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
#if !os(OSX)
import UIKit
#endif
@objc(ZoomChartViewJob)
open class ZoomViewJob: ViewPortJob
{
internal var scaleX: CGFloat = 0.0
internal var scaleY: CGFloat = 0.0
internal var axisDependency: YAxis.AxisDependency = .left
@objc public init(
viewPortHandler: ViewPortHandler,
scaleX: CGFloat,
scaleY: CGFloat,
xValue: Double,
yValue: Double,
transformer: Transformer,
axis: YAxis.AxisDependency,
view: ChartViewBase)
{
super.init(
viewPortHandler: viewPortHandler,
xValue: xValue,
yValue: yValue,
transformer: transformer,
view: view)
self.scaleX = scaleX
self.scaleY = scaleY
self.axisDependency = axis
}
open override func doJob()
{
guard
let viewPortHandler = viewPortHandler,
let transformer = transformer,
let view = view
else { return }
var matrix = viewPortHandler.setZoom(scaleX: scaleX, scaleY: scaleY)
viewPortHandler.refresh(newMatrix: matrix, chart: view, invalidate: false)
let yValsInView = (view as! BarLineChartViewBase).getAxis(axisDependency).axisRange / Double(viewPortHandler.scaleY)
let xValsInView = (view as! BarLineChartViewBase).xAxis.axisRange / Double(viewPortHandler.scaleX)
var pt = CGPoint(
x: CGFloat(xValue - xValsInView) / 2.0,
y: CGFloat(yValue + yValsInView) / 2.0
)
transformer.pointValueToPixel(&pt)
matrix = viewPortHandler.translate(pt: pt)
viewPortHandler.refresh(newMatrix: matrix, chart: view, invalidate: false)
(view as! BarLineChartViewBase).calculateOffsets()
view.setNeedsDisplay()
}
}
| apache-2.0 | 6b6f88cdf55099499e66e48256c170b5 | 27.373333 | 124 | 0.616541 | 4.91455 | false | false | false | false |
creatubbles/ctb-api-swift | CreatubblesAPIClientUnitTests/Spec/ErrorTransformerSpec.swift | 1 | 2928 | //
// CreationUploadMapper.swift
// CreatubblesAPIClient
//
// Copyright (c) 2017 Creatubbles Pte. Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Quick
import Nimble
@testable import CreatubblesAPIClient
class ErrorTransformerSpec: QuickSpec {
private let jsonAPIErrorJSON = "{\"errors\":[{\"code\":\"object-gallery_submission-invalid-creation_id\",\"status\":\"422\",\"title\":\"validation error\",\"detail\":\"has already been taken\",\"source\":{\"pointer\":\"/data/attributes/creation_id\"}}]}"
private let serverErrorJSON = "{\"status\":422,\"error\":\"Unprocessable Entity\"}"
override func spec() {
describe("Error transformer") {
it("Should parse JSONAPI error") {
let dictionary = JSONUtils.dictionaryFromJSONString(self.jsonAPIErrorJSON)
let errors = ErrorTransformer.errorsFromResponse(dictionary)
let error = errors.first
expect(errors).notTo(beNil())
expect(errors).notTo(beEmpty())
expect(error).notTo(beNil())
expect(error?.code) == "object-gallery_submission-invalid-creation_id"
expect(error?.status) == 422
expect(error?.title) == "validation error"
expect(error?.detail) == "has already been taken"
}
it("Should parse non-JSONAPI error") {
let dictionary = JSONUtils.dictionaryFromJSONString(self.serverErrorJSON)
let errors = ErrorTransformer.errorsFromResponse(dictionary)
let error = errors.first
expect(errors).notTo(beNil())
expect(errors).notTo(beEmpty())
expect(error).notTo(beNil())
expect(error?.status) == 422
expect(error?.title) == "Unprocessable Entity"
}
}
}
}
| mit | f8241299a0853b4684860767513d2275 | 45.47619 | 258 | 0.654713 | 4.807882 | false | false | false | false |
AaronMT/firefox-ios | Client/Frontend/Theme/ThemeManager.swift | 6 | 3509 | /* 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
enum ThemeManagerPrefs: String {
case systemThemeIsOn = "prefKeySystemThemeSwitchOnOff"
case automaticSwitchIsOn = "prefKeyAutomaticSwitchOnOff"
case automaticSliderValue = "prefKeyAutomaticSliderValue"
case themeName = "prefKeyThemeName"
}
class ThemeManager {
static let instance = ThemeManager()
var current: Theme = themeFrom(name: UserDefaults.standard.string(forKey: ThemeManagerPrefs.themeName.rawValue)) {
didSet {
UserDefaults.standard.set(current.name, forKey: ThemeManagerPrefs.themeName.rawValue)
NotificationCenter.default.post(name: .DisplayThemeChanged, object: nil)
}
}
var currentName: BuiltinThemeName {
return BuiltinThemeName(rawValue: ThemeManager.instance.current.name) ?? .normal
}
var automaticBrightnessValue: Float = UserDefaults.standard.float(forKey: ThemeManagerPrefs.automaticSliderValue.rawValue) {
didSet {
UserDefaults.standard.set(automaticBrightnessValue, forKey: ThemeManagerPrefs.automaticSliderValue.rawValue)
}
}
var automaticBrightnessIsOn: Bool = UserDefaults.standard.bool(forKey: ThemeManagerPrefs.automaticSwitchIsOn.rawValue) {
didSet {
UserDefaults.standard.set(automaticBrightnessIsOn, forKey: ThemeManagerPrefs.automaticSwitchIsOn.rawValue)
updateCurrentThemeBasedOnScreenBrightness()
}
}
var systemThemeIsOn: Bool {
didSet {
UserDefaults.standard.set(systemThemeIsOn, forKey: ThemeManagerPrefs.systemThemeIsOn.rawValue)
}
}
private init() {
UserDefaults.standard.register(defaults: [ThemeManagerPrefs.systemThemeIsOn.rawValue: true])
systemThemeIsOn = UserDefaults.standard.bool(forKey: ThemeManagerPrefs.systemThemeIsOn.rawValue)
NotificationCenter.default.addObserver(self, selector: #selector(brightnessChanged), name: UIScreen.brightnessDidChangeNotification, object: nil)
}
// UIViewControllers / UINavigationControllers need to have `preferredStatusBarStyle` and call this.
var statusBarStyle: UIStatusBarStyle {
if #available(iOS 13.0, *) {
if UIScreen.main.traitCollection.userInterfaceStyle == .dark && currentName == .normal {
return .darkContent
}
}
return currentName == .dark ? .lightContent : .default
}
func updateCurrentThemeBasedOnScreenBrightness() {
let prefValue = UserDefaults.standard.float(forKey: ThemeManagerPrefs.automaticSliderValue.rawValue)
let screenLessThanPref = Float(UIScreen.main.brightness) < prefValue
if screenLessThanPref, self.currentName == .normal {
self.current = DarkTheme()
} else if !screenLessThanPref, self.currentName == .dark {
self.current = NormalTheme()
}
}
@objc private func brightnessChanged() {
guard automaticBrightnessIsOn else { return }
updateCurrentThemeBasedOnScreenBrightness()
}
}
fileprivate func themeFrom(name: String?) -> Theme {
guard let name = name, let theme = BuiltinThemeName(rawValue: name) else { return NormalTheme() }
switch theme {
case .dark:
return DarkTheme()
default:
return NormalTheme()
}
}
| mpl-2.0 | fa12a5f42d441ca9cf73ad2d774ed90e | 37.988889 | 153 | 0.704474 | 5.100291 | false | false | false | false |
rcasanovan/Social-Feed | Social Feed/Pods/HanekeSwift/Haneke/UIImage+Haneke.swift | 20 | 3347 | //
// UIImage+Haneke.swift
// Haneke
//
// Created by Hermes Pique on 8/10/14.
// Copyright (c) 2014 Haneke. All rights reserved.
//
import UIKit
extension UIImage {
func hnk_imageByScaling(toSize size: CGSize) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, !hnk_hasAlpha(), 0.0)
draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
let resizedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return resizedImage!
}
func hnk_hasAlpha() -> Bool {
guard let alphaInfo = self.cgImage?.alphaInfo else { return false }
switch alphaInfo {
case .first, .last, .premultipliedFirst, .premultipliedLast, .alphaOnly:
return true
case .none, .noneSkipFirst, .noneSkipLast:
return false
}
}
func hnk_data(compressionQuality: Float = 1.0) -> Data! {
let hasAlpha = self.hnk_hasAlpha()
let data = hasAlpha ? UIImagePNGRepresentation(self) : UIImageJPEGRepresentation(self, CGFloat(compressionQuality))
return data
}
func hnk_decompressedImage() -> UIImage! {
let originalImageRef = self.cgImage
let originalBitmapInfo = originalImageRef?.bitmapInfo
guard let alphaInfo = originalImageRef?.alphaInfo else { return UIImage() }
// See: http://stackoverflow.com/questions/23723564/which-cgimagealphainfo-should-we-use
var bitmapInfo = originalBitmapInfo
switch alphaInfo {
case .none:
let rawBitmapInfoWithoutAlpha = (bitmapInfo?.rawValue)! & ~CGBitmapInfo.alphaInfoMask.rawValue
let rawBitmapInfo = rawBitmapInfoWithoutAlpha | CGImageAlphaInfo.noneSkipFirst.rawValue
bitmapInfo = CGBitmapInfo(rawValue: rawBitmapInfo)
case .premultipliedFirst, .premultipliedLast, .noneSkipFirst, .noneSkipLast:
break
case .alphaOnly, .last, .first: // Unsupported
return self
}
let colorSpace = CGColorSpaceCreateDeviceRGB()
let pixelSize = CGSize(width: self.size.width * self.scale, height: self.size.height * self.scale)
guard let context = CGContext(data: nil, width: Int(ceil(pixelSize.width)), height: Int(ceil(pixelSize.height)), bitsPerComponent: (originalImageRef?.bitsPerComponent)!, bytesPerRow: 0, space: colorSpace, bitmapInfo: (bitmapInfo?.rawValue)!) else {
return self
}
let imageRect = CGRect(x: 0, y: 0, width: pixelSize.width, height: pixelSize.height)
UIGraphicsPushContext(context)
// Flip coordinate system. See: http://stackoverflow.com/questions/506622/cgcontextdrawimage-draws-image-upside-down-when-passed-uiimage-cgimage
context.translateBy(x: 0, y: pixelSize.height)
context.scaleBy(x: 1.0, y: -1.0)
// UIImage and drawInRect takes into account image orientation, unlike CGContextDrawImage.
self.draw(in: imageRect)
UIGraphicsPopContext()
guard let decompressedImageRef = context.makeImage() else {
return self
}
let scale = UIScreen.main.scale
let image = UIImage(cgImage: decompressedImageRef, scale:scale, orientation:UIImageOrientation.up)
return image
}
}
| apache-2.0 | aafcf95f47d76d7d6597cdb00383c860 | 40.320988 | 256 | 0.659695 | 4.850725 | false | false | false | false |
mlilback/MJLCommon | Sources/MJLCommon/extensions/NSViewController+Alerts.swift | 1 | 3927 | //
// NSViewController+Alerts.swift
//
// Copyright ©2017 Mark Lilback. This file is licensed under the ISC license.
//
import Cocoa
#if canImport(SwiftyUserDefaults)
import SwiftyUserDefaults
#endif
public extension NSViewController {
/// Displays an alert sheet to confirm an action. If the defaults value for the suppressionKey is true, the handler is immediately called with true.
///
/// - Parameters:
/// - message: The message to display
/// - infoText: The informative text to display
/// - buttonTitle: The title for the rightmost/action button
/// - defaultToCancel: true if the cancel button should be the default button. defaults to false
/// - suppressionKey: Optional UserDefaults key to set to true if user selects to suppress future alerts. If nil, suppression checkbox is not displayed. Defaults to nil. If the key value is true, no sheet is shown and the handler is immediately called with a value of true.
/// - handler: called after the user has selected an action
/// - confirmed: true if the user selected the action button
func confirmAction(message: String, infoText: String, buttonTitle: String, cancelTitle: String = NSLocalizedString("Cancel", comment: ""), defaultToCancel: Bool = false, suppressionKey: String? = nil, handler: @escaping (_ confirmed: Bool) -> Void)
{
if let key = suppressionKey, UserDefaults.standard.bool(forKey: key) {
handler(true)
return
}
precondition(view.window != nil,"can't call without being in a window")
let alert = NSAlert()
alert.showsSuppressionButton = suppressionKey != nil
alert.messageText = message
alert.informativeText = infoText
alert.addButton(withTitle: buttonTitle)
alert.addButton(withTitle: cancelTitle)
if defaultToCancel {
alert.buttons[0].keyEquivalent = ""
alert.buttons[1].keyEquivalent = "\r"
}
alert.beginSheetModal(for: self.view.window!, completionHandler: { [weak alert] response in
if let key = suppressionKey, alert?.suppressionButton?.state ?? .off == .on {
UserDefaults.standard.set(true, forKey: key)
}
handler(response == .alertFirstButtonReturn)
})
}
#if canImport(SwiftyUserDefaults)
/// Displays an alert sheet to confirm an action. This versions takes a supression key in the format used by SwiftyUserDefaults. If such a value is not supplied or is a string, another version of this function is called. If the defaults value for the suppressionKey is true, the handler is immediately called with true.
///
/// - Parameters:
/// - message: The message to display
/// - infoText: The informative text to display
/// - buttonTitle: The title for the rightmost/action button
/// - defaultToCancel: true if the cancel button should be the default button. defaults to false
/// - suppressionKey: Optional UserDefaults key to set to true if user selects to suppress future alerts
/// - handler: called after the user has selected an action
/// - confirmed: true if the user selected the action button
func confirmAction(message: String, infoText: String, buttonTitle: String, cancelTitle: String = NSLocalizedString("Cancel", comment: ""), defaultToCancel: Bool = false, suppressionKey: DefaultsKey<Bool>, handler: @escaping (_ confirmed: Bool) -> Void)
{
guard !UserDefaults.standard[suppressionKey] else {
handler(true)
return
}
let alert = NSAlert()
alert.showsSuppressionButton = true
alert.messageText = message
alert.informativeText = infoText
alert.addButton(withTitle: buttonTitle)
alert.addButton(withTitle: cancelTitle)
if defaultToCancel {
alert.buttons[0].keyEquivalent = ""
alert.buttons[1].keyEquivalent = "\r"
}
alert.beginSheetModal(for: self.view.window!, completionHandler: { [weak alert] response in
if alert?.suppressionButton?.state ?? .off == .on {
UserDefaults.standard[suppressionKey] = true
}
handler(response == .alertFirstButtonReturn)
})
}
#endif
}
| isc | 58e6d716c918ffb2a5914ec163eeaa0e | 46.301205 | 320 | 0.735099 | 4.203426 | false | false | false | false |
DrawKit/DrawKit | DrawKitSwift/NSBezierPathAdditions.swift | 1 | 5575 | //
// NSBezierPathAdditions.swift
// DrawKitSwift
//
// Created by C.W. Betts on 3/8/18.
// Copyright © 2018 DrawKit. All rights reserved.
//
import DKDrawKit.DKAdditions.NSBezierPath.Text
import DKDrawKit.DKAdditions.NSBezierPath.Editing
import DKDrawKit.DKAdditions.NSBezierPath
extension NSBezierPath {
/// Determines the positions of any descender breaks for drawing underlines.
///
/// In order to correctly and accurately interrupt an underline where a glyph descender 'cuts' through
/// it, the locations of the start and end of each break must be computed. This does that by finding
/// the intersections of the glyph paths and a notional underline path. As such it is computationally
/// expensive (but is cached at a higher level).
/// - parameter str: The string in question.
/// - parameter range: The range of characters of interest within the string.
/// - parameter offset: The distance between the text baseline and the underline.
/// - returns: A list of descender break positions (`NSPoint`s).
public func descenderBreaks(for str: NSAttributedString, range: NSRange, underlineOffset offset: CGFloat) -> [NSPoint] {
return __descenderBreaks(for: str, range: range, underlineOffset: offset).map({$0.pointValue})
}
/// Converts all the information about an underline into a path that can be drawn.
///
/// Where descender breaks are passed in, the gap on either side of the break is widened by a factor
/// based on gt, which in turn is usually derived from the text size. This allows the breaks to size
/// proportionally to give pleasing results. The result may differ from Apple's standard text block
/// rendition (but note that for some fonts, DK's way works where Apple's does not, e.g. Zapfino).
/// - parameter mask: The underline attributes mask value.
/// - parameter sp: The starting position for the underline on the path.
/// - parameter length: The length of the underline on the path.
/// - parameter offset: The distance between the text baseline and the underline.
/// - parameter lineThickness: The thickness of the underline.
/// - parameter breaks: An array of descender breakpoints, or `nil`.
/// - parameter gt: Threshold value to suppress inclusion of very short "bits" of underline (a.k.a "grot").
/// - returns: A path. Stroking this path draws the underline.
public func textLinePath(withMask mask: NSUnderlineStyle, startPosition sp: CGFloat, length: CGFloat, offset: CGFloat, lineThickness: CGFloat, descenderBreaks breaks: [NSPoint]?, grotThreshold gt: CGFloat) -> NSBezierPath? {
let convBreaks: [NSValue]?
if let breaks = breaks {
convBreaks = breaks.map({return NSValue(point: $0)})
} else {
convBreaks = nil
}
return __textLinePath(withMask: mask, startPosition: sp, length: length, offset: offset, lineThickness: lineThickness, descenderBreaks: convBreaks, grotThreshold: gt)
}
/// Find the points where a line drawn horizontally across the path will intersect it.
///
/// This works by approximating the curve as a series of straight lines and testing each one for
/// intersection with the line at `y`. This is the primitive method used to determine line layout
/// rectangles - a series of calls to this is needed for each line (incrementing `y` by the
/// `lineheight`) and then rects forming from the resulting points. See `lineFragmentRects(forFixedLineheight:)`.
/// This is also used when calculating descender breaks for underlining text on a path. This method is
/// guaranteed to return an even number of (or none) results.
/// - parameter yPosition: The distance between the top edge of the bounds and the line to test.
/// - returns: A list of `NSPoint`s.
public func intersectingPointsWithHorizontalLine(atY yPosition: CGFloat) -> [NSPoint]? {
guard let preToRet = __intersectingPointsWithHorizontalLineAt(y: yPosition) else {
return nil
}
return preToRet.map({$0.pointValue})
}
@available(*, unavailable, renamed: "intersectingPointsWithHorizontalLine(atY:)")
public func intersectingPointsWithHorizontalLineAt(y yPosition: CGFloat) -> [NSPoint]? {
return intersectingPointsWithHorizontalLine(atY: yPosition)
}
/// Find rectangles within which text can be laid out to place the text within the path.
///
/// Given a lineheight value, this returns an array of `NSRect`s which are the ordered line
/// layout rects from left to right and top to bottom within the shape to layout text in. This is
/// computationally intensive, so the result should probably be cached until the shape is actually changed.
/// This works with a fixed `lineheight`, where every line is the same. Note that this method isn't really
/// suitable for use with `NSTextContainer` or Cocoa's text system in general - for flowing text using
/// `NSLayoutManager`, use `DKBezierTextContainer` which calls the `lineFragmentRect(forProposedRect:remaining:)`
/// method.
/// - parameter lineHeight: the lineheight for the lines of text.
/// - returns: A list of `NSRect`s.
public func lineFragmentRects(forFixedLineheight lineHeight: CGFloat) -> [NSRect] {
let preToRet = __lineFragmentRects(forFixedLineheight: lineHeight)
return preToRet.map({$0.rectValue})
}
}
extension NSBezierPath {
public func boundingBoxes(forPartcode pc: Int) -> [NSRect] {
let valueBoundBoxes = __boundingBoxes(forPartcode: pc)
let boxes = valueBoundBoxes.map({$0.rectValue})
return boxes
}
public func allBoundingBoxes() -> [NSRect] {
let valueBoundBoxes = __allBoundingBoxes()
let boxes = valueBoundBoxes.map({$0.rectValue})
return boxes
}
}
| mpl-2.0 | 4fef50826164111edeb6e3d872e691bc | 52.085714 | 225 | 0.745784 | 4.062682 | false | false | false | false |
enmiller/DebugOverlay | DebugOverlay/DebugOverlay.swift | 1 | 1713 | //
// DebugOverlay.swift
// DebugInformation
//
// Created by Eric Miller on 6/2/17.
// Copyright © 2017 Tiny Zepplin. All rights reserved.
//
import UIKit
/**
A built-in debugging overlay that can be used to verify design spec conformance, inspect the
view hierarchy, measure element position and dimensions, and much more.
To use the debug overlay, call the `prepareForPresentation()` method then two-finger tap on the status
bar inside of your application. A modal should appear with a list of debug options.
For simulator usage,
you need to use the `toggleVisibility()` method to make the overlay appear.
- Note: To use the spec compare feature, you must add the `NSPhotoLibraryUsageDescription`
key and a value to your info.plist.
- Attention: This object uses Apple Private APIs and should not be used in a production application environment.
It is the responsibility of the implementing developer to ensure this code is not used in production.
*/
struct DebugOverlay {
private static var overlayClass: UIWindow.Type?
/**
Prepares the debug information overlay for presentation.
*/
static func prepareForPresentation() {
let overlayClass = NSClassFromString("UIDebuggingInformationOverlay") as? UIWindow.Type
_ = overlayClass?.perform(NSSelectorFromString("prepareDebuggingOverlay"))
DebugOverlay.overlayClass = overlayClass
}
/**
Toggles the visibility of the debug information overlay
*/
static func toggleVisibility() {
let overlay = overlayClass?.perform(NSSelectorFromString("overlay")).takeUnretainedValue() as? UIWindow
_ = overlay?.perform(NSSelectorFromString("toggleVisibility"))
}
}
| mit | f19c3b713c3b83bc4383ec235e828354 | 35.425532 | 113 | 0.74007 | 4.91954 | false | false | false | false |
tavultesoft/keymanweb | ios/engine/KMEI/KeymanEngine/Classes/HTTPDownloader.swift | 1 | 5309 | //
// HTTPDownloader.swift
// KeymanEngine
//
// Created by Gabriel Wong on 2017-09-15.
// Copyright © 2017 SIL International. All rights reserved.
//
import Foundation
protocol HTTPDownloadDelegate: class {
func downloadRequestStarted(_ request: HTTPDownloadRequest)
func downloadRequestFinished(_ request: HTTPDownloadRequest)
func downloadRequestFailed(_ request: HTTPDownloadRequest, with: Error?)
func downloadQueueFinished(_ queue: HTTPDownloader)
func downloadQueueCancelled(_ queue: HTTPDownloader)
}
class HTTPDownloader: NSObject {
var queue: [HTTPDownloadRequest] = []
// TODO: Make unowned
/*weak*/ var handler: HTTPDownloadDelegate? // 'weak' interferes with installs
// from the app's browser.
var currentRequest: HTTPDownloadRequest?
var downloadSession: URLSession!
public var userInfo: [String: Any] = [:]
var isCancelled: Bool = false
init(_ handler: HTTPDownloadDelegate?, session: URLSession = .shared) {
super.init()
self.handler = handler
downloadSession = session
}
func addRequest(_ request: HTTPDownloadRequest) {
isCancelled = false
queue.append(request)
}
func popRequest() -> HTTPDownloadRequest? {
if queue.isEmpty {
return nil
}
return queue.remove(at: 0)
}
// Starts the queue. The queue is managed via event messages in order to process them sequentially.
func run() {
isCancelled = false
if !queue.isEmpty {
runRequest()
}
}
// Runs the next step in the queue, if appropriate.
func runRequest() {
// Perhaps more of an 'if', relying on 'completed' messages to continue the loop?
if !queue.isEmpty {
let req: HTTPDownloadRequest! = popRequest()
currentRequest = req
if req.typeCode == .downloadFile {
req.task = downloadSession.downloadTask(with: req.url, completionHandler: self.downloadCompletionHandler)
handler?.downloadRequestStarted(req)
}
req?.task?.resume()
} else if !isCancelled {
handler?.downloadQueueFinished(self)
}
// The next step in the queue, should it exist, will be triggered by urlSession(_, task:, didCompleteWithError:)
// which calls this method. Thus, this method may serve as the single source of the 'queue finished' message.
}
func downloadCompletionHandler(location: URL?, response: URLResponse?, error: Error?) -> Void {
guard let currentRequest = currentRequest else {
return
}
// If it's an error case
guard let location = location else {
// If location is `nil`, we have an error.
// See docs at https://developer.apple.com/documentation/foundation/urlsession/1411511-downloadtask
//
// Force the callback onto the main thread.
DispatchQueue.main.async {
self.handler?.downloadRequestFailed(currentRequest, with: nil)
self.runRequest()
}
return
}
guard error == nil else {
// The download process itself encountered an error.
DispatchQueue.main.async {
self.handler?.downloadRequestFailed(currentRequest, with: error)
self.runRequest()
}
return
}
// Successful download.
log.debug("Downloaded file \(currentRequest.url) as \(location), " +
"to be copied to \(currentRequest.destinationFile ?? "nil")")
// If a destination file for the download has already been specified, let's go ahead and copy it over.
if let destFile = currentRequest.destinationFile {
let destFileUrl = URL(fileURLWithPath: destFile)
do {
// Need to delete the file if it already exists (e.g. in case of a previous partial download)
if(FileManager.default.fileExists(atPath: destFileUrl.path)) {
try FileManager.default.removeItem(at: destFileUrl)
}
try FileManager.default.copyItem(at: location,
to: destFileUrl)
} catch {
log.error("Error saving the download: \(error)")
}
}
DispatchQueue.main.async {
self.handler?.downloadRequestFinished(currentRequest)
self.runRequest()
}
}
func dataCompletionHandler(data: Data?, response: URLResponse?, error: Error?) -> Void {
guard let currentRequest = currentRequest else {
return
}
guard let data = data else {
DispatchQueue.main.async {
self.handler?.downloadRequestFailed(currentRequest, with: nil)
self.runRequest()
}
return
}
// We only evaluate one at a time, so the 'current request' holds the data task's original request data.
currentRequest.rawResponseData = data
// With current internal settings, this will cache the data as we desire.
DispatchQueue.main.async {
self.handler?.downloadRequestFinished(currentRequest)
self.runRequest()
}
}
func cancelAllOperations() {
while !queue.isEmpty {
_ = popRequest()
}
// Done second so that there is no 'next quest' that could possibly trigger. (This is probably overcautious.)
if let currentRequest = currentRequest {
currentRequest.task?.cancel()
}
self.handler?.downloadQueueCancelled(self)
self.isCancelled = true
}
var requestsCount: Int {
return queue.count
}
}
| apache-2.0 | a30bc1e5c52f8c14a18edfdffd9239c5 | 30.784431 | 116 | 0.666918 | 4.684907 | false | false | false | false |
stevehe-campray/BSBDJ | BSBDJ/BSBDJ/Essence(精华)/Model/BSBTagInfo.swift | 1 | 957 | //
// BSBTagInfo.swift
// BSBDJ
//
// Created by hejingjin on 16/3/18.
// Copyright © 2016年 baisibudejie. All rights reserved.
//
import UIKit
class BSBTagInfo: NSObject {
/** 主题图片 */
var image_list : String = ""
var is_default : NSInteger = 0
var is_sub : NSInteger = 0
/** 主题名 */
var theme_name : String = ""
var theme_id : String = ""
/** 订阅数 */
var sub_number : String = ""
//字典数组转模型数组
class func dict2Model(list: [[String: AnyObject]]) -> [BSBTagInfo] {
var models = [BSBTagInfo]()
for dict in list
{
models.append(BSBTagInfo(dict: dict))
}
return models
}
// 字典转模型
init(dict: [String: AnyObject])
{
super.init()
setValuesForKeysWithDictionary(dict)
}
override func setValue(value: AnyObject?, forUndefinedKey key: String) {
}
}
| mit | 9c255c16e38c1a5190c59ba41d443d84 | 20.571429 | 76 | 0.554084 | 3.775 | false | false | false | false |
JaSpa/LazyJSON | LazyJSONTests/LazyJSONTests.swift | 1 | 1183 | //
// LazyJSONTests.swift
// LazyJSONTests
//
// Created by Janek Spaderna on 16.12.15.
// Copyright © 2015 jds. All rights reserved.
//
import XCTest
import LazyJSON
enum NilError: ErrorType {
case Unexpected(String)
}
class LazyJSONTests: XCTestCase {
func testPerformance() {
do {
guard let data =
NSBundle(forClass: LazyJSONTests.self)
.URLForResource("big_data", withExtension: "json")
.flatMap(NSData.init) else {
throw NilError.Unexpected("can't load the json file")
}
let json = try NSJSONSerialization.JSONObjectWithData(data, options: [])
var firstElem: [TestModel]? = nil
measureBlock {
do {
let parsed: [TestModel] = try decode(json, root: "types")
if firstElem == nil { firstElem = parsed }
} catch {
XCTFail("unexpected error: \(error)")
}
}
print(firstElem?.count ?? 0, "elements parsed")
} catch {
XCTFail("unexpected error: \(error)")
}
}
}
| mit | 5d14f455b1234032905e48edd434a6c2 | 25.266667 | 84 | 0.523689 | 4.690476 | false | true | false | false |
alexth/CDVDictionary | Dictionary/DictionaryTests/Utils/UIColor+AttributedTests.swift | 1 | 1498 | //
// UIColor+Attributed.swift
// Dictionary
//
// Created by Alex Golub on 9/27/16.
// Copyright © 2016 Alex Golub. All rights reserved.
//
import XCTest
@testable import Dictionary
class ColorUtilsTests: XCTestCase {
func testAttributedColor() {
guard let testColor = UIColor(named: "attributed") else {
XCTAssert(true, "unable to obtain attributed color")
return
}
let attributedColor = UIColor.attributed
XCTAssertEqual(testColor, attributedColor, "colors should be equal")
}
func testBaseColor() {
guard let testColor = UIColor(named: "base") else {
XCTAssert(true, "unable to obtain base color")
return
}
let baseColor = UIColor.base
XCTAssertEqual(testColor, baseColor, "colors should be equal")
}
func testBaseCellColor() {
guard let testColor = UIColor(named: "baseCell") else {
XCTAssert(true, "unable to obtain baseCell color")
return
}
let baseCellColor = UIColor.baseCell
XCTAssertEqual(testColor, baseCellColor, "colors should be equal")
}
func testBlackCustomColor() {
guard let testColor = UIColor(named: "blackCustom") else {
XCTAssert(true, "unable to obtain blackCustom color")
return
}
let blackCustomColor = UIColor.blackCustom
XCTAssertEqual(testColor, blackCustomColor, "colors should be equal")
}
}
| mit | f9ea93b3b255bab5ab4da0fca15fd570 | 25.263158 | 77 | 0.630595 | 4.813505 | false | true | false | false |
khizkhiz/swift | benchmark/single-source/StrToInt.swift | 2 | 1940 | //===--- StrToInt.swift ---------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// This test checks performance of String to Int conversion.
// It is reported to be very slow: <rdar://problem/17255477>
import TestsUtils
@inline(never)
public func run_StrToInt(N: Int) {
// 64 numbers from -500_000 to 500_000 generated randomly
let input = ["-237392", "293715", "126809", "333779", "-362824", "144198",
"-394973", "-163669", "-7236", "376965", "-400783", "-118670",
"454728", "-38915", "136285", "-448481", "-499684", "68298",
"382671", "105432", "-38385", "39422", "-267849", "-439886",
"292690", "87017", "404692", "27692", "486408", "336482",
"-67850", "56414", "-340902", "-391782", "414778", "-494338",
"-413017", "-377452", "-300681", "170194", "428941", "-291665",
"89331", "329496", "-364449", "272843", "-10688", "142542",
"-417439", "167337", "96598", "-264104", "-186029", "98480",
"-316727", "483808", "300149", "-405877", "-98938", "283685",
"-247856", "-46975", "346060", "160085",]
let ref_result = 517492
func DoOneIter(arr: [String]) -> Int {
var r = 0
for n in arr {
r += Int(n)!
}
if r < 0 {
r = -r
}
return r
}
var res = Int.max
for _ in 1...1000*N {
res = res & DoOneIter(input)
}
CheckResults(res == ref_result, "IncorrectResults in StrToInt: \(res) != \(ref_result)")
}
| apache-2.0 | 9bdeeca33e209b0f74cba0def6a4cd25 | 40.276596 | 90 | 0.525773 | 3.433628 | false | false | false | false |
dsoisson/SwiftLearningExercises | SwiftLearning.playground/Pages/Collection Types.xcplaygroundpage/Contents.swift | 1 | 15568 | /*:
[Table of Contents](Table%20of%20Contents) | [Previous](@previous) | [Next](@next)
*/
/*:
# Collection Types
*/
/*:
**Session Overview:**
Often times in programs you need to group data into a single container where the number of items is unknown. Swift provides 3 main containers known as *collection types* for storing collections of values. *Arrays* are ordered collections of values, *Sets* are unordered collections of unique values, and *Dictionaries* are unordered collections of key-value associations. Please visit the Swift Programming Language Guide section on [Collection Types](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html#//apple_ref/doc/uid/TP40014097-CH8-ID105) for more detail on collection types.
*/
import Foundation
/*:
## When you're allowed to change or *mutate* collections
Before we dive into detail on collection types, there's a suttle but easy way to indicate if you can mutate your collection type. We have already seen this with simple data types such as `Int` and `String`, you use `let` and `var`.
*/
let unmutableArray: [String] = ["One", "Two"]
//unmutableArray.append("Three")
var mutableArray: [Int] = [1, 2]
mutableArray.append(3)
//: > **Experiment**: Uncomment the unmutableArray.append statement
/*:
## Arrays
An *Array* stores values of the same type, `Int`s, `String`s, ect. in ordered manner. The same value of the type can appear multiple times at different positions of the array.
*/
/*:
### Creating Arrays
Swift's *arrays* need to know what type of elements it will contain. You can create an empty array, create an array with a default size and values for each element, create an array by adding multiple arrays together and create arrays using literals.
*/
/*:
**A new empty Array**
> You can create an array explicitly with the type or when appropriate use type inference.
*/
var array: [Int] = [Int]()
array = []
print("array has \(array.count) items.")
//: The above statements show two ways to create a new array, allowing only to store `Int`s and print the number of elements.
/*:
**A new Array with default values**
>You can create an array with default values by using the *initializer* that accepts a default value and a repeat count of how many elements the array should contain
*/
let nineNines = [Int](count: 9, repeatedValue: 9)
print("nineNines has \(nineNines.count) items.")
//: The above statements creates an array nine `Int`s all with a value of 9 and print the number of elements nineNines contains.
/*:
**A new Array by adding Arrays together**
>You can create an array by taking two *arrays* of the same type and adding them together usng the addition operator `+`. The new array's type is inferred from the type of the two arrays added together.
*/
let twoTwos = [Int](count: 2, repeatedValue: 2)
let threeThrees = [Int](count: 3, repeatedValue: 3)
let twosAndThrees = twoTwos + threeThrees
print("twosAndThrees has \(twosAndThrees.count) items.")
let threesAndTwos = threeThrees + twoTwos
print("threesAndTwos has \(threesAndTwos.count) items.")
//: The above statements creates two arrays by adding two other arrays together.
/*:
**A new Array using Array literal**
>You can create an array by using the literal syntax such as creating an array of `Ints` like `[1, 2, 3, 4, 5]`.
*/
let numbers = [1, 2, 3, 4, 5];
//: The above statement creates an array of numbers containing `Int` data types.
/*:
### Accessing data in an `Array`
You can access information and elements in an array by using the methods and properties provided by the `Array` collection type.
*/
print("numbers has \(numbers.count) elements")
if numbers.isEmpty {
print("numbers is empty")
} else {
print("numbers is not empty")
}
var firstNumber = numbers.first
var lastNumber = numbers.last
//: The above statements use properties of the `Array` collection type for count, empty, first element, and last element.
var secondNumber = numbers[1]
var thirdNumber = numbers[2]
//: The above statements use *subscript syntax* by passing the index of the value you want in square brackets after the name of the array.
/*:
### Modifying `Array`s
Using methods such as `append` and `remove` let you mutate an array.
*/
var mutableNumbers = numbers
mutableNumbers.append(6)
mutableNumbers.append(7)
mutableNumbers.append(8)
mutableNumbers.removeFirst()
mutableNumbers.removeLast()
mutableNumbers.removeAtIndex(0)
mutableNumbers.removeRange(mutableNumbers.startIndex.advancedBy(2)..<mutableNumbers.endIndex)
mutableNumbers[0] = 1
mutableNumbers[1] = 2
mutableNumbers.append(3)
mutableNumbers.append(4)
mutableNumbers.append(5)
mutableNumbers[0...4] = [5, 6, 7, 8, 9]
mutableNumbers.insert(10, atIndex: mutableNumbers.endIndex)
print(mutableNumbers)
//: The above statements using the `append`, `insert`, `remove` methods, *subscript syntax* as well as using a range to replace values of indexes.
/*:
### Iterating over elements in an `Array`
You use the `for-in` loop to iterate over elements in an `Array`
*/
for number in numbers {
print(number)
}
for (index, number) in numbers.enumerate() {
print("Item \(index + 1): \(number)")
}
//: The first `for-in` loop just pulls out the value for each element in the array, but the second `for-in` loops pulls out the index and value.
//: > **Experiment**: Use an `_` underscore instead of `name` in the above for loop. What happens?
/*:
## Sets
The `Set` collection type stores unique value of the same data type with no defined ordering. You use a `Set` instead of an `Array` when you need to ensure that an element only appears once.
*/
/*:
### Hash Values for Set Types
For a `Set` to ensure that it contains only unique values, each element must provide a value called the *hash value*. A *hash value* is an `Int` that is calulated and is the same for all objects that compare equally. Simple types such as `Int`s, `Double`s, `String`s, and `Bool`s all provide a *hash value* by default.
*/
let one = 1
let two = "two"
let three = M_PI
let four = false
one.hashValue
two.hashValue
three.hashValue
four.hashValue
/*:
### Creating Sets
You create a new set collection type by specifing the data type for the element as in `Set<Element>` where `Element` is the data type the set is allowed to store.
*/
var alphabet = Set<Character>()
alphabet = []
/*:
The above statements create an empty set that is only allowed to store the Character data type. The second statment assigns *alphabet* to an empty array using the array literal and type inference.
*/
//: **A new Set using Array literal**
var alphabet1: Set<Character> = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
var alphabet2: Set = ["j", "k", "l", "m", "n", "o", "p", "q", "r"]
//: You can create a new `Set` using the array literal, but you need to type the variable or constant. `alphabet2` is a shorter way to create a `Set` because it can be inferred that all the values are of the same type, in this case `String`s. Notice that `alphabet1` and `alphabet2` are not of the same type.
/*:
### Accessing data in a `Set`
Similar to the `Array` collection type, you access information and elements in an `Set` using properties and methods of the `Set` collection type.
*/
alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"]
print("alphabet has \(alphabet.count) elements")
if alphabet.isEmpty {
print("alphabet is empty")
} else {
print("alphabet is not empty")
}
var firstLetter = alphabet.first
//: The above statements use properties of the `Set` collection type for count, empty, and first element.
var secondLetter = alphabet[alphabet.startIndex.advancedBy(1)]
var thirdLetter = alphabet[alphabet.startIndex.advancedBy(2)]
//: The above statements use *subscript syntax* by passing the index of the value you want in square brackets after the name of the set.
/*:
### Modifying elements in a Set
Using methods such as `insert` and `remove` let you mutate a set.
*/
alphabet.insert("n")
alphabet.insert("o")
alphabet.insert("p")
alphabet.removeFirst()
alphabet.removeAtIndex(alphabet.startIndex)
alphabet.remove("o")
print(alphabet)
//: The above statements using the `insert` and `remove` methods to mutate the `Set`.
/*:
### Iterating over elements in a Set
You use the `for-in` loop to iterate over elements in an `Set`
*/
for letter in alphabet {
print(letter)
}
for letter in alphabet.sort() {
print(letter)
}
//: The first `for-in` loop just pulls out the value for each element in the set, but the second `for-in` first sorts the set before the looping starts.
/*:
### Set Operations
With the `Set` collection type, you can perform set operations in the mathematical sense.
*/
alphabet = ["a", "b", "c", "d", "e", "v", "w", "x", "y", "z"]
let vowels : Set<Character> = ["a", "e", "i", "o", "u"]
//: **intersect(_:)** creates a new `Set` of only those values both sets have in common.
let intersect = vowels.intersect(alphabet)
//: **exclusiveOr(_:)** creates a new `Set` of values from either set, but not from both.
let exclusiveOr = vowels.exclusiveOr(alphabet)
//: **union(_:)** creates a new `Set` with all values from both sets.
let union = vowels.union(alphabet)
//: **subtract(_:)** creates a new `Set` with values not in the specified set.
let subtract = vowels.subtract(alphabet)
/*:
### Set Membership and Equality
With the `Set` collection type, you can determine the membership of a set and if one set is equal to another.
*/
let family : Set = ["Matt", "Annie", "Samuel", "Jack", "Hudson", "Oliver"]
let parents : Set = ["Matt", "Annie"]
let children : Set = ["Samuel", "Jack", "Hudson", "Oliver"]
//: **“is equal” operator (==)** tests if one set is equal to another set.
family == parents.union(children)
parents == children
//: **isSubsetOf(_:)** tests if all of the values of a set are contained in another set.
children.isSubsetOf(family)
family.isSubsetOf(children)
//: **isSupersetOf(_:)** test if a set contains all of the values in another set.
family.isSupersetOf(parents)
family.isSupersetOf(children)
children.isSupersetOf(family)
//: **isStrictSubsetOf(_:) or isStrictSupersetOf(_:)** test if a set is a subset or superset, but not equal to, another set.
let old = parents
old.isStrictSubsetOf(parents)
let boys: Set = ["Matt", "Samuel", "Jack", "Hudson", "Oliver"]
boys.isStrictSubsetOf(family)
//: **isDisjointWith(_:)** test if two sets have any values in common.
parents.isDisjointWith(children)
family.isDisjointWith(children)
/*:
## Dictionaries
A `Dictionary` stores associations or mappings between keys of the same data type and values of the same data type in a container with no defined ordering. The value of each element is tied to a unique *key*. It's this unique *key* that enables you to lookup values based on an identifer, just like a real dictionary having the word be the key and the definition the value.
*/
/*:
### Creating Dictionaries
Much like the `Array` and `Set` collection types, you need to specify the data type that the `Dictionary` is allowed to store. Unlike `Array`s and `Set`s, you need to specify the data type for the *Key* and the *Value*.
*/
var longhand: Dictionary<String, String>? = nil;
var shorthand: [String: String]? = nil;
/*:
Above shows a long and short way to create a dictionary.
*/
//: **A new empty Dictionary**
var titles = [String: String]()
titles["dad"] = "Matt"
titles = [:]
/*:
Above creates an empty `Dictionary`, adds an entry into `titles` and then assigns `titles` to an empty dictionary using the shorthand form and type inference.
*/
//: **A new Dictionary using Dictionary literal**
titles = ["dad": "Matt", "mom": "Annie", "child_1": "Sam", "child_2": "Jack", "child_3": "Hudson", "child_4": "Oliver"]
/*:
Above creates a `Dictionary` using the literal syntax. Notice the *key: value* mapping separated by a comma, all surrounded by square brackets.
*/
/*:
### Accessing data in a Dictionary
Like the `Array` and `Set` collection types, the `Dictionary` also has the `count` and `isEmpty` properties, but unlike arrays and sets, you access elements using a *key*.
*/
print("titles has \(titles.count) elements")
if titles.isEmpty {
print("titles is empty")
} else {
print("titles is not empty")
}
var dad = titles["dad"]
if dad != nil {
print(dad!)
}
/*:
Above statements use the `count` and `isEmpty` properties, as well as use the *key* to retrive a value. It's possible that you use a *key* that does not exist in the dictionary. The `Dictionary` collection type will always return the value as an *Optional*. You then next would need to check for `nil` and *unwrap* the optional to obtain the real value.
*/
/*:
### Modifying elements in a Dictionary
There are two techniques to add/update entries for the `Dictionary` collection type, by using the *subscript syntax* or using a method.
*/
titles["dog"] = "Carson"
titles["child_1"] = "Samuel"
var father = titles.updateValue("Mathew", forKey: "dad")
var cat = titles.updateValue("Fluffy", forKey: "cat")
titles["dog"] = nil
cat = titles.removeValueForKey("cat")
if cat != nil {
print("removed \(cat!)")
}
/*:
The above statements use both the *subscript syntax* and methods for add, updating, and removing entries of a dictionary. Notice that with the method technique, you are returned a value if if the entry exists in the dictionary.
*/
/*:
### Iterating over elements in a Dictionary
Just like the `Array` and `Set` collection types, you iterate over a dictionary using a `for-in` loop.
*/
for (title, name) in titles {
print("\(title): \(name)")
}
for title in titles.keys {
print("title: \(title)")
}
for name in titles.values {
print("name: \(name)")
}
let titleNames = [String](titles.keys)
let names = [String](titles.values)
/*:
Above statements use the `for-in` loop to iterate over the `titles` giving you access to the *key* and *value*. You can also access only the *keys* or *values*.
*/
//: > **Experiment**: Create a array of dictionaries and iterate over the array printing the key and value of each dictionary
/*:
**Exercise:** You have to record all the students and their grades for your school. Leveraging arrays, dictionaries, and sets create table like containers for each class. Your classes are Math, Science, English and History with a total of 17 unique students. Print out each class roster and use and experiment with set operations and set membership and equality.
>> **Example Output:**
* `Math = Mathew Sheets, John Winters, Sam Smith`
* `Science = Sam Smith, Carson Daily, Adam Aarons`
* `Union of Math and Science = Mathew Sheets, John Winters, Sam Smith, Carson Daily, Adam Aarons`
>> **Constraints:**
* Use Set Operations
* intersect
* exclusiveOr
* union
* subtract
* Use Set Membership and Equality
* is equal
* isSubsetOf
* isSupersetOf
* isStrictSubsetOf
* isStrictSupersetOf
* isDisjointWith
*/
/*:
**Checkpoint:**
At this point, you should have a basic understanding of the collection types provided by the Swift programming language. Using arrays, you can store a collection of ordered values. Using sets, you can store a collection of unordered unique values. Using dictionaries, you can store a collection of key-value associations. With these three collection types, processing and manipulating data will be easier.
*/
/*:
**Supporting Chapters:**
- [Collection Types](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html)
*/
/*:
[Table of Contents](Table%20of%20Contents) | [Previous](@previous) | [Next](@next)
*/
| mit | 1cc8c74bd7b6fdb91ccd844c09a2ee99 | 43.215909 | 660 | 0.723914 | 3.89392 | false | false | false | false |
robrix/Surge | Source/Exponential.swift | 1 | 2012 | // Exponential.swift
//
// Copyright (c) 2014 Mattt Thompson (http://mattt.me)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
public func exp(x: [Double], y: [Double]) -> [Double] {
var results = [Double](x)
vvexp(&results, y, [Int32(x.count)])
return results
}
public func exp2(x: [Double], y: [Double]) -> [Double] {
var results = [Double](x)
vvexp2(&results, y, [Int32(x.count)])
return results
}
public func log(x: [Double]) -> [Double] {
var results = [Double](x)
vvlog(&results, x, [Int32(x.count)])
return results
}
public func log2(x: [Double]) -> [Double] {
var results = [Double](x)
vvlog2(&results, x, [Int32(x.count)])
return results
}
public func log10(x: [Double]) -> [Double] {
var results = [Double](x)
vvlog10(&results, x, [Int32(x.count)])
return results
}
public func logb(x: [Double]) -> [Double] {
var results = [Double](x)
vvlogb(&results, x, [Int32(x.count)])
return results
}
| mit | db0882240682ee5b6346fe4b4a8dc0fe | 30.936508 | 80 | 0.687873 | 3.732839 | false | false | false | false |
br1sk/brisk-ios | Brisk iOS/Model/Dictionary+Validation.swift | 1 | 514 | public extension Dictionary where Key == String {
public func onlyStrings() -> [String: String] {
var newDictionary = [String: String]()
for (key, value) in self {
newDictionary[key] = value as? String
}
return newDictionary
}
}
public extension Dictionary where Key == String, Value == String {
public func filterEmpty() -> [String: String] {
var newDictionary = [String: String]()
for (key, value) in self where !value.isEmpty {
newDictionary[key] = value
}
return newDictionary
}
}
| mit | 5f7e8a45718ea58bbf87f00d26f4e59e | 23.47619 | 66 | 0.680934 | 3.64539 | false | false | false | false |
xwu/swift | test/Constraints/protocols.swift | 1 | 15475 | // RUN: %target-typecheck-verify-swift
protocol Fooable { func foo() }
protocol Barable { func bar() }
extension Int : Fooable, Barable {
func foo() {}
func bar() {}
}
extension Float32 : Barable {
func bar() {}
}
func f0(_: Barable) {}
func f1(_ x: Fooable & Barable) {}
func f2(_: Float) {}
let nilFunc: Optional<(Barable) -> ()> = nil
func g(_: (Barable & Fooable) -> ()) {}
protocol Classable : AnyObject {}
class SomeArbitraryClass {}
func fc0(_: Classable) {}
func fc1(_: Fooable & Classable) {}
func fc2(_: AnyObject) {}
func fc3(_: SomeArbitraryClass) {}
func gc(_: (Classable & Fooable) -> ()) {}
var i : Int
var f : Float
var b : Barable
//===----------------------------------------------------------------------===//
// Conversion to and among existential types
//===----------------------------------------------------------------------===//
f0(i)
f0(f)
f0(b)
f1(i)
f1(f) // expected-error{{argument type 'Float' does not conform to expected type 'Fooable'}}
f1(b) // expected-error{{argument type 'Barable' does not conform to expected type 'Fooable'}}
//===----------------------------------------------------------------------===//
// Subtyping
//===----------------------------------------------------------------------===//
g(f0) // okay (subtype)
g(f1) // okay (exact match)
g(f2) // expected-error{{cannot convert value of type '(Float) -> ()' to expected argument type '(Barable & Fooable) -> ()'}}
g(nilFunc ?? f0)
gc(fc0) // okay
gc(fc1) // okay
gc(fc2) // okay
gc(fc3) // expected-error{{cannot convert value of type '(SomeArbitraryClass) -> ()' to expected argument type '(Classable & Fooable) -> ()'}}
// rdar://problem/19600325
func getAnyObject() -> AnyObject? {
return SomeArbitraryClass()
}
func castToClass(_ object: Any) -> SomeArbitraryClass? {
return object as? SomeArbitraryClass
}
_ = getAnyObject().map(castToClass)
_ = { (_: Any) -> Void in
return
} as ((Int) -> Void)
let _: (Int) -> Void = {
(_: Any) -> Void in
return
}
let _: () -> Any = {
() -> Int in
return 0
}
let _: () -> Int = {
() -> String in // expected-error {{declared closure result 'String' is incompatible with contextual type 'Int'}}
return ""
}
//===----------------------------------------------------------------------===//
// Members of archetypes
//===----------------------------------------------------------------------===//
func id<T>(_ t: T) -> T { return t }
protocol Initable {
init()
}
protocol P : Initable {
func bar(_ x: Int)
mutating func mut(_ x: Int)
static func tum()
typealias E = Int
typealias F = Self.E
typealias G = Array
}
protocol ClassP : class {
func bas(_ x: Int)
func quux(_ x: Int)
}
class ClassC : ClassP {
func bas(_ x: Int) {}
}
extension ClassP {
func quux(_ x: Int) {}
func bing(_ x: Int) {}
}
func generic<T: P>(_ t: T) {
var t = t
// Instance member of archetype
let _: (Int) -> () = id(t.bar)
let _: () = id(t.bar(0))
// Static member of archetype metatype
let _: () -> () = id(T.tum)
// Instance member of archetype metatype
let _: (T) -> (Int) -> () = id(T.bar)
let _: (Int) -> () = id(T.bar(t))
_ = t.mut // expected-error{{cannot reference 'mutating' method as function value}}
_ = t.tum // expected-error{{static member 'tum' cannot be used on instance of type 'T'}}
}
func genericClassP<T: ClassP>(_ t: T) {
// Instance member of archetype)
let _: (Int) -> () = id(t.bas)
let _: () = id(t.bas(0))
// Instance member of archetype metatype)
let _: (T) -> (Int) -> () = id(T.bas)
let _: (Int) -> () = id(T.bas(t))
let _: () = id(T.bas(t)(1))
}
func genericClassC<C : ClassC>(_ c: C) {
// Make sure that we can find members of protocol extensions
// on a class-bound archetype
let _ = c.bas(123)
let _ = c.quux(123)
let _ = c.bing(123)
}
//===----------------------------------------------------------------------===//
// Members of existentials
//===----------------------------------------------------------------------===//
func existential(_ p: P) {
var p = p
// Fully applied mutating method
p.mut(1)
_ = p.mut // expected-error{{cannot reference 'mutating' method as function value}}
// Instance member of existential)
let _: (Int) -> () = id(p.bar)
let _: () = id(p.bar(0))
// Static member of existential metatype)
let _: () -> () = id(type(of: p).tum)
}
func staticExistential(_ p: P.Type, pp: P.Protocol) {
let _ = p() // expected-error{{initializing from a metatype value must reference 'init' explicitly}}
let _ = p().bar // expected-error{{initializing from a metatype value must reference 'init' explicitly}}
let _ = p().bar(1) // expected-error{{initializing from a metatype value must reference 'init' explicitly}}
let ppp: P = p.init()
_ = pp() // expected-error{{value of type 'P.Protocol' is a protocol; it cannot be instantiated}}
_ = pp().bar // expected-error{{value of type 'P.Protocol' is a protocol; it cannot be instantiated}}
_ = pp().bar(2) // expected-error{{value of type 'P.Protocol' is a protocol; it cannot be instantiated}}
_ = pp.init() // expected-error{{protocol type 'P' cannot be instantiated}}
_ = pp.init().bar // expected-error{{protocol type 'P' cannot be instantiated}}
_ = pp.init().bar(3) // expected-error{{protocol type 'P' cannot be instantiated}}
_ = P() // expected-error{{protocol type 'P' cannot be instantiated}}
_ = P().bar // expected-error{{protocol type 'P' cannot be instantiated}}
_ = P().bar(4) // expected-error{{protocol type 'P' cannot be instantiated}}
// Instance member of metatype
let _: (P) -> (Int) -> () = P.bar
let _: (Int) -> () = P.bar(ppp)
P.bar(ppp)(5)
// Instance member of metatype value
let _: (P) -> (Int) -> () = pp.bar
let _: (Int) -> () = pp.bar(ppp)
pp.bar(ppp)(5)
// Static member of existential metatype value
let _: () -> () = p.tum
// Instance member of existential metatype -- not allowed
_ = p.bar // expected-error{{instance member 'bar' cannot be used on type 'P'}}
_ = p.mut // expected-error{{instance member 'mut' cannot be used on type 'P'}}
// expected-error@-1 {{cannot reference 'mutating' method as function value}}
// Static member of metatype -- not allowed
_ = pp.tum // expected-error{{static member 'tum' cannot be used on protocol metatype 'P.Protocol'}}
_ = P.tum // expected-error{{static member 'tum' cannot be used on protocol metatype 'P.Protocol'}}
// Access typealias through protocol and existential metatypes
_ = pp.E.self
_ = p.E.self
_ = pp.F.self
_ = p.F.self
// Make sure that we open generics
let _: [Int].Type = p.G.self
}
protocol StaticP {
static func foo(a: Int)
}
extension StaticP {
func bar() {
_ = StaticP.foo(a:) // expected-error{{static member 'foo(a:)' cannot be used on protocol metatype 'StaticP.Protocol'}} {{9-16=Self}}
func nested() {
_ = StaticP.foo(a:) // expected-error{{static member 'foo(a:)' cannot be used on protocol metatype 'StaticP.Protocol'}} {{11-18=Self}}
}
}
}
func existentialClassP(_ p: ClassP) {
// Instance member of existential)
let _: (Int) -> () = id(p.bas)
let _: () = id(p.bas(0))
// Instance member of existential metatype)
let _: (ClassP) -> (Int) -> () = id(ClassP.bas)
let _: (Int) -> () = id(ClassP.bas(p))
let _: () = id(ClassP.bas(p)(1))
}
// Partial application of curried protocol methods
protocol Scalar {}
protocol Vector {
func scale(_ c: Scalar) -> Self
}
protocol Functional {
func apply(_ v: Vector) -> Scalar
}
protocol Coalgebra {
func coproduct(_ f: Functional) -> (_ v1: Vector, _ v2: Vector) -> Scalar
}
// Make sure existential is closed early when we partially apply
func wrap<T>(_ t: T) -> T {
return t
}
func exercise(_ c: Coalgebra, f: Functional, v: Vector) {
let _: (Vector, Vector) -> Scalar = wrap(c.coproduct(f))
let _: (Scalar) -> Vector = v.scale
}
// Make sure existential isn't closed too late
protocol Copyable {
func copy() -> Self
}
func copyTwice(_ c: Copyable) -> Copyable {
return c.copy().copy()
}
//===----------------------------------------------------------------------===//
// Dynamic self
//===----------------------------------------------------------------------===//
protocol Clonable {
func maybeClone() -> Self?
func doubleMaybeClone() -> Self??
func subdivideClone() -> (Self, Self)
func metatypeOfClone() -> Self.Type
func goodClonerFn() -> (() -> Self)
}
extension Clonable {
func badClonerFn() -> ((Self) -> Self) { }
func veryBadClonerFn() -> ((inout Self) -> ()) { }
func extClone() -> Self { }
func extMaybeClone(_ b: Bool) -> Self? { }
func extProbablyClone(_ b: Bool) -> Self! { }
static func returnSelfStatic() -> Self { }
static func returnSelfOptionalStatic(_ b: Bool) -> Self? { }
static func returnSelfIUOStatic(_ b: Bool) -> Self! { }
}
func testClonableArchetype<T : Clonable>(_ t: T) {
// Instance member of extension returning Self)
let _: (T) -> () -> T = id(T.extClone)
let _: () -> T = id(T.extClone(t))
let _: T = id(T.extClone(t)())
let _: () -> T = id(t.extClone)
let _: T = id(t.extClone())
let _: (T) -> (Bool) -> T? = id(T.extMaybeClone)
let _: (Bool) -> T? = id(T.extMaybeClone(t))
let _: T? = id(T.extMaybeClone(t)(false))
let _: (Bool) -> T? = id(t.extMaybeClone)
let _: T? = id(t.extMaybeClone(true))
let _: (T) -> (Bool) -> T? = id(T.extProbablyClone as (T) -> (Bool) -> T?)
let _: (Bool) -> T? = id(T.extProbablyClone(t) as (Bool) -> T?)
let _: T! = id(T.extProbablyClone(t)(true))
let _: (Bool) -> T? = id(t.extProbablyClone as (Bool) -> T?)
let _: T! = id(t.extProbablyClone(true))
// Static member of extension returning Self)
let _: () -> T = id(T.returnSelfStatic)
let _: T = id(T.returnSelfStatic())
let _: (Bool) -> T? = id(T.returnSelfOptionalStatic)
let _: T? = id(T.returnSelfOptionalStatic(false))
let _: (Bool) -> T? = id(T.returnSelfIUOStatic as (Bool) -> T?)
let _: T! = id(T.returnSelfIUOStatic(true))
}
func testClonableExistential(_ v: Clonable, _ vv: Clonable.Type) {
let _: Clonable? = v.maybeClone()
let _: Clonable?? = v.doubleMaybeClone()
let _: (Clonable, Clonable) = v.subdivideClone()
let _: Clonable.Type = v.metatypeOfClone()
let _: () -> Clonable = v.goodClonerFn()
// Instance member of extension returning Self
let _: () -> Clonable = id(v.extClone)
let _: Clonable = id(v.extClone())
let _: Clonable? = id(v.extMaybeClone(true))
let _: Clonable! = id(v.extProbablyClone(true))
// Static member of extension returning Self)
let _: () -> Clonable = id(vv.returnSelfStatic)
let _: Clonable = id(vv.returnSelfStatic())
let _: (Bool) -> Clonable? = id(vv.returnSelfOptionalStatic)
let _: Clonable? = id(vv.returnSelfOptionalStatic(false))
let _: (Bool) -> Clonable? = id(vv.returnSelfIUOStatic as (Bool) -> Clonable?)
let _: Clonable! = id(vv.returnSelfIUOStatic(true))
let _ = v.badClonerFn() // expected-error {{member 'badClonerFn' cannot be used on value of protocol type 'Clonable'; use a generic constraint instead}}
let _ = v.veryBadClonerFn() // expected-error {{member 'veryBadClonerFn' cannot be used on value of protocol type 'Clonable'; use a generic constraint instead}}
}
// rdar://problem/50099849
protocol Trivial {
associatedtype T
}
func rdar_50099849() {
struct A : Trivial {
typealias T = A
}
struct B<C : Trivial> : Trivial { // expected-note {{'C' declared as parameter to type 'B'}}
typealias T = C.T
}
struct C<W: Trivial, Z: Trivial> : Trivial where W.T == Z.T {
typealias T = W.T
}
let _ = C<A, B>() // expected-error {{generic parameter 'C' could not be inferred}}
// expected-note@-1 {{explicitly specify the generic arguments to fix this issue}} {{17-17=<<#C: Trivial#>>}}
}
// rdar://problem/50512161 - improve diagnostic when generic parameter cannot be deduced
func rdar_50512161() {
struct Item {}
struct TrivialItem : Trivial {
typealias T = Item?
}
func foo<I>(_: I.Type = I.self, item: I.T) where I : Trivial { // expected-note {{in call to function 'foo(_:item:)'}}
fatalError()
}
func bar(_ item: Item) {
foo(item: item) // expected-error {{generic parameter 'I' could not be inferred}}
}
}
// SR-11609: Compiler crash on missing conformance for default param
func test_sr_11609() {
func foo<T : Initable>(_ x: T = .init()) -> T { x } // expected-note {{where 'T' = 'String'}}
let _: String = foo()
// expected-error@-1 {{local function 'foo' requires that 'String' conform to 'Initable'}}
}
// rdar://70814576 -- failed to produce a diagnostic when implicit value-to-optional conversion is involved.
func rdar70814576() {
struct S {}
func test(_: Fooable?) {
}
test(S()) // expected-error {{argument type 'S' does not conform to expected type 'Fooable'}}
}
extension Optional : Trivial {
typealias T = Wrapped
}
extension UnsafePointer : Trivial {
typealias T = Int
}
extension AnyHashable : Trivial {
typealias T = Int
}
extension UnsafeRawPointer : Trivial {
typealias T = Int
}
extension UnsafeMutableRawPointer : Trivial {
typealias T = Int
}
func test_inference_through_implicit_conversion() {
struct C : Hashable {}
func test<T: Trivial>(_: T) -> T {}
var arr: [C] = []
let ptr: UnsafeMutablePointer<C> = UnsafeMutablePointer(bitPattern: 0)!
let rawPtr: UnsafeMutableRawPointer = UnsafeMutableRawPointer(bitPattern: 0)!
let _: C? = test(C()) // Ok -> argument is implicitly promoted into an optional
let _: UnsafePointer<C> = test([C()]) // Ok - argument is implicitly converted to a pointer
let _: UnsafeRawPointer = test([C()]) // Ok - argument is implicitly converted to a raw pointer
let _: UnsafeMutableRawPointer = test(&arr) // Ok - inout Array<T> -> UnsafeMutableRawPointer
let _: UnsafePointer<C> = test(ptr) // Ok - UnsafeMutablePointer<T> -> UnsafePointer<T>
let _: UnsafeRawPointer = test(ptr) // Ok - UnsafeMutablePointer<T> -> UnsafeRawPointer
let _: UnsafeRawPointer = test(rawPtr) // Ok - UnsafeMutableRawPointer -> UnsafeRawPointer
let _: UnsafeMutableRawPointer = test(ptr) // Ok - UnsafeMutablePointer<T> -> UnsafeMutableRawPointer
let _: AnyHashable = test(C()) // Ok - argument is implicitly converted to `AnyHashable` because it's Hashable
}
// Make sure that conformances transitively checked through implicit conversions work with conditional requirements
protocol TestCond {}
extension Optional : TestCond where Wrapped == Int? {}
func simple<T : TestCond>(_ x: T) -> T { x }
func overloaded<T: TestCond>(_ x: T) -> T { x }
func overloaded<T: TestCond>(_ x: String) -> T { fatalError() }
func overloaded_result() -> Int { 42 }
func overloaded_result() -> String { "" }
func test_arg_conformance_with_conditional_reqs(i: Int) {
let _: Int?? = simple(i)
let _: Int?? = overloaded(i)
let _: Int?? = simple(overloaded_result())
let _: Int?? = overloaded(overloaded_result())
}
// rdar://77570994 - regression in type unification for literal collections
protocol Elt {
}
extension Int : Elt {}
extension Int64 : Elt {}
extension Dictionary : Elt where Key == String, Value: Elt {}
struct Object {}
extension Object : ExpressibleByDictionaryLiteral {
init(dictionaryLiteral elements: (String, Elt)...) {
}
}
enum E {
case test(cond: Bool, v: Int64)
var test_prop: Object {
switch self {
case let .test(cond, v):
return ["obj": ["a": v, "b": cond ? 0 : 42]] // Ok
}
}
}
| apache-2.0 | e865a0262de69aec8ec901ab5c80ecc4 | 28.702495 | 162 | 0.602132 | 3.664457 | false | false | false | false |
HarrisLee/Utils | MySampleCode-master/CustomTransition/CustomTransition-Swift/CustomTransition-Swift/Interactivity/TransitionInteractionController.swift | 1 | 2877 | //
// TransitionInteractionController.swift
// CustomTransition-Swift
//
// Created by 张星宇 on 16/2/8.
// Copyright © 2016年 zxy. All rights reserved.
//
import UIKit
class TransitionInteractionController: UIPercentDrivenInteractiveTransition {
var transitionContext: UIViewControllerContextTransitioning? = nil
var gestureRecognizer: UIScreenEdgePanGestureRecognizer
var edge: UIRectEdge
init(gestureRecognizer: UIScreenEdgePanGestureRecognizer, edgeForDragging edge: UIRectEdge) {
assert(edge == .Top || edge == .Bottom || edge == .Left || edge == .Right,
"edgeForDragging must be one of UIRectEdgeTop, UIRectEdgeBottom, UIRectEdgeLeft, or UIRectEdgeRight.")
self.gestureRecognizer = gestureRecognizer
self.edge = edge
super.init()
self.gestureRecognizer.addTarget(self, action: Selector("gestureRecognizeDidUpdate:"))
}
override func startInteractiveTransition(transitionContext: UIViewControllerContextTransitioning) {
self.transitionContext = transitionContext
super.startInteractiveTransition(transitionContext)
}
/**
用于根据计算动画完成的百分比
:param: gesture 当前的滑动手势,通过这个手势获取滑动的位移
:returns: 返回动画完成的百分比
*/
private func percentForGesture(gesture: UIScreenEdgePanGestureRecognizer) -> CGFloat {
let transitionContainerView = transitionContext?.containerView()
let locationInSourceView = gesture.locationInView(transitionContainerView)
let width = transitionContainerView?.bounds.width
let height = transitionContainerView?.bounds.height
switch self.edge {
case UIRectEdge.Right: return (width! - locationInSourceView.x) / width!
case UIRectEdge.Left: return locationInSourceView.x / width!
case UIRectEdge.Bottom: return (height! - locationInSourceView.y) / height!
case UIRectEdge.Top: return locationInSourceView.y / height!
default: return 0
}
}
/// 当手势有滑动时触发这个函数
func gestureRecognizeDidUpdate(gestureRecognizer: UIScreenEdgePanGestureRecognizer) {
switch gestureRecognizer.state {
case .Began: break
case .Changed: self.updateInteractiveTransition(self.percentForGesture(gestureRecognizer)) //手势滑动,更新百分比
case .Ended: // 滑动结束,判断是否超过一半,如果是则完成剩下的动画,否则取消动画
if self.percentForGesture(gestureRecognizer) >= 0.5 {
self.finishInteractiveTransition()
}
else {
self.cancelInteractiveTransition()
}
default: self.cancelInteractiveTransition()
}
}
}
| mit | a971742559630a1cb5ef5c8b77c95169 | 37.114286 | 114 | 0.686657 | 5.546778 | false | false | false | false |
Allen17/InternationalSpaceStation | InternationalSpaceStation/ISSFavoriteLocation.swift | 1 | 1010 | //
// ISSFavoriteLocation.swift
// InternationalSpaceStation
//
// Created by Allen Wong on 3/17/16.
// Copyright © 2016 Allen Wong. All rights reserved.
//
import Foundation
import MapKit
import CoreLocation
class ISSFavoriteLocation
{
static let sharedInstance = ISSFavoriteLocation()
var favoriteLocation: [MKPointAnnotation] = []
func addNewFavoriteLocation(coordinate: CLLocationCoordinate2D?)
{
guard let favoriteCoordinate = coordinate else
{
return
}
if favoriteLocation.filter({$0.coordinate.latitude == favoriteCoordinate.latitude && $0.coordinate.longitude == favoriteCoordinate.longitude}).isEmpty
{
let newFaovriateLocation = MKPointAnnotation()
newFaovriateLocation.coordinate = favoriteCoordinate
newFaovriateLocation.title = "lat: \(favoriteCoordinate.latitude), lng: \(favoriteCoordinate.longitude)"
favoriteLocation.append(newFaovriateLocation)
}
}
} | mit | 9def5a5215bea174a9a3a5d107cb6bc1 | 26.297297 | 159 | 0.695738 | 4.874396 | false | false | false | false |
dcunited001/SpectraNu | Spectra-OSX/SpectraTasks/SpectraEnumDefs.swift | 1 | 28388 | //
// SpectraEnumDefs.swift
// SpectraOSX
//
// Created by David Conner on 2/22/16.
// Copyright © 2016 Spectra. All rights reserved.
//
import Foundation
import Metal
import ModelIO
class SpectraEnumDefs {
static let mdlVertexFormat = [
"Invalid": MDLVertexFormat.Invalid.rawValue,
"PackedBit": MDLVertexFormat.PackedBit.rawValue,
"UCharBits": MDLVertexFormat.UCharBits.rawValue,
"CharBits": MDLVertexFormat.CharBits.rawValue,
"UCharNormalizedBits": MDLVertexFormat.UCharNormalizedBits.rawValue,
"CharNormalizedBits": MDLVertexFormat.CharNormalizedBits.rawValue,
"UShortBits": MDLVertexFormat.UShortBits.rawValue,
"ShortBits": MDLVertexFormat.ShortBits.rawValue,
"UShortNormalizedBits": MDLVertexFormat.UShortNormalizedBits.rawValue,
"ShortNormalizedBits": MDLVertexFormat.ShortNormalizedBits.rawValue,
"UIntBits": MDLVertexFormat.UIntBits.rawValue,
"IntBits": MDLVertexFormat.IntBits.rawValue,
"HalfBits": MDLVertexFormat.HalfBits.rawValue,
"FloatBits": MDLVertexFormat.FloatBits.rawValue,
"UChar": MDLVertexFormat.UChar.rawValue,
"UChar2": MDLVertexFormat.UChar2.rawValue,
"UChar3": MDLVertexFormat.UChar3.rawValue,
"UChar4": MDLVertexFormat.UChar4.rawValue,
"Char": MDLVertexFormat.Char.rawValue,
"Char2": MDLVertexFormat.Char2.rawValue,
"Char3": MDLVertexFormat.Char3.rawValue,
"Char4": MDLVertexFormat.Char4.rawValue,
"UCharNormalized": MDLVertexFormat.UCharNormalized.rawValue,
"UChar2Normalized": MDLVertexFormat.UChar2Normalized.rawValue,
"UChar3Normalized": MDLVertexFormat.UChar3Normalized.rawValue,
"UChar4Normalized": MDLVertexFormat.UChar4Normalized.rawValue,
"CharNormalized": MDLVertexFormat.CharNormalized.rawValue,
"Char2Normalized": MDLVertexFormat.Char2Normalized.rawValue,
"Char3Normalized": MDLVertexFormat.Char3Normalized.rawValue,
"Char4Normalized": MDLVertexFormat.Char4Normalized.rawValue,
"UShort": MDLVertexFormat.UShort.rawValue,
"UShort2": MDLVertexFormat.UShort2.rawValue,
"UShort3": MDLVertexFormat.UShort3.rawValue,
"UShort4": MDLVertexFormat.UShort4.rawValue,
"Short": MDLVertexFormat.Short.rawValue,
"Short2": MDLVertexFormat.Short2.rawValue,
"Short3": MDLVertexFormat.Short3.rawValue,
"Short4": MDLVertexFormat.Short4.rawValue,
"UShortNormalized": MDLVertexFormat.UShortNormalized.rawValue,
"UShort2Normalized": MDLVertexFormat.UShort2Normalized.rawValue,
"UShort3Normalized": MDLVertexFormat.UShort3Normalized.rawValue,
"UShort4Normalized": MDLVertexFormat.UShort4Normalized.rawValue,
"ShortNormalized": MDLVertexFormat.ShortNormalized.rawValue,
"Short2Normalized": MDLVertexFormat.Short2Normalized.rawValue,
"Short3Normalized": MDLVertexFormat.Short3Normalized.rawValue,
"Short4Normalized": MDLVertexFormat.Short4Normalized.rawValue,
"UInt": MDLVertexFormat.UInt.rawValue,
"UInt2": MDLVertexFormat.UInt2.rawValue,
"UInt3": MDLVertexFormat.UInt3.rawValue,
"UInt4": MDLVertexFormat.UInt4.rawValue,
"Int": MDLVertexFormat.Int.rawValue,
"Int2": MDLVertexFormat.Int2.rawValue,
"Int3": MDLVertexFormat.Int3.rawValue,
"Int4": MDLVertexFormat.Int4.rawValue,
"Half": MDLVertexFormat.Half.rawValue,
"Half2": MDLVertexFormat.Half2.rawValue,
"Half3": MDLVertexFormat.Half3.rawValue,
"Half4": MDLVertexFormat.Half4.rawValue,
"Float": MDLVertexFormat.Float.rawValue,
"Float2": MDLVertexFormat.Float2.rawValue,
"Float3": MDLVertexFormat.Float3.rawValue,
"Float4": MDLVertexFormat.Float4.rawValue,
"Int1010102Normalized": MDLVertexFormat.Int1010102Normalized.rawValue,
"UInt1010102Normalized": MDLVertexFormat.UInt1010102Normalized.rawValue]
static let mdlMaterialSemantic = [
"BaseColor": MDLMaterialSemantic.BaseColor.rawValue,
"Subsurface": MDLMaterialSemantic.Subsurface.rawValue,
"Metallic": MDLMaterialSemantic.Metallic.rawValue,
"Specular": MDLMaterialSemantic.Specular.rawValue,
"SpecularExponent": MDLMaterialSemantic.SpecularExponent.rawValue,
"SpecularTint": MDLMaterialSemantic.SpecularTint.rawValue,
"Roughness": MDLMaterialSemantic.Roughness.rawValue,
"Anisotropic": MDLMaterialSemantic.Anisotropic.rawValue,
"AnisotropicRotation": MDLMaterialSemantic.AnisotropicRotation.rawValue,
"Sheen": MDLMaterialSemantic.Sheen.rawValue,
"SheenTint": MDLMaterialSemantic.SheenTint.rawValue,
"Clearcoat": MDLMaterialSemantic.Clearcoat.rawValue,
"ClearcoatGloss": MDLMaterialSemantic.ClearcoatGloss.rawValue,
"Emission": MDLMaterialSemantic.Emission.rawValue,
"Bump": MDLMaterialSemantic.Bump.rawValue,
"Opacity": MDLMaterialSemantic.Opacity.rawValue,
"InterfaceIndexOfRefraction": MDLMaterialSemantic.InterfaceIndexOfRefraction.rawValue,
"MaterialIndexOfRefraction": MDLMaterialSemantic.MaterialIndexOfRefraction.rawValue,
"ObjectSpaceNormal": MDLMaterialSemantic.ObjectSpaceNormal.rawValue,
"TangentSpaceNormal": MDLMaterialSemantic.TangentSpaceNormal.rawValue,
"Displacement": MDLMaterialSemantic.Displacement.rawValue,
"DisplacementScale": MDLMaterialSemantic.DisplacementScale.rawValue,
"AmbientOcclusion": MDLMaterialSemantic.AmbientOcclusion.rawValue,
"AmbientOcclusionScale": MDLMaterialSemantic.AmbientOcclusionScale.rawValue,
"None": MDLMaterialSemantic.None.rawValue,
"UserDefined": MDLMaterialSemantic.UserDefined.rawValue
]
static let mdlMaterialPropertyType = [
"None": MDLMaterialPropertyType.None.rawValue,
"String": MDLMaterialPropertyType.String.rawValue,
"URL": MDLMaterialPropertyType.URL.rawValue,
"Texture": MDLMaterialPropertyType.Texture.rawValue,
"Color": MDLMaterialPropertyType.Color.rawValue,
"Float": MDLMaterialPropertyType.Float.rawValue,
"Float2": MDLMaterialPropertyType.Float2.rawValue,
"Float3": MDLMaterialPropertyType.Float3.rawValue,
"Float4": MDLMaterialPropertyType.Float4.rawValue,
"Matrix44": MDLMaterialPropertyType.Matrix44.rawValue
]
static let mdlMaterialTextureWrapMode = [
"Clamp": MDLMaterialTextureWrapMode.Clamp.rawValue,
"Repeat": MDLMaterialTextureWrapMode.Repeat.rawValue,
"Mirror": MDLMaterialTextureWrapMode.Mirror.rawValue
]
static let mdlMaterialTextureFilterMode = [
"Nearest": MDLMaterialTextureFilterMode.Nearest.rawValue,
"Linear": MDLMaterialTextureFilterMode.Linear.rawValue
]
static let mdlMaterialMipMapFilterMode = [
"Nearest": MDLMaterialMipMapFilterMode.Nearest.rawValue,
"Linear": MDLMaterialMipMapFilterMode.Linear.rawValue
]
static let mdlMeshBufferType = [
"Vertex": MDLMeshBufferType.Vertex.rawValue,
"Index": MDLMeshBufferType.Index.rawValue
]
static let mdlGeometryType = [
"TypePoints": UInt(MDLGeometryType.TypePoints.rawValue),
"TypeLines": UInt(MDLGeometryType.TypeLines.rawValue),
"TypeTriangles": UInt(MDLGeometryType.TypeTriangles.rawValue),
"TypeTriangleStrips": UInt(MDLGeometryType.TypeTriangleStrips.rawValue),
"TypeQuads": UInt(MDLGeometryType.TypeQuads.rawValue),
"TypeVariableTopology": UInt(MDLGeometryType.TypeVariableTopology.rawValue)
]
static let mdlIndexBitDepth = [
"Invalid": MDLIndexBitDepth.Invalid.rawValue,
"UInt8": MDLIndexBitDepth.UInt8.rawValue,
"UInt16": MDLIndexBitDepth.UInt16.rawValue,
"UInt32": MDLIndexBitDepth.UInt32.rawValue
]
static let mdlLightType = [
"Unknown": MDLLightType.Unknown.rawValue,
"Ambient": MDLLightType.Ambient.rawValue,
"Directional": MDLLightType.Directional.rawValue,
"Spot": MDLLightType.Spot.rawValue,
"Point": MDLLightType.Point.rawValue,
"Linear": MDLLightType.Linear.rawValue,
"DiscArea": MDLLightType.DiscArea.rawValue,
"RectangularArea": MDLLightType.RectangularArea.rawValue,
"SuperElliptical": MDLLightType.SuperElliptical.rawValue,
"Photometric": MDLLightType.Photometric.rawValue,
"Probe": MDLLightType.Probe.rawValue,
"Environment": MDLLightType.Environment.rawValue
]
}
class MetalEnumDefs {
static let mtlVertexStepFunction = [
"Constant": MTLVertexStepFunction.Constant.rawValue,
"PerVertex": MTLVertexStepFunction.PerVertex.rawValue,
"PerInstance": MTLVertexStepFunction.PerInstance.rawValue
]
static let mtlCompareFunction = [
"Never": MTLCompareFunction.Never.rawValue,
"Less": MTLCompareFunction.Less.rawValue,
"Equal": MTLCompareFunction.Equal.rawValue,
"LessEqual": MTLCompareFunction.LessEqual.rawValue,
"Greater": MTLCompareFunction.Greater.rawValue,
"NotEqual": MTLCompareFunction.NotEqual.rawValue,
"GreaterEqual": MTLCompareFunction.GreaterEqual.rawValue,
"Always": MTLCompareFunction.Always.rawValue
]
static let mtlStencilOperation = [
"Keep": MTLStencilOperation.Keep.rawValue,
"Zero": MTLStencilOperation.Zero.rawValue,
"Replace": MTLStencilOperation.Replace.rawValue,
"IncrementClamp": MTLStencilOperation.IncrementClamp.rawValue,
"DecrementClamp": MTLStencilOperation.DecrementClamp.rawValue,
"Invert": MTLStencilOperation.Invert.rawValue,
"IncrementWrap": MTLStencilOperation.IncrementWrap.rawValue,
"DecrementWrap": MTLStencilOperation.DecrementWrap.rawValue
]
static let mtlVertexFormat = [
"Invalid": MTLVertexFormat.Invalid.rawValue,
"UChar2": MTLVertexFormat.UChar2.rawValue,
"UChar3": MTLVertexFormat.UChar3.rawValue,
"UChar4": MTLVertexFormat.UChar4.rawValue,
"Char2": MTLVertexFormat.Char2.rawValue,
"Char3": MTLVertexFormat.Char3.rawValue,
"Char4": MTLVertexFormat.Char4.rawValue,
"UChar2Normalized": MTLVertexFormat.UChar2Normalized.rawValue,
"UChar3Normalized": MTLVertexFormat.UChar3Normalized.rawValue,
"UChar4Normalized": MTLVertexFormat.UChar4Normalized.rawValue,
"Char2Normalized": MTLVertexFormat.Char2Normalized.rawValue,
"Char3Normalized": MTLVertexFormat.Char3Normalized.rawValue,
"Char4Normalized": MTLVertexFormat.Char4Normalized.rawValue,
"UShort2": MTLVertexFormat.UShort2.rawValue,
"UShort3": MTLVertexFormat.UShort3.rawValue,
"UShort4": MTLVertexFormat.UShort4.rawValue,
"Short2": MTLVertexFormat.Short2.rawValue,
"Short3": MTLVertexFormat.Short3.rawValue,
"Short4": MTLVertexFormat.Short4.rawValue,
"UShort2Normalized": MTLVertexFormat.UShort2Normalized.rawValue,
"UShort3Normalized": MTLVertexFormat.UShort3Normalized.rawValue,
"UShort4Normalized": MTLVertexFormat.UShort4Normalized.rawValue,
"Short2Normalized": MTLVertexFormat.Short2Normalized.rawValue,
"Short3Normalized": MTLVertexFormat.Short3Normalized.rawValue,
"Short4Normalized": MTLVertexFormat.Short4Normalized.rawValue,
"Half2": MTLVertexFormat.Half2.rawValue,
"Half3": MTLVertexFormat.Half3.rawValue,
"Half4": MTLVertexFormat.Half4.rawValue,
"Float": MTLVertexFormat.Float.rawValue,
"Float2": MTLVertexFormat.Float2.rawValue,
"Float3": MTLVertexFormat.Float3.rawValue,
"Float4": MTLVertexFormat.Float4.rawValue,
"Int": MTLVertexFormat.Int.rawValue,
"Int2": MTLVertexFormat.Int2.rawValue,
"Int3": MTLVertexFormat.Int3.rawValue,
"Int4": MTLVertexFormat.Int4.rawValue,
"UInt": MTLVertexFormat.UInt.rawValue,
"UInt2": MTLVertexFormat.UInt2.rawValue,
"UInt3": MTLVertexFormat.UInt3.rawValue,
"UInt4": MTLVertexFormat.UInt4.rawValue,
"Int1010102Normalized": MTLVertexFormat.Int1010102Normalized.rawValue,
"UInt1010102Normalized": MTLVertexFormat.UInt1010102Normalized.rawValue
]
static let mtlBlendFactor = [
"Zero": MTLBlendFactor.Zero.rawValue,
"One": MTLBlendFactor.One.rawValue,
"SourceColor": MTLBlendFactor.SourceColor.rawValue,
"OneMinusSourceColor": MTLBlendFactor.OneMinusSourceColor.rawValue,
"SourceAlpha": MTLBlendFactor.SourceAlpha.rawValue,
"OneMinusSourceAlpha": MTLBlendFactor.OneMinusSourceAlpha.rawValue,
"DestinationColor": MTLBlendFactor.DestinationColor.rawValue,
"OneMinusDestinationColor": MTLBlendFactor.OneMinusDestinationColor.rawValue,
"DestinationAlpha": MTLBlendFactor.DestinationAlpha.rawValue,
"OneMinusDestinationAlpha": MTLBlendFactor.OneMinusDestinationAlpha.rawValue,
"SourceAlphaSaturated": MTLBlendFactor.SourceAlphaSaturated.rawValue,
"BlendColor": MTLBlendFactor.BlendColor.rawValue,
"OneMinusBlendColor": MTLBlendFactor.OneMinusBlendColor.rawValue,
"BlendAlpha": MTLBlendFactor.BlendAlpha.rawValue,
"OneMinusBlendAlpha": MTLBlendFactor.OneMinusBlendAlpha.rawValue
]
static let mtlBlendOperation = [
"Add": MTLBlendOperation.Add.rawValue,
"Subtract": MTLBlendOperation.Subtract.rawValue,
"ReverseSubtract": MTLBlendOperation.ReverseSubtract.rawValue,
"Min": MTLBlendOperation.Min.rawValue,
"Max": MTLBlendOperation.Max.rawValue
]
static let mtlLoadAction = [
"DontCare": MTLLoadAction.DontCare.rawValue,
"Load": MTLLoadAction.Load.rawValue,
"Clear": MTLLoadAction.Clear.rawValue
]
static let mtlStoreAction = [
"DontCare": MTLStoreAction.DontCare.rawValue,
"Store": MTLStoreAction.Store.rawValue,
"MultisampleResolve": MTLStoreAction.MultisampleResolve.rawValue
]
// Only available on specific versions of iOS
static let mtlMultisampleDepthResolveFilter: [String: UInt] = [
// TODO: how to access this enum's values?
"Sample0": 0,
"Min": 1,
"Max": 2
]
static let mtlSamplerMinMagFilter = [
"Nearest": MTLSamplerMinMagFilter.Nearest.rawValue,
"Linear": MTLSamplerMinMagFilter.Linear.rawValue
]
static let mtlSamplerMipFilter = [
"NotMipmapped": MTLSamplerMipFilter.NotMipmapped.rawValue,
"Nearest": MTLSamplerMipFilter.Nearest.rawValue,
"Linear": MTLSamplerMipFilter.Linear.rawValue
]
static let mtlSamplerAddressMode = [
"ClampToEdge": MTLSamplerAddressMode.ClampToEdge.rawValue,
"MirrorClampToEdge": MTLSamplerAddressMode.MirrorClampToEdge.rawValue,
"Repeat": MTLSamplerAddressMode.Repeat.rawValue,
"MirrorRepeat": MTLSamplerAddressMode.MirrorRepeat.rawValue,
"ClampToZero": MTLSamplerAddressMode.ClampToZero.rawValue
]
static let mtlTextureType = [
"Type1D": MTLTextureType.Type1D.rawValue,
"Type1DArray": MTLTextureType.Type1DArray.rawValue,
"Type2D": MTLTextureType.Type2D.rawValue,
"Type2DArray": MTLTextureType.Type2DArray.rawValue,
"Type2DMultisample": MTLTextureType.Type2DMultisample.rawValue,
"TypeCube": MTLTextureType.TypeCube.rawValue,
"TypeCubeArray": MTLTextureType.TypeCubeArray.rawValue,
"Type3D": MTLTextureType.Type3D.rawValue
]
static let mtlCpuCacheMode = [
"DefaultCache": MTLCPUCacheMode.DefaultCache.rawValue,
"WriteCombined": MTLCPUCacheMode.WriteCombined.rawValue
]
static let mtlStorageMode = [
"Shared": MTLStorageMode.Shared.rawValue,
"Managed": MTLStorageMode.Managed.rawValue,
"Private": MTLStorageMode.Private.rawValue
]
static let mtlPurgeableState = [
"KeepCurrent": MTLPurgeableState.KeepCurrent.rawValue,
"NonVolatile": MTLPurgeableState.NonVolatile.rawValue,
"Volatile": MTLPurgeableState.Volatile.rawValue,
"Empty": MTLPurgeableState.Empty.rawValue
]
static let mtlPixelFormat = [
"Invalid": MTLPixelFormat.Invalid.rawValue,
"A8Unorm": MTLPixelFormat.A8Unorm.rawValue,
"R8Unorm": MTLPixelFormat.R8Unorm.rawValue,
"R8Snorm": MTLPixelFormat.R8Snorm.rawValue,
"R8Uint": MTLPixelFormat.R8Uint.rawValue,
"R8Sint": MTLPixelFormat.R8Sint.rawValue,
"R16Unorm": MTLPixelFormat.R16Unorm.rawValue,
"R16Snorm": MTLPixelFormat.R16Snorm.rawValue,
"R16Uint": MTLPixelFormat.R16Uint.rawValue,
"R16Sint": MTLPixelFormat.R16Sint.rawValue,
"R16Float": MTLPixelFormat.R16Float.rawValue,
"RG8Unorm": MTLPixelFormat.RG8Unorm.rawValue,
"RG8Snorm": MTLPixelFormat.RG8Snorm.rawValue,
"RG8Uint": MTLPixelFormat.RG8Uint.rawValue,
"RG8Sint": MTLPixelFormat.RG8Sint.rawValue,
"R32Uint": MTLPixelFormat.R32Uint.rawValue,
"R32Sint": MTLPixelFormat.R32Sint.rawValue,
"R32Float": MTLPixelFormat.R32Float.rawValue,
"RG16Unorm": MTLPixelFormat.RG16Unorm.rawValue,
"RG16Snorm": MTLPixelFormat.RG16Snorm.rawValue,
"RG16Uint": MTLPixelFormat.RG16Uint.rawValue,
"RG16Sint": MTLPixelFormat.RG16Sint.rawValue,
"RG16Float": MTLPixelFormat.RG16Float.rawValue,
"RGBA8Unorm": MTLPixelFormat.RGBA8Unorm.rawValue,
"RGBA8Unorm_sRGB": MTLPixelFormat.RGBA8Unorm_sRGB.rawValue,
"RGBA8Snorm": MTLPixelFormat.RGBA8Snorm.rawValue,
"RGBA8Uint": MTLPixelFormat.RGBA8Uint.rawValue,
"RGBA8Sint": MTLPixelFormat.RGBA8Sint.rawValue,
"BGRA8Unorm": MTLPixelFormat.BGRA8Unorm.rawValue,
"BGRA8Unorm_sRGB": MTLPixelFormat.BGRA8Unorm_sRGB.rawValue,
"RGB10A2Unorm": MTLPixelFormat.RGB10A2Unorm.rawValue,
"RGB10A2Uint": MTLPixelFormat.RGB10A2Uint.rawValue,
"RG11B10Float": MTLPixelFormat.RG11B10Float.rawValue,
"RGB9E5Float": MTLPixelFormat.RGB9E5Float.rawValue,
"RG32Uint": MTLPixelFormat.RG32Uint.rawValue,
"RG32Sint": MTLPixelFormat.RG32Sint.rawValue,
"RG32Float": MTLPixelFormat.RG32Float.rawValue,
"RGBA16Unorm": MTLPixelFormat.RGBA16Unorm.rawValue,
"RGBA16Snorm": MTLPixelFormat.RGBA16Snorm.rawValue,
"RGBA16Uint": MTLPixelFormat.RGBA16Uint.rawValue,
"RGBA16Sint": MTLPixelFormat.RGBA16Sint.rawValue,
"RGBA16Float": MTLPixelFormat.RGBA16Float.rawValue,
"RGBA32Uint": MTLPixelFormat.RGBA32Uint.rawValue,
"RGBA32Sint": MTLPixelFormat.RGBA32Sint.rawValue,
"RGBA32Float": MTLPixelFormat.RGBA32Float.rawValue,
"BC1_RGBA": MTLPixelFormat.BC1_RGBA.rawValue,
"BC1_RGBA_sRGB": MTLPixelFormat.BC1_RGBA_sRGB.rawValue,
"BC2_RGBA": MTLPixelFormat.BC2_RGBA.rawValue,
"BC2_RGBA_sRGB": MTLPixelFormat.BC2_RGBA_sRGB.rawValue,
"BC3_RGBA": MTLPixelFormat.BC3_RGBA.rawValue,
"BC3_RGBA_sRGB": MTLPixelFormat.BC3_RGBA_sRGB.rawValue,
"BC4_RUnorm": MTLPixelFormat.BC4_RUnorm.rawValue,
"BC4_RSnorm": MTLPixelFormat.BC4_RSnorm.rawValue,
"BC5_RGUnorm": MTLPixelFormat.BC5_RGUnorm.rawValue,
"BC5_RGSnorm": MTLPixelFormat.BC5_RGSnorm.rawValue,
"BC6H_RGBFloat": MTLPixelFormat.BC6H_RGBFloat.rawValue,
"BC6H_RGBUfloat": MTLPixelFormat.BC6H_RGBUfloat.rawValue,
"BC7_RGBAUnorm": MTLPixelFormat.BC7_RGBAUnorm.rawValue,
"BC7_RGBAUnorm_sRGB": MTLPixelFormat.BC7_RGBAUnorm_sRGB.rawValue,
"GBGR422": MTLPixelFormat.GBGR422.rawValue,
"BGRG422": MTLPixelFormat.BGRG422.rawValue,
"Depth32Float": MTLPixelFormat.Depth32Float.rawValue,
"Stencil8": MTLPixelFormat.Stencil8.rawValue,
"Depth24Unorm_Stencil8": MTLPixelFormat.Depth24Unorm_Stencil8.rawValue,
"Depth32Float_Stencil8": MTLPixelFormat.Depth32Float_Stencil8.rawValue
]
// NOTE: values for an OptionSetType
static let mtlResourceOptions = [
"CPUModeDefaultCache": MTLResourceOptions.CPUCacheModeDefaultCache.rawValue,
"CPUCacheModeWriteCombined": MTLResourceOptions.CPUCacheModeWriteCombined.rawValue,
"StorageModeShared": MTLResourceOptions.StorageModeShared.rawValue,
"StorageModeManaged": MTLResourceOptions.StorageModeManaged.rawValue,
"StorageModePrivate": MTLResourceOptions.StorageModePrivate.rawValue
]
// NOTE: values for an OptionSetType
static let mtlTextureUsage = [
"Unknown": MTLTextureUsage.Unknown.rawValue,
"ShaderRead": MTLTextureUsage.ShaderRead.rawValue,
"ShaderWrite": MTLTextureUsage.ShaderWrite.rawValue,
"RenderTarget": MTLTextureUsage.RenderTarget.rawValue,
"PixelFormatView": MTLTextureUsage.PixelFormatView.rawValue
]
//
static let mtlPrimitiveType = [
"Point": MTLPrimitiveType.Point.rawValue,
"Line": MTLPrimitiveType.Line.rawValue,
"LineStrip": MTLPrimitiveType.LineStrip.rawValue,
"Triangle": MTLPrimitiveType.Triangle.rawValue,
"TriangleStrip": MTLPrimitiveType.TriangleStrip.rawValue
]
static let mtlIndexType = [
"UInt16": MTLIndexType.UInt16.rawValue,
"UInt32": MTLIndexType.UInt32.rawValue
]
static let mtlVisibilityResultMode = [
"Disabled": MTLVisibilityResultMode.Disabled.rawValue,
"Boolean": MTLVisibilityResultMode.Boolean.rawValue,
"Counting": MTLVisibilityResultMode.Counting.rawValue
]
static let mtlCullMode = [
"None": MTLCullMode.None.rawValue,
"Front": MTLCullMode.Front.rawValue,
"Back": MTLCullMode.Back.rawValue
]
static let mtlWinding = [
"Clockwise": MTLWinding.Clockwise.rawValue,
"CounterClockwise": MTLWinding.CounterClockwise.rawValue
]
static let mtlDepthClipMode = [
"Clamp": MTLDepthClipMode.Clamp.rawValue,
"Clip": MTLDepthClipMode.Clip.rawValue
]
static let mtlTriangleFillMode = [
"Fill": MTLTriangleFillMode.Fill.rawValue,
"Lines": MTLTriangleFillMode.Lines.rawValue
]
static let mtlDataType = [
"None": MTLDataType.None.rawValue,
"Struct": MTLDataType.Struct.rawValue,
"Array": MTLDataType.Array.rawValue,
"Float": MTLDataType.Float.rawValue,
"Float2": MTLDataType.Float2.rawValue,
"Float3": MTLDataType.Float3.rawValue,
"Float4": MTLDataType.Float4.rawValue,
"Float2x2": MTLDataType.Float2x2.rawValue,
"Float2x3": MTLDataType.Float2x3.rawValue,
"Float2x4": MTLDataType.Float2x4.rawValue,
"Float3x2": MTLDataType.Float3x2.rawValue,
"Float3x3": MTLDataType.Float3x3.rawValue,
"Float3x4": MTLDataType.Float3x4.rawValue,
"Float4x2": MTLDataType.Float4x2.rawValue,
"Float4x3": MTLDataType.Float4x3.rawValue,
"Float4x4": MTLDataType.Float4x4.rawValue,
"Half": MTLDataType.Half.rawValue,
"Half2": MTLDataType.Half2.rawValue,
"Half3": MTLDataType.Half3.rawValue,
"Half4": MTLDataType.Half4.rawValue,
"Half2x2": MTLDataType.Half2x2.rawValue,
"Half2x3": MTLDataType.Half2x3.rawValue,
"Half2x4": MTLDataType.Half2x4.rawValue,
"Half3x2": MTLDataType.Half3x2.rawValue,
"Half3x3": MTLDataType.Half3x3.rawValue,
"Half3x4": MTLDataType.Half3x4.rawValue,
"Half4x2": MTLDataType.Half4x2.rawValue,
"Half4x3": MTLDataType.Half4x3.rawValue,
"Half4x4": MTLDataType.Half4x4.rawValue,
"Int": MTLDataType.Int.rawValue,
"Int2": MTLDataType.Int2.rawValue,
"Int3": MTLDataType.Int3.rawValue,
"Int4": MTLDataType.Int4.rawValue,
"UInt": MTLDataType.UInt.rawValue,
"UInt2": MTLDataType.UInt2.rawValue,
"UInt3": MTLDataType.UInt3.rawValue,
"UInt4": MTLDataType.UInt4.rawValue,
"Short": MTLDataType.Short.rawValue,
"Short2": MTLDataType.Short2.rawValue,
"Short3": MTLDataType.Short3.rawValue,
"Short4": MTLDataType.Short4.rawValue,
"UShort": MTLDataType.UShort.rawValue,
"UShort2": MTLDataType.UShort2.rawValue,
"UShort3": MTLDataType.UShort3.rawValue,
"UShort4": MTLDataType.UShort4.rawValue,
"Char": MTLDataType.Char.rawValue,
"Char2": MTLDataType.Char2.rawValue,
"Char3": MTLDataType.Char3.rawValue,
"Char4": MTLDataType.Char4.rawValue,
"UChar": MTLDataType.UChar.rawValue,
"UChar2": MTLDataType.UChar2.rawValue,
"UChar3": MTLDataType.UChar3.rawValue,
"UChar4": MTLDataType.UChar4.rawValue,
"Bool": MTLDataType.Bool.rawValue,
"Bool2": MTLDataType.Bool2.rawValue,
"Bool3": MTLDataType.Bool3.rawValue,
"Bool4": MTLDataType.Bool4.rawValue
]
static let mtlArgumentType = [
"Buffer": MTLArgumentType.Buffer.rawValue,
"ThreadgroupMemory": MTLArgumentType.ThreadgroupMemory.rawValue,
"Texture": MTLArgumentType.Texture.rawValue,
"Sampler": MTLArgumentType.Sampler.rawValue
]
static let mtlArgumentAccess = [
"ReadOnly": MTLArgumentAccess.ReadOnly.rawValue,
"ReadWrite": MTLArgumentAccess.ReadWrite.rawValue,
"WriteOnly": MTLArgumentAccess.WriteOnly.rawValue
]
// option set type
static let mtlBlitOption = [
"None": MTLBlitOption.None.rawValue,
"DepthFromDepthStencil": MTLBlitOption.DepthFromDepthStencil.rawValue,
"StencilFromDepthStencil": MTLBlitOption.StencilFromDepthStencil.rawValue
]
static let mtlBufferStatus = [
"NotEnqueued": MTLCommandBufferStatus.NotEnqueued.rawValue,
"Enqueued": MTLCommandBufferStatus.Enqueued.rawValue,
"Committed": MTLCommandBufferStatus.Committed.rawValue,
"Scheduled": MTLCommandBufferStatus.Scheduled.rawValue,
"Completed": MTLCommandBufferStatus.Completed.rawValue,
"Error": MTLCommandBufferStatus.Error.rawValue
]
static let mtlCommandBufferError = [
"None": MTLCommandBufferError.None.rawValue,
"Internal": MTLCommandBufferError.Internal.rawValue,
"Timeout": MTLCommandBufferError.Timeout.rawValue,
"PageFault": MTLCommandBufferError.PageFault.rawValue,
"Blacklisted": MTLCommandBufferError.Blacklisted.rawValue,
"NotPermitted": MTLCommandBufferError.NotPermitted.rawValue,
"OutOfMemory": MTLCommandBufferError.OutOfMemory.rawValue,
"InvalidResource": MTLCommandBufferError.InvalidResource.rawValue
]
static let mtlFeatureSet = [
"OSX_GPUFamily1_v1": MTLFeatureSet.OSX_GPUFamily1_v1.rawValue
]
static let mtlPipelineOption = [
"None": MTLPipelineOption.None.rawValue,
"ArgumentInfo": MTLPipelineOption.ArgumentInfo.rawValue,
"BufferTypeInfo": MTLPipelineOption.BufferTypeInfo.rawValue
]
static let mtlFunctionType = [
"Vertex": MTLFunctionType.Vertex.rawValue,
"Fragment": MTLFunctionType.Fragment.rawValue,
"Kernel": MTLFunctionType.Kernel.rawValue
]
static let mtlLibraryError = [
"Unsupported": MTLLibraryError.Unsupported.rawValue,
"Internal": MTLLibraryError.Internal.rawValue,
"CompileFailure": MTLLibraryError.CompileFailure.rawValue,
"CompileWarning": MTLLibraryError.CompileWarning.rawValue
]
static let mtlRenderPipelineError = [
"Internal": MTLRenderPipelineError.Internal.rawValue,
"Unsupported": MTLRenderPipelineError.Unsupported.rawValue,
"InvalidInput": MTLRenderPipelineError.InvalidInput.rawValue
]
static let mtlPrimitiveTopologyClass = [
"Unspecified": MTLPrimitiveTopologyClass.Unspecified.rawValue,
"Point": MTLPrimitiveTopologyClass.Point.rawValue,
"Line": MTLPrimitiveTopologyClass.Line.rawValue,
"Triangle": MTLPrimitiveTopologyClass.Triangle.rawValue
]
} | mit | f9ac1766976e877235a043c86ef88952 | 44.49359 | 94 | 0.703632 | 4.662013 | false | false | false | false |
WeMadeCode/ZXPageView | ZXPageView/Classes/ZXPageStyle.swift | 1 | 2060 | //
// ZXPageStyle.swift
// ZXPageView
//
// Created by Anthony on 2017/8/9.
// Copyright © 2017年 Anthony. All rights reserved.
//
import UIKit
public class ZXPageStyle: NSObject {
/// 内容是否可以滚动
public var isScrollEnable:Bool = true
/// 顶部按钮属性
public var titleHeight : CGFloat = 44 // 字体高度
public var normalColor : UIColor = UIColor.gray // 非选中字体颜色
public var selectColor : UIColor = UIColor.orange // 选中字体的颜色
public var fontSize : CGFloat = 15 // 字体大小
public var titleMargin : CGFloat = 30 // 字体间距
public var isDivideByScreen : Bool = true // 当标签过少时,是否会等分屏幕
/// 滚动条属性
public var isShowBottomLine : Bool = true // 是否显示滚动条
public var bottomLineColor : UIColor = UIColor.orange // 滚动条颜色
public var bottomLineHeight : CGFloat = 2 // 滚动条高度
public var cornerRadius : CGFloat = 2 // 滚动条圆角
public var isLongStyle : Bool = true // 是否为长条形
/// 标题缩放属性
public var isScaleEnable : Bool = false // 是否支持
public var maxScale : CGFloat = 1.2 // 缩放大小
/// 是否需要显示背景
public var isShowCoverView : Bool = false //是否单个展示背景色
public var isShowEachView : Bool = false //是否全部展示背景色
public var coverBgColor : UIColor = UIColor.black //背景色颜色
public var coverAlpha : CGFloat = 0.4 //背景色透明度
public var coverMargin : CGFloat = 12 //背景边距
public var coverHeight : CGFloat = 30 //背景高度
public var coverRadius : CGFloat = 15 //背景圆角度
/// pageControl的高度
public var pageControlHeight : CGFloat = 20
}
| mit | 98d17169344f67f760b0ce8c929f001e | 30.232143 | 73 | 0.570612 | 4.214458 | false | false | false | false |
matchmore/alps-ios-sdk | Matchmore/Matchmore+Creation.swift | 1 | 6685 | //
// Matchmore+Creation.swift
// Matchmore
//
// Created by Maciej Burda on 15/11/2017.
// Copyright © 2018 Matchmore SA. All rights reserved.
//
import Foundation
import UIKit
public extension Matchmore {
/// Creates or reuses cached mobile device object. Mobile device object is used to represent the smartphone.
///
/// - Parameters:
/// - device: (Optional) Device object that will be created on MatchMore's cloud. When device is `nil` this function will use `UIDevice.current` properties to create new Mobile Device.
/// - shouldStartMonitoring: (Optional) flag that determines if created device should monitored for matches immediately after creating.
/// - completion: Callback that returns response from the Matchmore cloud.
public class func startUsingMainDevice(device: MobileDevice? = nil, shouldStartMonitoring: Bool = true, completion: @escaping ((Result<MobileDevice>) -> Void)) {
if let mainDevice = instance.mobileDevices.main, device == nil {
instance.matchMonitor.startMonitoringFor(device: mainDevice)
completion(.success(mainDevice))
return
}
let uiDevice = UIDevice.current
let mobileDevice = MobileDevice(name: device?.name ?? uiDevice.name,
platform: device?.platform ?? uiDevice.systemName,
deviceToken: device?.deviceToken ?? instance.remoteNotificationManager.deviceToken ?? "",
location: device?.location ?? instance.locationUpdateManager.lastLocation)
instance.mobileDevices.create(item: mobileDevice) { result in
if let mainDevice = result.responseObject, shouldStartMonitoring {
instance.matchMonitor.startMonitoringFor(device: mainDevice)
}
completion(result)
}
}
/// Creates new pin device. Device created this way can be accessed via pin devices store: `Matchmore.pinDevices` or through callback's `Result`.
///
/// - Parameters:
/// - device: Pin device object that will be created on MatchMore's cloud.
/// - shouldStartMonitoring: (Optional) flag that determines if created device should monitored for matches immediately after creating.
/// - completion: Callback that returns response from the Matchmore cloud.
public class func createPinDevice(pinDevice: PinDevice, shouldStartMonitoring: Bool = true, completion: @escaping ((Result<PinDevice>) -> Void)) {
instance.pinDevices.create(item: pinDevice) { result in
if let pinDevice = result.responseObject, shouldStartMonitoring {
instance.matchMonitor.startMonitoringFor(device: pinDevice)
}
completion(result)
}
}
/// Creates new publication attached to given device.
///
/// - Parameters:
/// - publication: Publication object that will be created on MatchMore's cloud.
/// - forDevice: device on which publication is supposed to be created.
/// - completion: Callback that returns response from the Matchmore cloud.
public class func createPublication(publication: Publication, forDevice: Device, completion: @escaping ((Result<Publication>) -> Void)) {
publication.deviceId = forDevice.id
instance.publications.create(item: publication) { result in
completion(result)
}
}
/// Creates new publication attached to beacon.
///
/// - Parameters:
/// - publication: Publication object that will be created on MatchMore's cloud.
/// - forBeacon: beacon on which publication is supposed to be created.
/// - completion: Callback that returns response from the Matchmore cloud.
public class func createPublication(publication: Publication, forBeacon: IBeaconTriple, completion: @escaping ((Result<Publication>) -> Void)) {
publication.deviceId = forBeacon.deviceId
instance.publications.create(item: publication) { result in
completion(result)
}
}
/// Creates new publication attached to main device.
///
/// - Parameters:
/// - publication: Publication object that will be created on MatchMore's cloud and automatically attached to main mobile device.
/// - completion: Callback that returns response from the Matchmore cloud.
public class func createPublicationForMainDevice(publication: Publication, completion: @escaping ((Result<Publication>) -> Void)) {
publication.deviceId = instance.mobileDevices.main?.id
instance.publications.create(item: publication) { result in
completion(result)
}
}
/// Creates new subscription attached to device with given id.
///
/// - Parameters:
/// - subscription: Subscription object that will be created on MatchMore's cloud.
/// - forDevice: device on which subscriptions is supposed to be created.
/// - completion: Callback that returns response from the Matchmore cloud.
public class func createSubscription(subscription: Subscription, forDevice: Device, completion: @escaping ((Result<Subscription>) -> Void)) {
subscription.deviceId = forDevice.id
instance.subscriptions.create(item: subscription) { result in
completion(result)
}
}
/// Creates new subscription attached to device with given id.
///
/// - Parameters:
/// - subscription: Subscription object that will be created on MatchMore's cloud and automatically attached to main mobile device.
/// - completion: Callback that returns response from the Matchmore cloud.
public class func createSubscriptionForMainDevice(subscription: Subscription, completion: @escaping ((Result<Subscription>) -> Void)) {
subscription.deviceId = instance.mobileDevices.main?.id
instance.subscriptions.create(item: subscription) { result in
completion(result)
}
}
/// Start monitoring matches for given device. In order to receive matches implement `MatchDelegate`.
///
/// - Parameters:
/// - device: Device object that will be monitored.
public class func startMonitoringMatches(forDevice: Device) {
instance.matchMonitor.startMonitoringFor(device: forDevice)
}
/// Stop monitoring matches for given device. In order to receive matches implement `MatchDelegate`.
///
/// - Parameters:
/// - device: Device object that will not be monitored anymore.
public class func stopMonitoringMatches(forDevice: Device) {
instance.matchMonitor.stopMonitoringFor(device: forDevice)
}
}
| mit | 56f27e9b5269e0fd6f286701dc7a0571 | 50.022901 | 190 | 0.680132 | 5.141538 | false | false | false | false |
0bmxa/CCCB-Lighter | CCCB Lighter/ViewController.swift | 1 | 2645 | //
// ViewController.swift
// CCCB Lighter
//
// Created by mxa on 03.01.2017.
// Copyright © 2017 mxa. All rights reserved.
//
import Cocoa
class ViewController: NSViewController {
let daliURL = "http://dali.club.berlin.ccc.de/cgi-bin/licht.cgi"
@IBOutlet weak var allLampsSlider: NSSlider?
@IBOutlet weak var allLampsValueLabel: NSTextField?
@IBOutlet weak var touchBarAllLampsSlider: NSSlider?
override func viewDidLoad() {
super.viewDidLoad()
self.allLampsSlider?.minValue = 150
self.allLampsSlider?.maxValue = 255
self.touchBarAllLampsSlider?.minValue = 150
self.touchBarAllLampsSlider?.maxValue = 255
self.updateUI()
// Workaround to get key events in here
NSEvent.addLocalMonitorForEvents(matching: .keyUp) { event -> NSEvent? in
self.keyUp(with: event)
return event
}
}
// Action from UI slider
@IBAction func allLampsSliderChanged(_ sender: NSSlider?) {
guard let sliderValue = self.allLampsSlider?.integerValue else { return }
self.lampValueChanged(value: sliderValue)
}
// Action from touchbar slider
@IBAction func touchBarAllLampsSliderChanged(_ sender: NSSlider) {
guard let sliderValue = self.touchBarAllLampsSlider?.integerValue else { return }
self.lampValueChanged(value: sliderValue)
}
// Action from keyboard
override func keyUp(with event: NSEvent) {
guard let keyChars = event.characters else { return }
// FIXME: Cheaply manipulates the UI slider...
if keyChars.contains("-") {
self.allLampsSlider?.integerValue -= 10
} else if keyChars.contains("+") || keyChars.contains("=") {
self.allLampsSlider?.integerValue += 10
}
self.allLampsSliderChanged(nil)
}
}
private extension ViewController {
// Trigger lamp value change
func lampValueChanged(value lampValue: Int) {
DaliConnector.setAllLamps(to: lampValue) {
self.updateUI()
}
}
// Update UI
func updateUI() {
DaliConnector.averageLampValue { averageLampValue in
// UI Slider
self.allLampsSlider?.integerValue = averageLampValue
// UI Label
let percentage = (Double(averageLampValue)/255.0 * 100.0).rounded()
self.allLampsValueLabel?.stringValue = "\(percentage) %"
// TouchBar Slider
self.touchBarAllLampsSlider?.integerValue = averageLampValue
}
}
}
| mit | 3a13c6827037f49bcbc017f820044e47 | 28.377778 | 89 | 0.622163 | 4.851376 | false | false | false | false |
mparrish91/gifRecipes | application/AppDelegate.swift | 1 | 4455 | //
// AppDelegate.swift
// reddift
//
// Created by sonson on 2015/09/01.
// Copyright (c) 2015年 sonson. All rights reserved.
//
import GoogleMobileAds
import reddift
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, ImageCache {
var session: Session?
var window: UIWindow?
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
// handle redirect URL from reddit.com
return OAuth2Authorizer.sharedInstance.receiveRedirect(url as URL, completion: {(result) -> Void in
switch result {
case .failure(let error):
print(error)
case .success(let token):
DispatchQueue.main.async(execute: { () -> Void in
do {
try OAuth2TokenRepository.save(token: token, of:token.name)
NotificationCenter.default.post(name: OAuth2TokenRepositoryDidSaveTokenName, object: nil, userInfo: nil)
} catch { print(error) }
})
}
})
}
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
// handle redirect URL from reddit.com
return OAuth2Authorizer.sharedInstance.receiveRedirect(url as URL, completion: {(result) -> Void in
switch result {
case .failure(let error):
print(error)
case .success(let token):
DispatchQueue.main.async(execute: { () -> Void in
do {
try OAuth2TokenRepository.save(token: token, of:token.name)
NotificationCenter.default.post(name: OAuth2TokenRepositoryDidSaveTokenName, object: nil, userInfo: nil)
} catch { print(error) }
})
}
})
}
func refreshSession() {
// refresh current session token
do {
try self.session?.refreshToken({ (result) -> Void in
switch result {
case .failure(let error):
print(error)
case .success(let token):
DispatchQueue.main.async(execute: { () -> Void in
print(token)
NotificationCenter.default.post(name: OAuth2TokenRepositoryDidSaveTokenName, object: nil, userInfo: nil)
})
}
})
} catch { print(error) }
}
func reloadSession() {
// reddit username is save NSUserDefaults using "currentName" key.
// create an authenticated or anonymous session object
if let currentName = UserDefaults.standard.object(forKey: "currentName") as? String {
do {
let token = try OAuth2TokenRepository.token(of: currentName)
self.session = Session(token: token)
self.refreshSession()
} catch { print(error) }
} else {
self.session = Session()
}
NotificationCenter.default.post(name: OAuth2TokenRepositoryDidUpdateTokenName, object: nil, userInfo: nil)
}
func applicationDidFinishLaunching(_ application: UIApplication) {
self.reloadSession()
// deleteAllThumbnails()
// deleteAllCaches()
UINavigationBar.appearance().barTintColor = UIColor.white
UINavigationBar.appearance().tintColor = UIColor(netHex: 0x4A4A4A)
// Initialize Google Mobile Ads SDK
GADMobileAds.configure(withApplicationID: "ca-app-pub-3940256099942544~1458002511")
DispatchQueue.global(qos: .default).async {
let html = ""
do {
if let data = html.data(using: .unicode) {
let attr = try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
print(attr)
}
} catch {
}
}
}
func applicationWillEnterForeground(_ application: UIApplication) {
self.refreshSession()
}
}
extension UIApplication {
static func appDelegate() -> AppDelegate? {
if let obj = self.shared.delegate as? AppDelegate {
return obj
}
return nil
}
}
| mit | 3620e00265193b78bfa7b6d41f88126b | 35.5 | 158 | 0.571076 | 5.257379 | false | false | false | false |
corichmond/turbo-adventure | project8/Project8/ViewController.swift | 20 | 3572 | //
// ViewController.swift
// Project8
//
// Created by Hudzilla on 20/11/2014.
// Copyright (c) 2014 Hudzilla. All rights reserved.
//
import Foundation
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var cluesLabel: UILabel!
@IBOutlet weak var answersLabel: UILabel!
@IBOutlet weak var currentAnswer: UITextField!
@IBOutlet weak var scoreLabel: UILabel!
var letterButtons = [UIButton]()
var activatedButtons = [UIButton]()
var solutions = [String]()
var score: Int = 0 {
didSet {
scoreLabel.text = "Score: \(score)"
}
}
var level = 1
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
for subview in view.subviews {
if subview.tag == 1001 {
let btn = subview as! UIButton
letterButtons.append(btn)
btn.addTarget(self, action: "letterTapped:", forControlEvents: .TouchUpInside)
}
}
loadLevel()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func submitTapped(sender: AnyObject) {
if let solutionPosition = find(solutions, currentAnswer.text) {
activatedButtons.removeAll()
var splitClues = answersLabel.text!.componentsSeparatedByString("\n")
splitClues[solutionPosition] = currentAnswer.text
answersLabel.text = join("\n", splitClues)
currentAnswer.text = ""
++score
if score % 7 == 0 {
let ac = UIAlertController(title: "Well done!", message: "Are you ready for the next level?", preferredStyle: .Alert)
ac.addAction(UIAlertAction(title: "Let's go!", style: .Default, handler: levelUp))
presentViewController(ac, animated: true, completion: nil)
}
}
}
@IBAction func clearTapped(sender: AnyObject) {
currentAnswer.text = ""
for btn in activatedButtons {
btn.hidden = false
}
activatedButtons.removeAll()
}
func loadLevel() {
var clueString = ""
var solutionString = ""
var letterBits = [String]()
if let levelFilePath = NSBundle.mainBundle().pathForResource("level\(level)", ofType: "txt") {
if let levelContents = NSString(contentsOfFile: levelFilePath, usedEncoding: nil, error: nil) {
var lines = levelContents.componentsSeparatedByString("\n")
lines.shuffle()
for (index, line) in enumerate(lines as! [String]) {
let parts = line.componentsSeparatedByString(": ")
let answer = parts[0]
let clue = parts[1]
clueString += "\(index + 1). \(clue)\n"
let solutionWord = answer.stringByReplacingOccurrencesOfString("|", withString: "")
solutionString += "\(count(solutionWord)) letters\n"
solutions.append(solutionWord)
let bits = answer.componentsSeparatedByString("|")
letterBits += bits
}
}
}
cluesLabel.text = clueString.stringByTrimmingCharactersInSet(.whitespaceAndNewlineCharacterSet())
answersLabel.text = solutionString.stringByTrimmingCharactersInSet(.whitespaceAndNewlineCharacterSet())
letterBits.shuffle()
letterButtons.shuffle()
if letterBits.count == letterButtons.count {
for i in 0 ..< letterBits.count {
letterButtons[i].setTitle(letterBits[i], forState: .Normal)
}
}
}
func letterTapped(btn: UIButton) {
currentAnswer.text = currentAnswer.text + btn.titleLabel!.text!
activatedButtons.append(btn)
btn.hidden = true
}
func levelUp(action: UIAlertAction!) {
// ++level // we only have one level!
solutions.removeAll(keepCapacity: true)
loadLevel()
for btn in letterButtons {
btn.hidden = false
}
}
}
| unlicense | 2b787b2474594f76326097162a04dff4 | 25.072993 | 121 | 0.701288 | 3.938258 | false | false | false | false |
JohnCoates/Aerial | Aerial/Source/Models/Extensions/NSImage+trim.swift | 1 | 3056 | //
// NSImage+trim.swift
// Aerial
//
// Created by Guillaume Louel on 23/04/2020.
// Copyright © 2020 Guillaume Louel. All rights reserved.
//
import Cocoa
extension NSImage {
func trim() -> NSImage? {
var imageRect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)
let imageRef = self.cgImage(forProposedRect: &imageRect, context: nil, hints: nil)
let trimTo = self.getTrimmedRect()
// let cutRef = imageRef?.cropping(to: trimTo)
guard let cutRef = imageRef?.cropping(to: trimTo) else {
return nil
}
return NSImage(cgImage: cutRef, size: trimTo.size)
}
// There might be a better way to do this but that's all I found...
// swiftlint:disable:next cyclomatic_complexity
private func getTrimmedRect() -> CGRect {
let bmp = self.representations[0] as! NSBitmapImageRep
let data: UnsafeMutablePointer<UInt8> = bmp.bitmapData!
var alpha: UInt8
var topCrop = 0
var bottomCrop = bmp.pixelsHigh
var leftCrop = 0
var rightCrop = bmp.pixelsWide
// Top crop
outerTop: for row in 0..<bmp.pixelsHigh {
for col in 0..<bmp.pixelsWide {
alpha = data[(bmp.pixelsWide * row + col) * 4 + 3]
if alpha != 0 {
topCrop = row
break outerTop
}
}
}
// Bottom crop
outerBottom: for row in (0..<bmp.pixelsHigh).reversed() {
for col in 0..<bmp.pixelsWide {
alpha = data[(bmp.pixelsWide * row + col) * 4 + 3]
if alpha != 0 {
bottomCrop = row
break outerBottom
}
}
}
// Left crop
outerLeft: for col in 0..<bmp.pixelsWide {
for row in 0..<bmp.pixelsHigh {
alpha = data[(bmp.pixelsWide * row + col) * 4 + 3]
if alpha != 0 {
leftCrop = col
break outerLeft
}
}
}
// Right crop
outerRight: for col in (0..<bmp.pixelsWide).reversed() {
for row in 0..<bmp.pixelsHigh {
alpha = data[(bmp.pixelsWide * row + col) * 4 + 3]
if alpha != 0 {
rightCrop = col
break outerRight
}
}
}
return CGRect(x: leftCrop, y: topCrop, width: rightCrop-leftCrop, height: bottomCrop-topCrop)
}
func tinting(with tintColor: NSColor) -> NSImage {
guard let cgImage = self.cgImage(forProposedRect: nil, context: nil, hints: nil) else { return self }
return NSImage(size: size, flipped: false) { bounds in
guard let context = NSGraphicsContext.current?.cgContext else { return false }
tintColor.set()
context.clip(to: bounds, mask: cgImage)
context.fill(bounds)
return true
}
}
}
| mit | d8ade6e08261cc553e6c44a5df133831 | 28.660194 | 109 | 0.520786 | 4.479472 | false | false | false | false |
hughbe/swift | stdlib/public/core/KeyPath.swift | 1 | 64882 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
@_transparent
internal func _abstract(
methodName: StaticString = #function,
file: StaticString = #file, line: UInt = #line
) -> Never {
#if INTERNAL_CHECKS_ENABLED
_fatalErrorMessage("abstract method", methodName, file: file, line: line,
flags: _fatalErrorFlags())
#else
_conditionallyUnreachable()
#endif
}
// MARK: Type-erased abstract base classes
/// A type-erased key path, from any root type to any resulting value type.
public class AnyKeyPath: Hashable, _AppendKeyPath {
/// The root type for this key path.
@_inlineable
public static var rootType: Any.Type {
return _rootAndValueType.root
}
/// The value type for this key path.
@_inlineable
public static var valueType: Any.Type {
return _rootAndValueType.value
}
internal final var _kvcKeyPathStringPtr: UnsafePointer<CChar>?
final public var hashValue: Int {
var hash = 0
withBuffer {
var buffer = $0
while true {
let (component, type) = buffer.next()
hash ^= _mixInt(component.value.hashValue)
if let type = type {
hash ^= _mixInt(unsafeBitCast(type, to: Int.self))
} else {
break
}
}
}
return hash
}
public static func ==(a: AnyKeyPath, b: AnyKeyPath) -> Bool {
// Fast-path identical objects
if a === b {
return true
}
// Short-circuit differently-typed key paths
if type(of: a) != type(of: b) {
return false
}
return a.withBuffer {
var aBuffer = $0
return b.withBuffer {
var bBuffer = $0
// Two equivalent key paths should have the same reference prefix
if aBuffer.hasReferencePrefix != bBuffer.hasReferencePrefix {
return false
}
while true {
let (aComponent, aType) = aBuffer.next()
let (bComponent, bType) = bBuffer.next()
if aComponent.header.endOfReferencePrefix
!= bComponent.header.endOfReferencePrefix
|| aComponent.value != bComponent.value
|| aType != bType {
return false
}
if aType == nil {
return true
}
}
}
}
}
// SPI for the Foundation overlay to allow interop with KVC keypath-based
// APIs.
public var _kvcKeyPathString: String? {
guard let ptr = _kvcKeyPathStringPtr else { return nil }
return String(validatingUTF8: ptr)
}
// MARK: Implementation details
// Prevent normal initialization. We use tail allocation via
// allocWithTailElems().
internal init() {
_sanityCheckFailure("use _create(...)")
}
// internal-with-availability
public class var _rootAndValueType: (root: Any.Type, value: Any.Type) {
_abstract()
}
public // @testable
static func _create(
capacityInBytes bytes: Int,
initializedBy body: (UnsafeMutableRawBufferPointer) -> Void
) -> Self {
_sanityCheck(bytes > 0 && bytes % 4 == 0,
"capacity must be multiple of 4 bytes")
let result = Builtin.allocWithTailElems_1(self, (bytes/4)._builtinWordValue,
Int32.self)
result._kvcKeyPathStringPtr = nil
let base = UnsafeMutableRawPointer(Builtin.projectTailElems(result,
Int32.self))
body(UnsafeMutableRawBufferPointer(start: base, count: bytes))
return result
}
func withBuffer<T>(_ f: (KeyPathBuffer) throws -> T) rethrows -> T {
defer { _fixLifetime(self) }
let base = UnsafeRawPointer(Builtin.projectTailElems(self, Int32.self))
return try f(KeyPathBuffer(base: base))
}
}
/// A partially type-erased key path, from a concrete root type to any
/// resulting value type.
public class PartialKeyPath<Root>: AnyKeyPath { }
// MARK: Concrete implementations
internal enum KeyPathKind { case readOnly, value, reference }
/// A key path from a specific root type to a specific resulting value type.
public class KeyPath<Root, Value>: PartialKeyPath<Root> {
public typealias _Root = Root
public typealias _Value = Value
public final override class var _rootAndValueType: (
root: Any.Type,
value: Any.Type
) {
return (Root.self, Value.self)
}
// MARK: Implementation
typealias Kind = KeyPathKind
class var kind: Kind { return .readOnly }
static func appendedType<AppendedValue>(
with t: KeyPath<Value, AppendedValue>.Type
) -> KeyPath<Root, AppendedValue>.Type {
let resultKind: Kind
switch (self.kind, t.kind) {
case (_, .reference):
resultKind = .reference
case (let x, .value):
resultKind = x
default:
resultKind = .readOnly
}
switch resultKind {
case .readOnly:
return KeyPath<Root, AppendedValue>.self
case .value:
return WritableKeyPath.self
case .reference:
return ReferenceWritableKeyPath.self
}
}
final func projectReadOnly(from root: Root) -> Value {
// TODO: For perf, we could use a local growable buffer instead of Any
var curBase: Any = root
return withBuffer {
var buffer = $0
while true {
let (rawComponent, optNextType) = buffer.next()
let valueType = optNextType ?? Value.self
let isLast = optNextType == nil
func project<CurValue>(_ base: CurValue) -> Value? {
func project2<NewValue>(_: NewValue.Type) -> Value? {
let newBase: NewValue = rawComponent.projectReadOnly(base)
if isLast {
_sanityCheck(NewValue.self == Value.self,
"key path does not terminate in correct type")
return unsafeBitCast(newBase, to: Value.self)
} else {
curBase = newBase
return nil
}
}
return _openExistential(valueType, do: project2)
}
if let result = _openExistential(curBase, do: project) {
return result
}
}
}
}
deinit {
withBuffer { $0.destroy() }
}
}
/// A key path that supports reading from and writing to the resulting value.
public class WritableKeyPath<Root, Value>: KeyPath<Root, Value> {
// MARK: Implementation detail
override class var kind: Kind { return .value }
// `base` is assumed to be undergoing a formal access for the duration of the
// call, so must not be mutated by an alias
func projectMutableAddress(from base: UnsafePointer<Root>)
-> (pointer: UnsafeMutablePointer<Value>, owner: Builtin.NativeObject) {
var p = UnsafeRawPointer(base)
var type: Any.Type = Root.self
var keepAlive: [AnyObject] = []
return withBuffer {
var buffer = $0
_sanityCheck(!buffer.hasReferencePrefix,
"WritableKeyPath should not have a reference prefix")
while true {
let (rawComponent, optNextType) = buffer.next()
let nextType = optNextType ?? Value.self
func project<CurValue>(_: CurValue.Type) {
func project2<NewValue>(_: NewValue.Type) {
p = rawComponent.projectMutableAddress(p,
from: CurValue.self,
to: NewValue.self,
isRoot: p == UnsafeRawPointer(base),
keepAlive: &keepAlive)
}
_openExistential(nextType, do: project2)
}
_openExistential(type, do: project)
if optNextType == nil { break }
type = nextType
}
// TODO: With coroutines, it would be better to yield here, so that
// we don't need the hack of the keepAlive array to manage closing
// accesses.
let typedPointer = p.assumingMemoryBound(to: Value.self)
return (pointer: UnsafeMutablePointer(mutating: typedPointer),
owner: keepAlive._getOwner_native())
}
}
}
/// A key path that supports reading from and writing to the resulting value
/// with reference semantics.
public class ReferenceWritableKeyPath<Root, Value>: WritableKeyPath<Root, Value> {
// MARK: Implementation detail
final override class var kind: Kind { return .reference }
final override func projectMutableAddress(from base: UnsafePointer<Root>)
-> (pointer: UnsafeMutablePointer<Value>, owner: Builtin.NativeObject) {
// Since we're a ReferenceWritableKeyPath, we know we don't mutate the base in
// practice.
return projectMutableAddress(from: base.pointee)
}
final func projectMutableAddress(from origBase: Root)
-> (pointer: UnsafeMutablePointer<Value>, owner: Builtin.NativeObject) {
var keepAlive: [AnyObject] = []
var address: UnsafeMutablePointer<Value> = withBuffer {
var buffer = $0
// Project out the reference prefix.
var base: Any = origBase
while buffer.hasReferencePrefix {
let (rawComponent, optNextType) = buffer.next()
_sanityCheck(optNextType != nil,
"reference prefix should not go to end of buffer")
let nextType = optNextType.unsafelyUnwrapped
func project<NewValue>(_: NewValue.Type) -> Any {
func project2<CurValue>(_ base: CurValue) -> Any {
return rawComponent.projectReadOnly(base) as NewValue
}
return _openExistential(base, do: project2)
}
base = _openExistential(nextType, do: project)
}
// Start formal access to the mutable value, based on the final base
// value.
func formalMutation<MutationRoot>(_ base: MutationRoot)
-> UnsafeMutablePointer<Value> {
var base2 = base
return withUnsafeBytes(of: &base2) { baseBytes in
var p = baseBytes.baseAddress.unsafelyUnwrapped
var curType: Any.Type = MutationRoot.self
while true {
let (rawComponent, optNextType) = buffer.next()
let nextType = optNextType ?? Value.self
func project<CurValue>(_: CurValue.Type) {
func project2<NewValue>(_: NewValue.Type) {
p = rawComponent.projectMutableAddress(p,
from: CurValue.self,
to: NewValue.self,
isRoot: p == baseBytes.baseAddress,
keepAlive: &keepAlive)
}
_openExistential(nextType, do: project2)
}
_openExistential(curType, do: project)
if optNextType == nil { break }
curType = nextType
}
let typedPointer = p.assumingMemoryBound(to: Value.self)
return UnsafeMutablePointer(mutating: typedPointer)
}
}
return _openExistential(base, do: formalMutation)
}
return (address, keepAlive._getOwner_native())
}
}
// MARK: Implementation details
internal enum KeyPathComponentKind {
/// The keypath projects within the storage of the outer value, like a
/// stored property in a struct.
case `struct`
/// The keypath projects from the referenced pointer, like a
/// stored property in a class.
case `class`
/// The keypath projects using a getter/setter pair.
case computed
/// The keypath optional-chains, returning nil immediately if the input is
/// nil, or else proceeding by projecting the value inside.
case optionalChain
/// The keypath optional-forces, trapping if the input is
/// nil, or else proceeding by projecting the value inside.
case optionalForce
/// The keypath wraps a value in an optional.
case optionalWrap
}
internal struct ComputedPropertyID: Hashable {
var value: Int
var isStoredProperty: Bool
var isTableOffset: Bool
static func ==(x: ComputedPropertyID, y: ComputedPropertyID) -> Bool {
return x.value == y.value
&& x.isStoredProperty == y.isStoredProperty
&& x.isTableOffset == x.isTableOffset
}
var hashValue: Int {
var hash = 0
hash ^= _mixInt(value)
hash ^= _mixInt(isStoredProperty ? 13 : 17)
hash ^= _mixInt(isTableOffset ? 19 : 23)
return hash
}
}
internal enum KeyPathComponent: Hashable {
/// The keypath projects within the storage of the outer value, like a
/// stored property in a struct.
case `struct`(offset: Int)
/// The keypath projects from the referenced pointer, like a
/// stored property in a class.
case `class`(offset: Int)
/// The keypath projects using a getter.
case get(id: ComputedPropertyID,
get: UnsafeRawPointer, argument: UnsafeRawPointer)
/// The keypath projects using a getter/setter pair. The setter can mutate
/// the base value in-place.
case mutatingGetSet(id: ComputedPropertyID,
get: UnsafeRawPointer, set: UnsafeRawPointer,
argument: UnsafeRawPointer)
/// The keypath projects using a getter/setter pair that does not mutate its
/// base.
case nonmutatingGetSet(id: ComputedPropertyID,
get: UnsafeRawPointer, set: UnsafeRawPointer,
argument: UnsafeRawPointer)
/// The keypath optional-chains, returning nil immediately if the input is
/// nil, or else proceeding by projecting the value inside.
case optionalChain
/// The keypath optional-forces, trapping if the input is
/// nil, or else proceeding by projecting the value inside.
case optionalForce
/// The keypath wraps a value in an optional.
case optionalWrap
static func ==(a: KeyPathComponent, b: KeyPathComponent) -> Bool {
switch (a, b) {
case (.struct(offset: let a), .struct(offset: let b)),
(.class (offset: let a), .class (offset: let b)):
return a == b
case (.optionalChain, .optionalChain),
(.optionalForce, .optionalForce),
(.optionalWrap, .optionalWrap):
return true
case (.get(id: let id1, get: _, argument: _),
.get(id: let id2, get: _, argument: _)):
return id1 == id2
case (.mutatingGetSet(id: let id1, get: _, set: _, argument: _),
.mutatingGetSet(id: let id2, get: _, set: _, argument: _)):
return id1 == id2
case (.nonmutatingGetSet(id: let id1, get: _, set: _, argument: _),
.nonmutatingGetSet(id: let id2, get: _, set: _, argument: _)):
return id1 == id2
case (.struct, _),
(.class, _),
(.optionalChain, _),
(.optionalForce, _),
(.optionalWrap, _),
(.get, _),
(.mutatingGetSet, _),
(.nonmutatingGetSet, _):
return false
}
}
var hashValue: Int {
var hash: Int = 0
switch self {
case .struct(offset: let a):
hash ^= _mixInt(0)
hash ^= _mixInt(a)
case .class(offset: let b):
hash ^= _mixInt(1)
hash ^= _mixInt(b)
case .optionalChain:
hash ^= _mixInt(2)
case .optionalForce:
hash ^= _mixInt(3)
case .optionalWrap:
hash ^= _mixInt(4)
case .get(id: let id, get: _, argument: _):
hash ^= _mixInt(5)
hash ^= _mixInt(id.hashValue)
case .mutatingGetSet(id: let id, get: _, set: _, argument: _):
hash ^= _mixInt(6)
hash ^= _mixInt(id.hashValue)
case .nonmutatingGetSet(id: let id, get: _, set: _, argument: _):
hash ^= _mixInt(7)
hash ^= _mixInt(id.hashValue)
}
return hash
}
}
// A class that triggers writeback to a pointer when destroyed.
internal final class MutatingWritebackBuffer<CurValue, NewValue> {
let base: UnsafeMutablePointer<CurValue>
let set: @convention(thin) (NewValue, inout CurValue, UnsafeRawPointer) -> ()
let argument: UnsafeRawPointer
var value: NewValue
deinit {
set(value, &base.pointee, argument)
}
init(base: UnsafeMutablePointer<CurValue>,
set: @escaping @convention(thin) (NewValue, inout CurValue, UnsafeRawPointer) -> (),
argument: UnsafeRawPointer,
value: NewValue) {
self.base = base
self.set = set
self.argument = argument
self.value = value
}
}
// A class that triggers writeback to a non-mutated value when destroyed.
internal final class NonmutatingWritebackBuffer<CurValue, NewValue> {
let base: CurValue
let set: @convention(thin) (NewValue, CurValue, UnsafeRawPointer) -> ()
let argument: UnsafeRawPointer
var value: NewValue
deinit {
set(value, base, argument)
}
init(base: CurValue,
set: @escaping @convention(thin) (NewValue, CurValue, UnsafeRawPointer) -> (),
argument: UnsafeRawPointer,
value: NewValue) {
self.base = base
self.set = set
self.argument = argument
self.value = value
}
}
internal struct RawKeyPathComponent {
var header: Header
var body: UnsafeRawBufferPointer
struct Header {
static var payloadMask: UInt32 {
return _SwiftKeyPathComponentHeader_PayloadMask
}
static var discriminatorMask: UInt32 {
return _SwiftKeyPathComponentHeader_DiscriminatorMask
}
static var discriminatorShift: UInt32 {
return _SwiftKeyPathComponentHeader_DiscriminatorShift
}
static var structTag: UInt32 {
return _SwiftKeyPathComponentHeader_StructTag
}
static var computedTag: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedTag
}
static var classTag: UInt32 {
return _SwiftKeyPathComponentHeader_ClassTag
}
static var optionalTag: UInt32 {
return _SwiftKeyPathComponentHeader_OptionalTag
}
static var optionalChainPayload: UInt32 {
return _SwiftKeyPathComponentHeader_OptionalChainPayload
}
static var optionalWrapPayload: UInt32 {
return _SwiftKeyPathComponentHeader_OptionalWrapPayload
}
static var optionalForcePayload: UInt32 {
return _SwiftKeyPathComponentHeader_OptionalForcePayload
}
static var endOfReferencePrefixFlag: UInt32 {
return _SwiftKeyPathComponentHeader_EndOfReferencePrefixFlag
}
static var outOfLineOffsetPayload: UInt32 {
return _SwiftKeyPathComponentHeader_OutOfLineOffsetPayload
}
static var unresolvedFieldOffsetPayload: UInt32 {
return _SwiftKeyPathComponentHeader_UnresolvedFieldOffsetPayload
}
static var unresolvedIndirectOffsetPayload: UInt32 {
return _SwiftKeyPathComponentHeader_UnresolvedIndirectOffsetPayload
}
static var computedMutatingFlag: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedMutatingFlag
}
static var computedSettableFlag: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedSettableFlag
}
static var computedIDByStoredPropertyFlag: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedIDByStoredPropertyFlag
}
static var computedIDByVTableOffsetFlag: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedIDByVTableOffsetFlag
}
static var computedHasArgumentsFlag: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedHasArgumentsFlag
}
static var computedIDResolutionMask: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedIDResolutionMask
}
static var computedIDResolved: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedIDResolved
}
static var computedIDUnresolvedIndirectPointer: UInt32 {
return _SwiftKeyPathComponentHeader_ComputedIDUnresolvedIndirectPointer
}
var _value: UInt32
var discriminator: UInt32 {
return (_value & Header.discriminatorMask) >> Header.discriminatorShift
}
var payload: UInt32 {
get {
return _value & Header.payloadMask
}
set {
_sanityCheck(newValue & Header.payloadMask == newValue,
"payload too big")
_value = _value & ~Header.payloadMask | newValue
}
}
var endOfReferencePrefix: Bool {
get {
return _value & Header.endOfReferencePrefixFlag != 0
}
set {
if newValue {
_value |= Header.endOfReferencePrefixFlag
} else {
_value &= ~Header.endOfReferencePrefixFlag
}
}
}
var kind: KeyPathComponentKind {
switch (discriminator, payload) {
case (Header.structTag, _):
return .struct
case (Header.classTag, _):
return .class
case (Header.computedTag, _):
return .computed
case (Header.optionalTag, Header.optionalChainPayload):
return .optionalChain
case (Header.optionalTag, Header.optionalWrapPayload):
return .optionalWrap
case (Header.optionalTag, Header.optionalForcePayload):
return .optionalForce
default:
_sanityCheckFailure("invalid header")
}
}
// The component header is 4 bytes, but may be followed by an aligned
// pointer field for some kinds of component, forcing padding.
static var pointerAlignmentSkew: Int {
return MemoryLayout<Int>.size - MemoryLayout<Int32>.size
}
var bodySize: Int {
switch kind {
case .struct, .class:
if payload == Header.payloadMask { return 4 } // overflowed
return 0
case .optionalChain, .optionalForce, .optionalWrap:
return 0
case .computed:
let ptrSize = MemoryLayout<Int>.size
// align to pointer, minimum two pointers for id and get
var total = Header.pointerAlignmentSkew + ptrSize * 2
// additional word for a setter
if payload & Header.computedSettableFlag != 0 {
total += ptrSize
}
// TODO: Include the argument size
_sanityCheck(payload & Header.computedHasArgumentsFlag == 0,
"arguments not implemented")
return total
}
}
var isTrivial: Bool {
switch kind {
case .struct, .class, .optionalChain, .optionalForce, .optionalWrap:
return true
case .computed:
// TODO: consider nontrivial arguments
_sanityCheck(payload & Header.computedHasArgumentsFlag == 0,
"arguments not implemented")
return true
}
}
}
var _structOrClassOffset: Int {
_sanityCheck(header.kind == .struct || header.kind == .class,
"no offset for this kind")
// An offset too large to fit inline is represented by a signal and stored
// in the body.
if header.payload == Header.outOfLineOffsetPayload {
// Offset overflowed into body
_sanityCheck(body.count >= MemoryLayout<UInt32>.size,
"component not big enough")
return Int(body.load(as: UInt32.self))
}
return Int(header.payload)
}
var _computedIDValue: Int {
_sanityCheck(header.kind == .computed,
"not a computed property")
return body.load(fromByteOffset: Header.pointerAlignmentSkew,
as: Int.self)
}
var _computedID: ComputedPropertyID {
let payload = header.payload
return ComputedPropertyID(
value: _computedIDValue,
isStoredProperty: payload & Header.computedIDByStoredPropertyFlag != 0,
isTableOffset: payload & Header.computedIDByVTableOffsetFlag != 0)
}
var _computedGetter: UnsafeRawPointer {
_sanityCheck(header.kind == .computed,
"not a computed property")
return body.load(
fromByteOffset: Header.pointerAlignmentSkew + MemoryLayout<Int>.size,
as: UnsafeRawPointer.self)
}
var _computedSetter: UnsafeRawPointer {
_sanityCheck(header.kind == .computed,
"not a computed property")
_sanityCheck(header.payload & Header.computedSettableFlag != 0,
"not a settable property")
return body.load(
fromByteOffset: Header.pointerAlignmentSkew + MemoryLayout<Int>.size * 2,
as: UnsafeRawPointer.self)
}
var value: KeyPathComponent {
switch header.kind {
case .struct:
return .struct(offset: _structOrClassOffset)
case .class:
return .class(offset: _structOrClassOffset)
case .optionalChain:
return .optionalChain
case .optionalForce:
return .optionalForce
case .optionalWrap:
return .optionalWrap
case .computed:
let isSettable = header.payload & Header.computedSettableFlag != 0
let isMutating = header.payload & Header.computedMutatingFlag != 0
_sanityCheck(header.payload & Header.computedHasArgumentsFlag == 0,
"arguments not implemented")
let id = _computedID
let get = _computedGetter
switch (isSettable, isMutating) {
case (false, false):
return .get(id: id, get: get, argument: get)
case (true, false):
return .nonmutatingGetSet(id: id,
get: get,
set: _computedSetter,
argument: get)
case (true, true):
return .mutatingGetSet(id: id,
get: get,
set: _computedSetter,
argument: get)
case (false, true):
_sanityCheckFailure("impossible")
}
}
}
func destroy() {
switch header.kind {
case .struct,
.class,
.optionalChain,
.optionalForce,
.optionalWrap:
// trivial
return
case .computed:
// TODO: consider nontrivial arguments
_sanityCheck(header.payload & Header.computedHasArgumentsFlag == 0,
"arguments not implemented")
return
}
}
func clone(into buffer: inout UnsafeMutableRawBufferPointer,
endOfReferencePrefix: Bool) {
var newHeader = header
newHeader.endOfReferencePrefix = endOfReferencePrefix
var componentSize = MemoryLayout<Header>.size
buffer.storeBytes(of: newHeader, as: Header.self)
switch header.kind {
case .struct,
.class:
if header.payload == Header.outOfLineOffsetPayload {
let overflowOffset = body.load(as: UInt32.self)
buffer.storeBytes(of: overflowOffset, toByteOffset: 4,
as: UInt32.self)
componentSize += 4
}
case .optionalChain,
.optionalForce,
.optionalWrap:
break
case .computed:
// Fields are pointer-aligned after the header
componentSize += Header.pointerAlignmentSkew
// TODO: nontrivial arguments need to be copied by value witness
_sanityCheck(header.payload & Header.computedHasArgumentsFlag == 0,
"arguments not implemented")
buffer.storeBytes(of: _computedIDValue,
toByteOffset: MemoryLayout<Int>.size,
as: Int.self)
buffer.storeBytes(of: _computedGetter,
toByteOffset: 2 * MemoryLayout<Int>.size,
as: UnsafeRawPointer.self)
componentSize += MemoryLayout<Int>.size * 2
if header.payload & Header.computedSettableFlag != 0 {
buffer.storeBytes(of: _computedSetter,
toByteOffset: MemoryLayout<Int>.size * 3,
as: UnsafeRawPointer.self)
componentSize += MemoryLayout<Int>.size
}
}
buffer = UnsafeMutableRawBufferPointer(
start: buffer.baseAddress.unsafelyUnwrapped + componentSize,
count: buffer.count - componentSize)
}
func projectReadOnly<CurValue, NewValue>(_ base: CurValue) -> NewValue {
switch value {
case .struct(let offset):
var base2 = base
return withUnsafeBytes(of: &base2) {
let p = $0.baseAddress.unsafelyUnwrapped.advanced(by: offset)
// The contents of the struct should be well-typed, so we can assume
// typed memory here.
return p.assumingMemoryBound(to: NewValue.self).pointee
}
case .class(let offset):
_sanityCheck(CurValue.self is AnyObject.Type,
"base is not a class")
let baseObj = unsafeBitCast(base, to: AnyObject.self)
let basePtr = UnsafeRawPointer(Builtin.bridgeToRawPointer(baseObj))
defer { _fixLifetime(baseObj) }
return basePtr.advanced(by: offset)
.assumingMemoryBound(to: NewValue.self)
.pointee
case .get(id: _, get: let rawGet, argument: let argument),
.mutatingGetSet(id: _, get: let rawGet, set: _, argument: let argument),
.nonmutatingGetSet(id: _, get: let rawGet, set: _, argument: let argument):
typealias Getter
= @convention(thin) (CurValue, UnsafeRawPointer) -> NewValue
let get = unsafeBitCast(rawGet, to: Getter.self)
return get(base, argument)
case .optionalChain:
fatalError("TODO")
case .optionalForce:
fatalError("TODO")
case .optionalWrap:
fatalError("TODO")
}
}
func projectMutableAddress<CurValue, NewValue>(
_ base: UnsafeRawPointer,
from _: CurValue.Type,
to _: NewValue.Type,
isRoot: Bool,
keepAlive: inout [AnyObject]
) -> UnsafeRawPointer {
switch value {
case .struct(let offset):
return base.advanced(by: offset)
case .class(let offset):
// A class dereference should only occur at the root of a mutation,
// since otherwise it would be part of the reference prefix.
_sanityCheck(isRoot,
"class component should not appear in the middle of mutation")
// AnyObject memory can alias any class reference memory, so we can
// assume type here
let object = base.assumingMemoryBound(to: AnyObject.self).pointee
// The base ought to be kept alive for the duration of the derived access
keepAlive.append(object)
return UnsafeRawPointer(Builtin.bridgeToRawPointer(object))
.advanced(by: offset)
case .mutatingGetSet(id: _, get: let rawGet, set: let rawSet,
argument: let argument):
typealias Getter
= @convention(thin) (CurValue, UnsafeRawPointer) -> NewValue
typealias Setter
= @convention(thin) (NewValue, inout CurValue, UnsafeRawPointer) -> ()
let get = unsafeBitCast(rawGet, to: Getter.self)
let set = unsafeBitCast(rawSet, to: Setter.self)
let baseTyped = UnsafeMutablePointer(
mutating: base.assumingMemoryBound(to: CurValue.self))
let writeback = MutatingWritebackBuffer(base: baseTyped,
set: set,
argument: argument,
value: get(baseTyped.pointee, argument))
keepAlive.append(writeback)
// A maximally-abstracted, final, stored class property should have
// a stable address.
return UnsafeRawPointer(Builtin.addressof(&writeback.value))
case .nonmutatingGetSet(id: _, get: let rawGet, set: let rawSet,
argument: let argument):
// A nonmutating property should only occur at the root of a mutation,
// since otherwise it would be part of the reference prefix.
_sanityCheck(isRoot,
"nonmutating component should not appear in the middle of mutation")
typealias Getter
= @convention(thin) (CurValue, UnsafeRawPointer) -> NewValue
typealias Setter
= @convention(thin) (NewValue, CurValue, UnsafeRawPointer) -> ()
let get = unsafeBitCast(rawGet, to: Getter.self)
let set = unsafeBitCast(rawSet, to: Setter.self)
let baseValue = base.assumingMemoryBound(to: CurValue.self).pointee
let writeback = NonmutatingWritebackBuffer(base: baseValue,
set: set,
argument: argument,
value: get(baseValue, argument))
keepAlive.append(writeback)
// A maximally-abstracted, final, stored class property should have
// a stable address.
return UnsafeRawPointer(Builtin.addressof(&writeback.value))
case .optionalForce:
fatalError("TODO")
case .optionalChain, .optionalWrap, .get:
_sanityCheckFailure("not a mutable key path component")
}
}
}
internal struct KeyPathBuffer {
var data: UnsafeRawBufferPointer
var trivial: Bool
var hasReferencePrefix: Bool
var mutableData: UnsafeMutableRawBufferPointer {
return UnsafeMutableRawBufferPointer(mutating: data)
}
struct Header {
var _value: UInt32
static var sizeMask: UInt32 {
return _SwiftKeyPathBufferHeader_SizeMask
}
static var reservedMask: UInt32 {
return _SwiftKeyPathBufferHeader_ReservedMask
}
static var trivialFlag: UInt32 {
return _SwiftKeyPathBufferHeader_TrivialFlag
}
static var hasReferencePrefixFlag: UInt32 {
return _SwiftKeyPathBufferHeader_HasReferencePrefixFlag
}
init(size: Int, trivial: Bool, hasReferencePrefix: Bool) {
_sanityCheck(size <= Int(Header.sizeMask), "key path too big")
_value = UInt32(size)
| (trivial ? Header.trivialFlag : 0)
| (hasReferencePrefix ? Header.hasReferencePrefixFlag : 0)
}
var size: Int { return Int(_value & Header.sizeMask) }
var trivial: Bool { return _value & Header.trivialFlag != 0 }
var hasReferencePrefix: Bool {
get {
return _value & Header.hasReferencePrefixFlag != 0
}
set {
if newValue {
_value |= Header.hasReferencePrefixFlag
} else {
_value &= ~Header.hasReferencePrefixFlag
}
}
}
// In a key path pattern, the "trivial" flag is used to indicate
// "instantiable in-line"
var instantiableInLine: Bool {
return trivial
}
func validateReservedBits() {
_precondition(_value & Header.reservedMask == 0,
"reserved bits set to an unexpected bit pattern")
}
}
init(base: UnsafeRawPointer) {
let header = base.load(as: Header.self)
data = UnsafeRawBufferPointer(
start: base + MemoryLayout<Int>.size,
count: header.size)
trivial = header.trivial
hasReferencePrefix = header.hasReferencePrefix
}
func destroy() {
if trivial { return }
fatalError("TODO")
}
mutating func next() -> (RawKeyPathComponent, Any.Type?) {
let header = pop(RawKeyPathComponent.Header.self)
// Track if this is the last component of the reference prefix.
if header.endOfReferencePrefix {
_sanityCheck(self.hasReferencePrefix,
"beginMutation marker in non-reference-writable key path?")
self.hasReferencePrefix = false
}
let body: UnsafeRawBufferPointer
let size = header.bodySize
if size != 0 {
body = popRaw(size: size, alignment: 4)
} else {
body = UnsafeRawBufferPointer(start: nil, count: 0)
}
let component = RawKeyPathComponent(header: header, body: body)
// fetch type, which is in the buffer unless it's the final component
let nextType: Any.Type?
if data.count == 0 {
nextType = nil
} else {
nextType = pop(Any.Type.self)
}
return (component, nextType)
}
mutating func pop<T>(_ type: T.Type) -> T {
_sanityCheck(_isPOD(T.self), "should be POD")
let raw = popRaw(size: MemoryLayout<T>.size,
alignment: MemoryLayout<T>.alignment)
let resultBuf = UnsafeMutablePointer<T>.allocate(capacity: 1)
_memcpy(dest: resultBuf,
src: UnsafeMutableRawPointer(mutating: raw.baseAddress.unsafelyUnwrapped),
size: UInt(MemoryLayout<T>.size))
let result = resultBuf.pointee
resultBuf.deallocate(capacity: 1)
return result
}
mutating func popRaw(size: Int, alignment: Int) -> UnsafeRawBufferPointer {
var baseAddress = data.baseAddress.unsafelyUnwrapped
var misalignment = Int(bitPattern: baseAddress) % alignment
if misalignment != 0 {
misalignment = alignment - misalignment
baseAddress += misalignment
}
let result = UnsafeRawBufferPointer(start: baseAddress, count: size)
data = UnsafeRawBufferPointer(
start: baseAddress + size,
count: data.count - size - misalignment
)
return result
}
}
// MARK: Library intrinsics for projecting key paths.
@_inlineable
public // COMPILER_INTRINSIC
func _projectKeyPathPartial<Root>(
root: Root,
keyPath: PartialKeyPath<Root>
) -> Any {
func open<Value>(_: Value.Type) -> Any {
return _projectKeyPathReadOnly(root: root,
keyPath: unsafeDowncast(keyPath, to: KeyPath<Root, Value>.self))
}
return _openExistential(type(of: keyPath).valueType, do: open)
}
@_inlineable
public // COMPILER_INTRINSIC
func _projectKeyPathAny<RootValue>(
root: RootValue,
keyPath: AnyKeyPath
) -> Any? {
let (keyPathRoot, keyPathValue) = type(of: keyPath)._rootAndValueType
func openRoot<KeyPathRoot>(_: KeyPathRoot.Type) -> Any? {
guard let rootForKeyPath = root as? KeyPathRoot else {
return nil
}
func openValue<Value>(_: Value.Type) -> Any {
return _projectKeyPathReadOnly(root: rootForKeyPath,
keyPath: unsafeDowncast(keyPath, to: KeyPath<KeyPathRoot, Value>.self))
}
return _openExistential(keyPathValue, do: openValue)
}
return _openExistential(keyPathRoot, do: openRoot)
}
public // COMPILER_INTRINSIC
func _projectKeyPathReadOnly<Root, Value>(
root: Root,
keyPath: KeyPath<Root, Value>
) -> Value {
return keyPath.projectReadOnly(from: root)
}
public // COMPILER_INTRINSIC
func _projectKeyPathWritable<Root, Value>(
root: UnsafeMutablePointer<Root>,
keyPath: WritableKeyPath<Root, Value>
) -> (UnsafeMutablePointer<Value>, Builtin.NativeObject) {
return keyPath.projectMutableAddress(from: root)
}
public // COMPILER_INTRINSIC
func _projectKeyPathReferenceWritable<Root, Value>(
root: Root,
keyPath: ReferenceWritableKeyPath<Root, Value>
) -> (UnsafeMutablePointer<Value>, Builtin.NativeObject) {
return keyPath.projectMutableAddress(from: root)
}
// MARK: Appending type system
// FIXME(ABI): The type relationships between KeyPath append operands are tricky
// and don't interact well with our overriding rules. Hack things by injecting
// a bunch of `appending` overloads as protocol extensions so they aren't
// constrained by being overrides, and so that we can use exact-type constraints
// on `Self` to prevent dynamically-typed methods from being inherited by
// statically-typed key paths.
public protocol _AppendKeyPath {}
extension _AppendKeyPath where Self == AnyKeyPath {
public func appending(path: AnyKeyPath) -> AnyKeyPath? {
return _tryToAppendKeyPaths(root: self, leaf: path)
}
}
extension _AppendKeyPath /* where Self == PartialKeyPath<T> */ {
public func appending<Root>(path: AnyKeyPath) -> PartialKeyPath<Root>?
where Self == PartialKeyPath<Root> {
return _tryToAppendKeyPaths(root: self, leaf: path)
}
public func appending<Root, AppendedRoot, AppendedValue>(
path: KeyPath<AppendedRoot, AppendedValue>
) -> KeyPath<Root, AppendedValue>?
where Self == PartialKeyPath<Root> {
return _tryToAppendKeyPaths(root: self, leaf: path)
}
public func appending<Root, AppendedRoot, AppendedValue>(
path: ReferenceWritableKeyPath<AppendedRoot, AppendedValue>
) -> ReferenceWritableKeyPath<Root, AppendedValue>?
where Self == PartialKeyPath<Root> {
return _tryToAppendKeyPaths(root: self, leaf: path)
}
}
extension _AppendKeyPath /* where Self == KeyPath<T,U> */ {
public func appending<Root, Value, AppendedValue>(
path: KeyPath<Value, AppendedValue>
) -> KeyPath<Root, AppendedValue>
where Self: KeyPath<Root, Value> {
return _appendingKeyPaths(root: self, leaf: path)
}
/* TODO
public func appending<Root, Value, Leaf>(
path: Leaf,
// FIXME: Satisfy "Value generic param not used in signature" constraint
_: Value.Type = Value.self
) -> PartialKeyPath<Root>?
where Self: KeyPath<Root, Value>, Leaf == AnyKeyPath {
return _tryToAppendKeyPaths(root: self, leaf: path)
}
*/
public func appending<Root, Value, AppendedValue>(
path: ReferenceWritableKeyPath<Value, AppendedValue>
) -> ReferenceWritableKeyPath<Root, AppendedValue>
where Self == KeyPath<Root, Value> {
return _appendingKeyPaths(root: self, leaf: path)
}
}
extension _AppendKeyPath /* where Self == WritableKeyPath<T,U> */ {
public func appending<Root, Value, AppendedValue>(
path: WritableKeyPath<Value, AppendedValue>
) -> WritableKeyPath<Root, AppendedValue>
where Self == WritableKeyPath<Root, Value> {
return _appendingKeyPaths(root: self, leaf: path)
}
public func appending<Root, Value, AppendedValue>(
path: ReferenceWritableKeyPath<Value, AppendedValue>
) -> ReferenceWritableKeyPath<Root, AppendedValue>
where Self == WritableKeyPath<Root, Value> {
return _appendingKeyPaths(root: self, leaf: path)
}
}
extension _AppendKeyPath /* where Self == ReferenceWritableKeyPath<T,U> */ {
public func appending<Root, Value, AppendedValue>(
path: WritableKeyPath<Value, AppendedValue>
) -> ReferenceWritableKeyPath<Root, AppendedValue>
where Self == ReferenceWritableKeyPath<Root, Value> {
return _appendingKeyPaths(root: self, leaf: path)
}
}
// internal-with-availability
public func _tryToAppendKeyPaths<Result: AnyKeyPath>(
root: AnyKeyPath,
leaf: AnyKeyPath
) -> Result? {
let (rootRoot, rootValue) = type(of: root)._rootAndValueType
let (leafRoot, leafValue) = type(of: leaf)._rootAndValueType
if rootValue != leafRoot {
return nil
}
func open<Root>(_: Root.Type) -> Result {
func open2<Value>(_: Value.Type) -> Result {
func open3<AppendedValue>(_: AppendedValue.Type) -> Result {
let typedRoot = unsafeDowncast(root, to: KeyPath<Root, Value>.self)
let typedLeaf = unsafeDowncast(leaf,
to: KeyPath<Value, AppendedValue>.self)
let result = _appendingKeyPaths(root: typedRoot, leaf: typedLeaf)
return unsafeDowncast(result, to: Result.self)
}
return _openExistential(leafValue, do: open3)
}
return _openExistential(rootValue, do: open2)
}
return _openExistential(rootRoot, do: open)
}
// internal-with-availability
public func _appendingKeyPaths<
Root, Value, AppendedValue,
Result: KeyPath<Root, AppendedValue>
>(
root: KeyPath<Root, Value>,
leaf: KeyPath<Value, AppendedValue>
) -> Result {
let resultTy = type(of: root).appendedType(with: type(of: leaf))
return root.withBuffer {
var rootBuffer = $0
return leaf.withBuffer {
var leafBuffer = $0
// Reserve room for the appended KVC string, if both key paths are
// KVC-compatible.
let appendedKVCLength: Int, rootKVCLength: Int, leafKVCLength: Int
if let rootPtr = root._kvcKeyPathStringPtr,
let leafPtr = leaf._kvcKeyPathStringPtr {
rootKVCLength = Int(_swift_stdlib_strlen(rootPtr))
leafKVCLength = Int(_swift_stdlib_strlen(leafPtr))
// root + "." + leaf
appendedKVCLength = rootKVCLength + 1 + leafKVCLength
} else {
rootKVCLength = 0
leafKVCLength = 0
appendedKVCLength = 0
}
// Result buffer has room for both key paths' components, plus the
// header, plus space for the middle type.
// Align up the root so that we can put the component type after it.
let alignMask = MemoryLayout<Int>.alignment - 1
let rootSize = (rootBuffer.data.count + alignMask) & ~alignMask
let resultSize = rootSize + leafBuffer.data.count
+ 2 * MemoryLayout<Int>.size
// Tail-allocate space for the KVC string.
let totalResultSize = (resultSize + appendedKVCLength + 3) & ~3
var kvcStringBuffer: UnsafeMutableRawPointer? = nil
let result = resultTy._create(capacityInBytes: totalResultSize) {
var destBuffer = $0
// Remember where the tail-allocated KVC string buffer begins.
if appendedKVCLength > 0 {
kvcStringBuffer = destBuffer.baseAddress.unsafelyUnwrapped
.advanced(by: resultSize)
destBuffer = .init(start: destBuffer.baseAddress,
count: resultSize)
}
func pushRaw(size: Int, alignment: Int)
-> UnsafeMutableRawBufferPointer {
var baseAddress = destBuffer.baseAddress.unsafelyUnwrapped
var misalign = Int(bitPattern: baseAddress) % alignment
if misalign != 0 {
misalign = alignment - misalign
baseAddress = baseAddress.advanced(by: misalign)
}
let result = UnsafeMutableRawBufferPointer(
start: baseAddress,
count: size)
destBuffer = UnsafeMutableRawBufferPointer(
start: baseAddress + size,
count: destBuffer.count - size - misalign)
return result
}
func push<T>(_ value: T) {
let buf = pushRaw(size: MemoryLayout<T>.size,
alignment: MemoryLayout<T>.alignment)
buf.storeBytes(of: value, as: T.self)
}
// Save space for the header.
let leafIsReferenceWritable = type(of: leaf).kind == .reference
let header = KeyPathBuffer.Header(
size: resultSize - MemoryLayout<Int>.size,
trivial: rootBuffer.trivial && leafBuffer.trivial,
hasReferencePrefix: rootBuffer.hasReferencePrefix
|| leafIsReferenceWritable
)
push(header)
// Start the components at pointer alignment
_ = pushRaw(size: RawKeyPathComponent.Header.pointerAlignmentSkew,
alignment: 4)
let leafHasReferencePrefix = leafBuffer.hasReferencePrefix
// Clone the root components into the buffer.
while true {
let (component, type) = rootBuffer.next()
let isLast = type == nil
// If the leaf appended path has a reference prefix, then the
// entire root is part of the reference prefix.
let endOfReferencePrefix: Bool
if leafHasReferencePrefix {
endOfReferencePrefix = false
} else if isLast && leafIsReferenceWritable {
endOfReferencePrefix = true
} else {
endOfReferencePrefix = component.header.endOfReferencePrefix
}
component.clone(
into: &destBuffer,
endOfReferencePrefix: endOfReferencePrefix)
if let type = type {
push(type)
} else {
// Insert our endpoint type between the root and leaf components.
push(Value.self as Any.Type)
break
}
}
// Clone the leaf components into the buffer.
while true {
let (component, type) = leafBuffer.next()
component.clone(
into: &destBuffer,
endOfReferencePrefix: component.header.endOfReferencePrefix)
if let type = type {
push(type)
} else {
break
}
}
_sanityCheck(destBuffer.count == 0,
"did not fill entire result buffer")
}
// Build the KVC string if there is one.
if let kvcStringBuffer = kvcStringBuffer {
let rootPtr = root._kvcKeyPathStringPtr.unsafelyUnwrapped
let leafPtr = leaf._kvcKeyPathStringPtr.unsafelyUnwrapped
_memcpy(dest: kvcStringBuffer,
src: UnsafeMutableRawPointer(mutating: rootPtr),
size: UInt(rootKVCLength))
kvcStringBuffer.advanced(by: rootKVCLength)
.storeBytes(of: 0x2E /* '.' */, as: CChar.self)
_memcpy(dest: kvcStringBuffer.advanced(by: rootKVCLength + 1),
src: UnsafeMutableRawPointer(mutating: leafPtr),
size: UInt(leafKVCLength))
result._kvcKeyPathStringPtr =
UnsafePointer(kvcStringBuffer.assumingMemoryBound(to: CChar.self))
kvcStringBuffer.advanced(by: rootKVCLength + leafKVCLength + 1)
.storeBytes(of: 0 /* '\0' */, as: CChar.self)
}
return unsafeDowncast(result, to: Result.self)
}
}
}
// The distance in bytes from the address point of a KeyPath object to its
// buffer header. Includes the size of the Swift heap object header and the
// pointer to the KVC string.
internal var keyPathObjectHeaderSize: Int {
return MemoryLayout<HeapObject>.size + MemoryLayout<Int>.size
}
// Runtime entry point to instantiate a key path object.
@_cdecl("swift_getKeyPath")
public func _swift_getKeyPath(pattern: UnsafeMutableRawPointer,
arguments: UnsafeRawPointer)
-> UnsafeRawPointer {
// The key path pattern is laid out like a key path object, with a few
// modifications:
// - Instead of the two-word object header with isa and refcount, two
// pointers to metadata accessors are provided for the root and leaf
// value types of the key path.
// - The header reuses the "trivial" bit to mean "instantiable in-line",
// meaning that the key path described by this pattern has no contextually
// dependent parts (no dependence on generic parameters, subscript indexes,
// etc.), so it can be set up as a global object once. (The resulting
// global object will itself always have the "trivial" bit set, since it
// never needs to be destroyed.)
// - Components may have unresolved forms that require instantiation.
// - Type metadata pointers are unresolved, and instead
// point to accessor functions that instantiate the metadata.
//
// The pattern never precomputes the capabilities of the key path (readonly/
// writable/reference-writable), nor does it encode the reference prefix.
// These are resolved dynamically, so that they always reflect the dynamic
// capability of the properties involved.
let oncePtr = pattern
let patternPtr = pattern.advanced(by: MemoryLayout<Int>.size)
let bufferPtr = patternPtr.advanced(by: keyPathObjectHeaderSize)
// If the pattern is instantiable in-line, do a dispatch_once to
// initialize it. (The resulting object will still have the collocated
// "trivial" bit set, since a global object never needs destruction.)
let bufferHeader = bufferPtr.load(as: KeyPathBuffer.Header.self)
bufferHeader.validateReservedBits()
if bufferHeader.instantiableInLine {
Builtin.onceWithContext(oncePtr._rawValue, _getKeyPath_instantiateInline,
patternPtr._rawValue)
// Return the instantiated object at +1.
// TODO: This will be unnecessary once we support global objects with inert
// refcounting.
let object = Unmanaged<AnyKeyPath>.fromOpaque(patternPtr)
_ = object.retain()
return UnsafeRawPointer(patternPtr)
}
// Otherwise, instantiate a new key path object modeled on the pattern.
return _getKeyPath_instantiatedOutOfLine(patternPtr, arguments)
}
internal func _getKeyPath_instantiatedOutOfLine(
_ pattern: UnsafeRawPointer,
_ arguments: UnsafeRawPointer)
-> UnsafeRawPointer {
// Do a pass to determine the class of the key path we'll be instantiating
// and how much space we'll need for it.
let (keyPathClass, rootType, size)
= _getKeyPathClassAndInstanceSize(pattern, arguments)
// Allocate the instance.
let instance = keyPathClass._create(capacityInBytes: size) { instanceData in
// Instantiate the pattern into the instance.
let patternBufferPtr = pattern.advanced(by: keyPathObjectHeaderSize)
let patternBuffer = KeyPathBuffer(base: patternBufferPtr)
_instantiateKeyPathBuffer(patternBuffer, instanceData, rootType, arguments)
}
// Take the KVC string from the pattern.
let kvcStringPtr = pattern.advanced(by: MemoryLayout<HeapObject>.size)
instance._kvcKeyPathStringPtr = kvcStringPtr
.load(as: Optional<UnsafePointer<CChar>>.self)
// Hand it off at +1.
return UnsafeRawPointer(Unmanaged.passRetained(instance).toOpaque())
}
internal func _getKeyPath_instantiateInline(
_ objectRawPtr: Builtin.RawPointer
) {
let objectPtr = UnsafeMutableRawPointer(objectRawPtr)
// Do a pass to determine the class of the key path we'll be instantiating
// and how much space we'll need for it.
// The pattern argument doesn't matter since an in-place pattern should never
// have arguments.
let (keyPathClass, rootType, instantiatedSize)
= _getKeyPathClassAndInstanceSize(objectPtr, objectPtr)
// TODO: Eventually, we'll need to handle cases where the instantiated
// key path has a different size from the pattern (because it involves
// resilient types, for example). For now, require that the size match the
// buffer.
let bufferPtr = objectPtr.advanced(by: keyPathObjectHeaderSize)
let buffer = KeyPathBuffer(base: bufferPtr)
let totalSize = buffer.data.count + MemoryLayout<Int>.size
let bufferData = UnsafeMutableRawBufferPointer(
start: bufferPtr,
count: totalSize)
_sanityCheck(instantiatedSize == totalSize,
"size-changing in-place instantiation not implemented")
// Instantiate the pattern in place.
_instantiateKeyPathBuffer(buffer, bufferData, rootType, bufferPtr)
_swift_instantiateInertHeapObject(objectPtr,
unsafeBitCast(keyPathClass, to: OpaquePointer.self))
}
internal typealias MetadataAccessor =
@convention(c) (UnsafeRawPointer) -> UnsafeRawPointer
internal func _getKeyPathClassAndInstanceSize(
_ pattern: UnsafeRawPointer,
_ arguments: UnsafeRawPointer
) -> (
keyPathClass: AnyKeyPath.Type,
rootType: Any.Type,
size: Int
) {
// Resolve the root and leaf types.
let rootAccessor = pattern.load(as: MetadataAccessor.self)
let leafAccessor = pattern.load(fromByteOffset: MemoryLayout<Int>.size,
as: MetadataAccessor.self)
let root = unsafeBitCast(rootAccessor(arguments), to: Any.Type.self)
let leaf = unsafeBitCast(leafAccessor(arguments), to: Any.Type.self)
// Scan the pattern to figure out the dynamic capability of the key path.
// Start off assuming the key path is writable.
var capability: KeyPathKind = .value
let bufferPtr = pattern.advanced(by: keyPathObjectHeaderSize)
var buffer = KeyPathBuffer(base: bufferPtr)
let size = buffer.data.count + MemoryLayout<Int>.size
scanComponents: while true {
let header = buffer.pop(RawKeyPathComponent.Header.self)
func popOffset() {
if header.payload == RawKeyPathComponent.Header.unresolvedFieldOffsetPayload
|| header.payload == RawKeyPathComponent.Header.outOfLineOffsetPayload {
_ = buffer.pop(UInt32.self)
}
if header.payload == RawKeyPathComponent.Header.unresolvedIndirectOffsetPayload {
_ = buffer.pop(Int.self)
}
}
switch header.kind {
case .struct:
// No effect on the capability.
// TODO: we should dynamically prevent "let" properties from being
// reassigned.
popOffset()
case .class:
// The rest of the key path could be reference-writable.
// TODO: we should dynamically prevent "let" properties from being
// reassigned.
capability = .reference
popOffset()
case .computed:
let settable =
header.payload & RawKeyPathComponent.Header.computedSettableFlag != 0
let mutating =
header.payload & RawKeyPathComponent.Header.computedMutatingFlag != 0
switch (settable, mutating) {
case (false, false):
// If the property is get-only, the capability becomes read-only, unless
// we get another reference-writable component.
capability = .readOnly
case (true, false):
capability = .reference
case (true, true):
// Writable if the base is. No effect.
break
case (false, true):
_sanityCheckFailure("unpossible")
}
_sanityCheck(
header.payload & RawKeyPathComponent.Header.computedHasArgumentsFlag == 0,
"arguments not implemented yet")
_ = buffer.popRaw(size: MemoryLayout<Int>.size * (settable ? 3 : 2),
alignment: MemoryLayout<Int>.alignment)
case .optionalChain,
.optionalWrap:
// Chaining always renders the whole key path read-only.
capability = .readOnly
break scanComponents
case .optionalForce:
// No effect.
break
}
// Break if this is the last component.
if buffer.data.count == 0 { break }
// Pop the type accessor reference.
_ = buffer.popRaw(size: MemoryLayout<Int>.size,
alignment: MemoryLayout<Int>.alignment)
}
// Grab the class object for the key path type we'll end up with.
func openRoot<Root>(_: Root.Type) -> AnyKeyPath.Type {
func openLeaf<Leaf>(_: Leaf.Type) -> AnyKeyPath.Type {
switch capability {
case .readOnly:
return KeyPath<Root, Leaf>.self
case .value:
return WritableKeyPath<Root, Leaf>.self
case .reference:
return ReferenceWritableKeyPath<Root, Leaf>.self
}
}
return _openExistential(leaf, do: openLeaf)
}
let classTy = _openExistential(root, do: openRoot)
return (keyPathClass: classTy, rootType: root, size: size)
}
internal func _instantiateKeyPathBuffer(
_ origPatternBuffer: KeyPathBuffer,
_ origDestData: UnsafeMutableRawBufferPointer,
_ rootType: Any.Type,
_ arguments: UnsafeRawPointer
) {
// NB: patternBuffer and destData alias when the pattern is instantiable
// in-line. Therefore, do not read from patternBuffer after the same position
// in destData has been written to.
var patternBuffer = origPatternBuffer
let destHeaderPtr = origDestData.baseAddress.unsafelyUnwrapped
var destData = UnsafeMutableRawBufferPointer(
start: destHeaderPtr.advanced(by: MemoryLayout<Int>.size),
count: origDestData.count - MemoryLayout<Int>.size)
func pushDest<T>(_ value: T) {
_sanityCheck(_isPOD(T.self))
var value2 = value
let size = MemoryLayout<T>.size
let alignment = MemoryLayout<T>.alignment
var baseAddress = destData.baseAddress.unsafelyUnwrapped
var misalign = Int(bitPattern: baseAddress) % alignment
if misalign != 0 {
misalign = alignment - misalign
baseAddress = baseAddress.advanced(by: misalign)
}
_memcpy(dest: baseAddress, src: &value2,
size: UInt(size))
destData = UnsafeMutableRawBufferPointer(
start: baseAddress.advanced(by: size),
count: destData.count - size - misalign)
}
// Track where the reference prefix begins.
var endOfReferencePrefixComponent: UnsafeMutableRawPointer? = nil
var previousComponentAddr: UnsafeMutableRawPointer? = nil
// Instantiate components that need it.
var base: Any.Type = rootType
// Some pattern forms are pessimistically larger than what we need in the
// instantiated key path. Keep track of this.
var shrinkage = 0
while true {
let componentAddr = destData.baseAddress.unsafelyUnwrapped
let header = patternBuffer.pop(RawKeyPathComponent.Header.self)
func tryToResolveOffset() {
if header.payload == RawKeyPathComponent.Header.unresolvedFieldOffsetPayload {
// Look up offset in type metadata. The value in the pattern is the
// offset within the metadata object.
let metadataPtr = unsafeBitCast(base, to: UnsafeRawPointer.self)
let offsetOfOffset = patternBuffer.pop(UInt32.self)
let offset = metadataPtr.load(fromByteOffset: Int(offsetOfOffset),
as: UInt32.self)
// Rewrite the header for a resolved offset.
var newHeader = header
newHeader.payload = RawKeyPathComponent.Header.outOfLineOffsetPayload
pushDest(newHeader)
pushDest(offset)
return
}
if header.payload == RawKeyPathComponent.Header.unresolvedIndirectOffsetPayload {
// Look up offset in the indirectly-referenced variable we have a
// pointer.
let offsetVar = patternBuffer.pop(UnsafeRawPointer.self)
let offsetValue = UInt32(offsetVar.load(as: UInt.self))
// Rewrite the header for a resolved offset.
var newHeader = header
newHeader.payload = RawKeyPathComponent.Header.outOfLineOffsetPayload
pushDest(newHeader)
pushDest(offsetValue)
// On 64-bit systems the pointer to the ivar offset variable is
// pointer-sized and -aligned, but the resulting offset ought to be
// 32 bits only, so we can shrink the result object a bit.
if MemoryLayout<Int>.size == 8 {
shrinkage += MemoryLayout<UnsafeRawPointer>.size
}
return
}
// Otherwise, just transfer the pre-resolved component.
pushDest(header)
if header.payload == RawKeyPathComponent.Header.outOfLineOffsetPayload {
let offset = patternBuffer.pop(UInt32.self)
pushDest(offset)
}
}
switch header.kind {
case .struct:
// The offset may need to be resolved dynamically.
tryToResolveOffset()
case .class:
// Crossing a class can end the reference prefix, and makes the following
// key path potentially reference-writable.
endOfReferencePrefixComponent = previousComponentAddr
// The offset may need to be resolved dynamically.
tryToResolveOffset()
case .optionalChain,
.optionalWrap,
.optionalForce:
// No instantiation necessary.
pushDest(header)
break
case .computed:
// A nonmutating settable property can end the reference prefix and
// makes the following key path potentially reference-writable.
if header.payload & RawKeyPathComponent.Header.computedSettableFlag != 0
&& header.payload & RawKeyPathComponent.Header.computedMutatingFlag == 0 {
endOfReferencePrefixComponent = previousComponentAddr
}
// The offset may need resolution if the property is keyed by a stored
// property.
var newHeader = header
var id = patternBuffer.pop(Int.self)
switch header.payload
& RawKeyPathComponent.Header.computedIDResolutionMask {
case RawKeyPathComponent.Header.computedIDResolved:
// Nothing to do.
break
case RawKeyPathComponent.Header.computedIDUnresolvedIndirectPointer:
// The value in the pattern is a pointer to the actual unique word-sized
// value in memory.
let idPtr = UnsafeRawPointer(bitPattern: id).unsafelyUnwrapped
id = idPtr.load(as: Int.self)
default:
_sanityCheckFailure("unpossible")
}
newHeader.payload &= ~RawKeyPathComponent.Header.computedIDResolutionMask
pushDest(newHeader)
pushDest(id)
// Carry over the accessors.
let getter = patternBuffer.pop(UnsafeRawPointer.self)
pushDest(getter)
if header.payload & RawKeyPathComponent.Header.computedSettableFlag != 0{
let setter = patternBuffer.pop(UnsafeRawPointer.self)
pushDest(setter)
}
// Carry over the arguments.
_sanityCheck(header.payload
& RawKeyPathComponent.Header.computedHasArgumentsFlag == 0,
"arguments not implemented")
}
// Break if this is the last component.
if patternBuffer.data.count == 0 { break }
// Resolve the component type.
let componentTyAccessor = patternBuffer.pop(MetadataAccessor.self)
base = unsafeBitCast(componentTyAccessor(arguments), to: Any.Type.self)
pushDest(base)
previousComponentAddr = componentAddr
}
// We should have traversed both buffers.
_sanityCheck(patternBuffer.data.isEmpty && destData.count == shrinkage)
// Write out the header.
let destHeader = KeyPathBuffer.Header(
size: origPatternBuffer.data.count - shrinkage,
trivial: true, // TODO: nontrivial indexes
hasReferencePrefix: endOfReferencePrefixComponent != nil)
destHeaderPtr.storeBytes(of: destHeader, as: KeyPathBuffer.Header.self)
// Mark the reference prefix if there is one.
if let endOfReferencePrefixComponent = endOfReferencePrefixComponent {
var componentHeader = endOfReferencePrefixComponent
.load(as: RawKeyPathComponent.Header.self)
componentHeader.endOfReferencePrefix = true
endOfReferencePrefixComponent.storeBytes(of: componentHeader,
as: RawKeyPathComponent.Header.self)
}
}
| apache-2.0 | 52ed35f7002ed6e82bb25e293a0342d9 | 34.435281 | 91 | 0.652847 | 4.827171 | false | false | false | false |
wrengels/Amplify4 | Amplify4/Amplify4/MapItem.swift | 1 | 1532 | //
// MapItem.swift
// Amplify4
//
// Created by Bill Engels on 3/13/15.
// Copyright (c) 2015 Bill Engels. All rights reserved.
//
import Cocoa
class MapItem: NSObject {
var isLit = 0
var isClickable = false
var coItems = [MapItem]()
var rec = NSRect()
var litBez = NSBezierPath()
var highlightPoint = NSPoint()
let highlightLineWidth : CGFloat = 4 // width of highlight line
let highlightStrokeColor = NSColor(red: 36/255, green: 204/255, blue: 217/255, alpha: 1)
let highlightScale : CGFloat = 1.3
func doLitBez (b : NSBezierPath) {
self.litBez = b
var move = NSAffineTransform()
move.translateXBy(highlightPoint.x, yBy: highlightPoint.y)
move.scaleBy(highlightScale)
self.litBez.transformUsingAffineTransform(move)
litBez.lineWidth = highlightLineWidth
}
func report() -> NSAttributedString {
// overridden by match or frag
return NSAttributedString()
}
func info() -> NSAttributedString {
// overridden by match and frag
return NSAttributedString()
}
func lightCoItems() {
self.isLit++
self.isClickable = true
for item in coItems {
item.isLit++
}
}
func unlightCoItems() {
self.isLit--
self.isClickable = false
for item in coItems {
item.isLit--
}
}
func plotHighlight() {
highlightStrokeColor.set()
litBez.stroke()
}
}
| gpl-2.0 | 8f01335e5d682d90d2b4d4ff22e82617 | 23.709677 | 92 | 0.5953 | 4.267409 | false | false | false | false |
markcerqueira/hello-chuckpad | hello-chuckpad/View Controllers/LiveViewController.swift | 1 | 2013 | //
// LiveViewController.swift
// hello-chuckpad
//
// Created by Mark Cerqueira on 1/6/18.
//
import UIKit
final class LiveViewController: UIViewController, ChuckPadLiveDelegate {
@IBOutlet private var sessionGUIDLabel: UILabel!
@IBOutlet private var connectToSessionButton: UIButton!
@IBOutlet private var publishMessageButton: UIButton!
private var liveSession: LiveSession?
private var chuckPadLive: ChuckPadLive = ChuckPadLive.sharedInstance()
// MARK: - View Controller
override func viewDidLoad() {
super.viewDidLoad()
sessionGUIDLabel.isHidden = true
connectToSessionButton.isHidden = true
publishMessageButton.isHidden = true
}
// MARK: - IBActions
@IBAction func createNewLiveSessionPressed() {
ChuckPadSocial.sharedInstance().createLiveSession("My Live Session", sessionData: nil) { [weak self] (succeeded, liveSession, error) in
self?.liveSession = liveSession
self?.sessionGUIDLabel.text = liveSession?.sessionGUID
self?.sessionGUIDLabel.isHidden = false
self?.connectToSessionButton.isHidden = false
}
}
@IBAction func connectToSessionPressed() {
let demoLiveSession = LiveSession()
demoLiveSession.sessionGUID = "demo_channel"
chuckPadLive.connect(liveSession, chuckPadLiveDelegate: self)
sessionGUIDLabel.text = "\(demoLiveSession.sessionGUID!) - Connected"
publishMessageButton.isHidden = false
}
@IBAction func publishMessagePressed() {
chuckPadLive.publish("Hello Spencer2!")
}
// MARK: - ChuckPadLiveDelegate
func chuckPadLive(_ chuckPadLive: ChuckPadLive!, didReceive liveStatus: LiveStatus) {
print("didReceive - \(liveStatus)")
}
func chuckPadLive(_ chuckPadLive: ChuckPadLive!, didReceiveData data: Any) {
print("didReceive - \(data)")
}
}
| gpl-3.0 | 1333183eeff15739c3e000862ad594a8 | 29.969231 | 143 | 0.659215 | 5.353723 | false | false | false | false |
yanniks/Robonect-iOS | RobonectAPI/Enumerations/ErrorCode.swift | 1 | 3197 | //
// Copyright (C) 2017 Yannik Ehlert.
//
// 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.
//
//
// ErrorCode.swift
// Robonect
//
// Created by Yannik Ehlert on 06.06.17.
// Copyright © 2017 Yannik Ehlert. All rights reserved.
//
import Foundation
public extension RobonectAPI {
/**
Enumeration of error codes. Based on http://www.robonect.de/viewtopic.php?f=30&t=930&p=7687&hilit=Fehlercodes#p7687
*/
public enum ErrorCode: Int {
case workAreaExceeded = 1
case noLoopSignal = 2
case loopSensorMalfunctionFront = 4
case loopSensorMalfunctionBack = 5
case loopSensorMalfunction = 6
case wrongPinEntered = 8
case mowerImpacted = 9
case mowerTurned = 10
case batteryLow = 11
case batteryEmpty = 12
case noDrive = 13
case mowerLifted = 15
case stuckInCharger = 16
case chargerBlocked = 17
case impactSensorMalfunctionFront = 18
case impactSensorMalfunctionBack = 19
case rightEngineBlocked = 20
case leftEngineBlocked = 21
case rightWeelMalfunction = 22
case leftWheelMalfunction = 23
case bladeMotorMalfunction = 24
case mowingUnitBlocked = 25
case settingsResetted = 27
case storageCircuitProblem = 28
case slopeTooSteep = 29
case batteryProblem = 30
case stopButtonProblem = 31
case tiltSensorMalfunction = 32
case mowerIsTilted = 33
case rightEngineOverload = 35
case leftEngineOverload = 36
case currentTooHigh = 37
case cuttingHeightAdjustmentBlocked = 42
case unexpectedCuttingHeightAdjustment = 43
case guideWireSKOneNotFound = 50
case guideWireSKTwoNotFound = 51
case guideWireSKThreeNotFound = 52
case calibrationGuideWireEnded = 56
case shorttermBatteryProblem = 58
case batteryProblemTwo = 66
case alarmMowerPoweredOff = 69
case alarmMowerStopped = 70
case mowerRaised = 71
case mowerTilted = 72
// In case the code is not known
case unknown = -1
}
}
| mit | f3dbe685cbe1c5fa77cb2fdf4ee2550e | 37.047619 | 120 | 0.684919 | 4.482468 | false | false | false | false |
danielloureda/congenial-sniffle | Project8/Project8/ViewController.swift | 1 | 4115 | //
// ViewController.swift
// Project8
//
// Created by Daniel Loureda Arteaga on 12/6/17.
// Copyright © 2017 Dano. All rights reserved.
//
import UIKit
import GameplayKit
class ViewController: UIViewController {
@IBOutlet weak var cluesLabel: UILabel!
@IBOutlet weak var answersLabel: UILabel!
@IBOutlet weak var currentAnswer: UITextField!
@IBOutlet weak var scoreLabel: UILabel!
var letterButtons = [UIButton]()
var activatedButtons = [UIButton]()
var solutions = [String]()
var score: Int = 0 {
didSet {
scoreLabel.text = "Score: \(score)"
}
}
var level = 1
override func viewDidLoad() {
super.viewDidLoad()
for subview in view.subviews where subview.tag == 1001 {
let btn = subview as! UIButton
letterButtons.append(btn)
btn.addTarget(self, action: #selector(letterTapped), for: .touchUpInside)
}
loadLevel()
}
func loadLevel(){
var clueString = ""
var solutionString = ""
var letterBits = [String]()
if let levelFilePath = Bundle.main.path(forResource: "level\(level)", ofType: "txt") {
if let levelContents = try? String(contentsOfFile: levelFilePath) {
var lines = levelContents.components(separatedBy: "\n")
lines = GKRandomSource.sharedRandom().arrayByShufflingObjects(in: lines) as! [String]
for(index, line) in lines.enumerated(){
let parts = line.components(separatedBy: ":")
let answer = parts[0]
let clue = parts[1]
clueString += "\(index + 1). \(clue)\n"
let solutionWord = answer.replacingOccurrences(of: "|", with: "")
solutionString += "\(solutionWord.characters.count) letters\n"
solutions.append(solutionWord)
let bits = answer.components(separatedBy: "|")
letterBits += bits
}
}
}
cluesLabel.text = clueString.trimmingCharacters(in: .whitespacesAndNewlines)
answersLabel.text = solutionString.trimmingCharacters(in: .whitespacesAndNewlines)
letterBits = GKRandomSource.sharedRandom().arrayByShufflingObjects(in: letterBits) as! [String]
if letterBits.count == letterButtons.count {
for i in 0 ..< letterBits.count {
letterButtons[i].setTitle(letterBits[i], for: .normal)
}
}
}
func letterTapped(btn: UIButton){
currentAnswer.text = currentAnswer.text! + btn.titleLabel!.text!
activatedButtons.append(btn)
btn.isHidden = true
}
@IBAction func submitTapped() {
if let solutionPosition = solutions.index(of: currentAnswer.text!) {
activatedButtons.removeAll()
var splitClues = answersLabel.text!.components(separatedBy: "\n")
splitClues[solutionPosition] = currentAnswer.text!
answersLabel.text = splitClues.joined(separator: "\n")
currentAnswer.text = ""
score += 1
if score % 7 == 0 {
let ac = UIAlertController(title: "Well done!", message: "Are you ready for the next level?", preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "Let's go!", style: .default, handler: levelUp))
present(ac, animated: true)
}
}
}
func levelUp(action: UIAlertAction) {
level += 1
solutions.removeAll(keepingCapacity: true)
loadLevel()
for btn in letterButtons {
btn.isHidden = false
}
}
@IBAction func clearTapped() {
currentAnswer.text = ""
for btn in activatedButtons {
btn.isHidden = false
}
activatedButtons.removeAll()
}
}
| apache-2.0 | 35198ad376f96bec3b9fe8d8878790a8 | 31.912 | 133 | 0.554448 | 5.274359 | false | false | false | false |
devxoul/URLNavigator | Example/Sources/AppDelegate.swift | 1 | 1462 | //
// AppDelegate.swift
// URLNavigatorExample
//
// Created by Suyeol Jeon on 7/12/16.
// Copyright © 2016 Suyeol Jeon. All rights reserved.
//
import UIKit
import URLNavigator
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
private var navigator: NavigatorProtocol?
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
let navigator = Navigator()
// Initialize navigation map
NavigationMap.initialize(navigator: navigator)
let window = UIWindow(frame: UIScreen.main.bounds)
window.makeKeyAndVisible()
window.backgroundColor = .white
let userListViewController = UserListViewController(navigator: navigator)
window.rootViewController = UINavigationController(rootViewController: userListViewController)
self.window = window
self.navigator = navigator
return true
}
func application(
_ app: UIApplication,
open url: URL,
options: [UIApplication.OpenURLOptionsKey: Any] = [:]
) -> Bool {
// Try presenting the URL first
if self.navigator?.present(url, wrap: UINavigationController.self) != nil {
print("[Navigator] present: \(url)")
return true
}
// Try opening the URL
if self.navigator?.open(url) == true {
print("[Navigator] open: \(url)")
return true
}
return false
}
}
| mit | 8803728fd04c100817e08a388c01169f | 23.762712 | 98 | 0.700205 | 4.743506 | false | false | false | false |
boqian2000/swift-algorithm-club | Treap/TreapCollectionType.swift | 3 | 3211 | //
// TreapCollectionType.swift
// Treap
//
// Created by Robert Thompson on 2/18/16.
// Copyright © 2016 Robert Thompson
/* Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/
import Foundation
extension Treap: MutableCollection {
public typealias Index = TreapIndex<Key>
public subscript(index: TreapIndex<Key>) -> Element {
get {
guard let result = self.get(index.keys[index.keyIndex]) else {
fatalError("Invalid index!")
}
return result
}
mutating set {
let key = index.keys[index.keyIndex]
self = self.set(key: key, val: newValue)
}
}
public subscript(key: Key) -> Element? {
get {
return self.get(key)
}
mutating set {
guard let value = newValue else {
let _ = try? self.delete(key: key)
return
}
self = self.set(key: key, val: value)
}
}
public var startIndex: TreapIndex<Key> {
return TreapIndex<Key>(keys: keys, keyIndex: 0)
}
public var endIndex: TreapIndex<Key> {
let keys = self.keys
return TreapIndex<Key>(keys: keys, keyIndex: keys.count)
}
public func index(after i: TreapIndex<Key>) -> TreapIndex<Key> {
return i.successor()
}
fileprivate var keys: [Key] {
var results: [Key] = []
if case let .node(key, _, _, left, right) = self {
results.append(contentsOf: left.keys)
results.append(key)
results.append(contentsOf: right.keys)
}
return results
}
}
public struct TreapIndex<Key: Comparable>: Comparable {
public static func <(lhs: TreapIndex<Key>, rhs: TreapIndex<Key>) -> Bool {
return lhs.keyIndex < rhs.keyIndex
}
fileprivate let keys: [Key]
fileprivate let keyIndex: Int
public func successor() -> TreapIndex {
return TreapIndex(keys: keys, keyIndex: keyIndex + 1)
}
public func predecessor() -> TreapIndex {
return TreapIndex(keys: keys, keyIndex: keyIndex - 1)
}
fileprivate init(keys: [Key] = [], keyIndex: Int = 0) {
self.keys = keys
self.keyIndex = keyIndex
}
}
public func ==<Key: Comparable>(lhs: TreapIndex<Key>, rhs: TreapIndex<Key>) -> Bool {
return lhs.keys == rhs.keys && lhs.keyIndex == rhs.keyIndex
}
| mit | 9f8534223e968eec6203a011d6e85b88 | 27.918919 | 85 | 0.677259 | 4.179688 | false | false | false | false |
Koolistov/Convenience | Convenience/UIColor+Convenience.swift | 1 | 1724 | //
// UIColor+Convenience.swift
// Convenience
//
// Created by Johan Kool on 2/12/14.
// Copyright (c) 2014 Koolistov Pte. Ltd. All rights reserved.
//
import Foundation
import UIKit
public extension UIColor {
/**
Create a color from a hexadecimal string
String may be prefixed with #. Alpha values are supported too.
- parameter hex: An hexadecimal string
*/
public convenience init(hex: String) {
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var alpha: CGFloat = 1.0
var rgba = hex
if rgba.hasPrefix("#") {
let index = rgba.startIndex.advancedBy(1)
rgba = rgba.substringFromIndex(index)
}
let scanner = NSScanner(string: rgba)
var hexValue: CUnsignedLongLong = 0
if scanner.scanHexLongLong(&hexValue) {
if rgba.characters.count == 6 {
red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0
green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0
blue = CGFloat(hexValue & 0x0000FF) / 255.0
} else if rgba.characters.count == 8 {
red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0
green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0
blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0
alpha = CGFloat(hexValue & 0x000000FF) / 255.0
} else {
print("invalid rgb string length")
}
} else {
print("scan hex error in string \(rgba)")
}
self.init(red:red, green:green, blue:blue, alpha:alpha)
}
}
| mit | 8776a1567174b121cb44e8447d6be66e | 30.345455 | 70 | 0.539443 | 4.046948 | false | false | false | false |
Legoless/iOS-Course | 2015-1/Lesson8/Gamebox/Gamebox/DictionaryExample.swift | 2 | 794 | //
// DictionaryExample.swift
// Gamebox
//
// Created by Dal Rupnik on 29/10/15.
// Copyright © 2015 Unified Sense. All rights reserved.
//
import Foundation
func lesson5 () {
var dictionary : [String : AnyObject] = [String : AnyObject]()
dictionary["A"] = nil
print ("First: \(dictionary.count)")
dictionary["A"] = NSNull()
if dictionary["A"] is NSNull {
print ("IS NSNULL")
}
if dictionary["A"] != nil {
print ("IS NIL")
}
if let _ = dictionary["A"] as? NSNull {
print("NULL")
}
print ("Second: \(dictionary.count)")
dictionary["A"] = nil
if dictionary["A"] != nil {
print ("IS SECOND NIL")
}
print ("Third: \(dictionary.count)")
} | mit | ed44750679c74fcf358d1f58552ce550 | 17.045455 | 66 | 0.520807 | 4.005051 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/CryptoAssets/Sources/BitcoinChainKit/Transactions/NativeBitcoin/CoinSelection/CoinSelectionInputs.swift | 1 | 1086 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import BigInt
import PlatformKit
public struct CoinSelectionInputs {
public struct Target {
let value: BigUInt
let scriptType: BitcoinScriptType
public init(
value: BigUInt,
scriptType: BitcoinScriptType
) {
self.value = value
self.scriptType = scriptType
}
}
public let target: Target
public let feePerByte: BigUInt
public let unspentOutputs: [UnspentOutput]
public let sortingStrategy: CoinSortingStrategy
public let changeOutputType: BitcoinScriptType
public init(
target: CoinSelectionInputs.Target,
feePerByte: BigUInt,
unspentOutputs: [UnspentOutput],
sortingStrategy: CoinSortingStrategy,
changeOutputType: BitcoinScriptType
) {
self.target = target
self.feePerByte = feePerByte
self.unspentOutputs = unspentOutputs
self.sortingStrategy = sortingStrategy
self.changeOutputType = changeOutputType
}
}
| lgpl-3.0 | 6f36dc6167b943b499c59280119f8d2f | 25.463415 | 62 | 0.663594 | 5.070093 | false | false | false | false |
targetcloud/TGPageView | TGPageView/TGPageView/TGPageView/UIColor+extension.swift | 2 | 2356 | //
// UIColor+extension.swift
// TGPageView
//
// Created by targetcloud on 2017/3/22.
// Copyright © 2017年 targetcloud. All rights reserved.
//
import UIKit
extension UIColor{
class func randomColor() -> UIColor{
return UIColor(red: CGFloat(arc4random_uniform(255))/255.0, green: CGFloat(arc4random_uniform(255))/255.0, blue: CGFloat(arc4random_uniform(255))/255.0, alpha: 1.0)
}
class func random() -> UIColor{
return UIColor.randomColor()
}
convenience init(r: CGFloat, g: CGFloat, b: CGFloat, alpha: CGFloat = 1.0) {
self.init(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: alpha)
}
convenience init(c: CGFloat, alpha: CGFloat = 1.0) {
self.init(red: c/255.0, green: c/255.0, blue: c/255.0, alpha: alpha)
}
convenience init?(hex:String) {
guard hex.characters.count>=6 else {
return nil
}
var hexTemp = hex.uppercased()
if hexTemp.hasPrefix("0X") || hexTemp.hasPrefix("##"){
hexTemp = (hexTemp as NSString).substring(from: 2)
}
if hexTemp.hasPrefix("#"){
hexTemp = (hexTemp as NSString).substring(from: 1)
}
var range = NSRange(location: 0, length: 2)
let rHex = (hexTemp as NSString).substring(with: range)
range.location = 2
let gHex = (hexTemp as NSString).substring(with: range)
range.location = 4
let bHex = (hexTemp as NSString).substring(with: range)
var r : UInt32 = 0
var g : UInt32 = 0
var b : UInt32 = 0
Scanner(string: rHex).scanHexInt32(&r)
Scanner(string: gHex).scanHexInt32(&g)
Scanner(string: bHex).scanHexInt32(&b)
self.init(red: CGFloat(r)/255.0, green: CGFloat(g)/255.0, blue: CGFloat(b)/255.0, alpha: 1.0)
}
func getRGB() -> (CGFloat,CGFloat,CGFloat) {
var r : CGFloat = 0
var g : CGFloat = 0
var b : CGFloat = 0
if self.getRed(&r, green: &g, blue: &b, alpha: nil){
return (r * 255,g * 255,b * 255)
}
guard let cmps = cgColor.components else {
// throw
fatalError("请使用RGB创建UIColor")
}
return(cmps[0] * 255,cmps[1] * 255,cmps[2] * 255)
}
}
| mit | 95ce06df13a0eb7a0c188f215ac509a3 | 30.24 | 172 | 0.555698 | 3.660938 | false | false | false | false |
huonw/swift | test/SILGen/weak.swift | 1 | 3723 |
// RUN: %target-swift-emit-silgen -module-name weak -Xllvm -sil-full-demangle -enable-sil-ownership %s | %FileCheck %s
class C {
func f() -> Int { return 42 }
}
func takeClosure(fn: @escaping () -> Int) {}
struct A {
weak var x: C?
}
// CHECK: sil hidden @$S4weak5test01cyAA1CC_tF : $@convention(thin) (@guaranteed C) -> () {
func test0(c c: C) {
var c = c
// CHECK: bb0(%0 : @guaranteed $C):
// CHECK: [[C:%.*]] = alloc_box ${ var C }
// CHECK-NEXT: [[PBC:%.*]] = project_box [[C]]
var a: A
// CHECK: [[A1:%.*]] = alloc_box ${ var A }
// CHECK: [[MARKED_A1:%.*]] = mark_uninitialized [var] [[A1]]
// CHECK-NEXT: [[PBA:%.*]] = project_box [[MARKED_A1]]
weak var x = c
// CHECK: [[X:%.*]] = alloc_box ${ var @sil_weak Optional<C> }, var, name "x"
// CHECK-NEXT: [[PBX:%.*]] = project_box [[X]]
// Implicit conversion
// CHECK-NEXT: [[READ:%.*]] = begin_access [read] [unknown] [[PBC]]
// CHECK-NEXT: [[TMP:%.*]] = load [copy] [[READ]] : $*C
// CHECK-NEXT: end_access [[READ]]
// CHECK-NEXT: [[OPTVAL:%.*]] = enum $Optional<C>, #Optional.some!enumelt.1, [[TMP]] : $C
// CHECK-NEXT: store_weak [[OPTVAL]] to [initialization] [[PBX]] : $*@sil_weak Optional<C>
// CHECK-NEXT: destroy_value [[OPTVAL]] : $Optional<C>
a.x = c
// Implicit conversion
// CHECK-NEXT: [[READ:%.*]] = begin_access [read] [unknown] [[PBC]]
// CHECK-NEXT: [[TMP:%.*]] = load [copy] [[READ]] : $*C
// CHECK-NEXT: end_access [[READ]]
// CHECK-NEXT: [[OPTVAL:%.*]] = enum $Optional<C>, #Optional.some!enumelt.1, [[TMP]] : $C
// Drill to a.x
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PBA]]
// CHECK-NEXT: [[A_X:%.*]] = struct_element_addr [[WRITE]] : $*A, #A.x
// Store to a.x.
// CHECK-NEXT: store_weak [[OPTVAL]] to [[A_X]] : $*@sil_weak Optional<C>
// CHECK-NEXT: destroy_value [[OPTVAL]] : $Optional<C>
}
// <rdar://problem/16871284> silgen crashes on weak capture
// CHECK: closure #1 () -> Swift.Int in weak.testClosureOverWeak() -> ()
// CHECK-LABEL: sil private @$S4weak19testClosureOverWeakyyFSiycfU_ : $@convention(thin) (@guaranteed { var @sil_weak Optional<C> }) -> Int {
// CHECK: bb0(%0 : @guaranteed ${ var @sil_weak Optional<C> }):
// CHECK-NEXT: %1 = project_box %0
// CHECK-NEXT: debug_value_addr %1 : $*@sil_weak Optional<C>, var, name "bC", argno 1
// CHECK-NEXT: [[READ:%.*]] = begin_access [read] [unknown] %1
// CHECK-NEXT: [[STK:%.*]] = alloc_stack $Optional<C>
// CHECK-NEXT: [[VAL:%.*]] = load_weak [[READ]] : $*@sil_weak Optional<C>
// CHECK-NEXT: store [[VAL]] to [init] [[STK]] : $*Optional<C>
func testClosureOverWeak() {
weak var bC = C()
takeClosure { bC!.f() }
}
class CC {
weak var x: CC?
// CHECK-LABEL: sil hidden @$S4weak2CCC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned CC) -> @owned CC {
// CHECK: bb0([[SELF:%.*]] : @owned $CC):
// CHECK: [[UNINIT_SELF:%.*]] = mark_uninitialized [rootself] [[SELF]] : $CC
// CHECK: [[FOO:%.*]] = alloc_box ${ var Optional<CC> }, var, name "foo"
// CHECK: [[PB:%.*]] = project_box [[FOO]]
// CHECK: [[BORROWED_UNINIT_SELF:%.*]] = begin_borrow [[UNINIT_SELF]]
// CHECK: [[X:%.*]] = ref_element_addr [[BORROWED_UNINIT_SELF]] : $CC, #CC.x
// CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[X]] : $*@sil_weak Optional<CC>
// CHECK: [[VALUE:%.*]] = load_weak [[READ]] : $*@sil_weak Optional<CC>
// CHECK: store [[VALUE]] to [init] [[PB]] : $*Optional<CC>
// CHECK: end_borrow [[BORROWED_UNINIT_SELF]] from [[UNINIT_SELF]]
// CHECK: destroy_value [[FOO]]
// CHECK: } // end sil function '$S4weak2CCC{{[_0-9a-zA-Z]*}}fc'
init() {
var foo = x
}
}
func testNoneWeak() {
weak var x: CC? = nil
weak var y: CC? = .none
}
| apache-2.0 | a41ec8c9b38d18781f4b71eeef2e08a5 | 39.467391 | 141 | 0.565673 | 2.933806 | false | true | false | false |
YuanZhu-apple/ResearchKit | Testing/ORKTest/ORKTest/Charts/ChartDataSources.swift | 5 | 16950 | /*
Copyright (c) 2015, James Cox. All rights reserved.
Copyright (c) 2015-2016, Ricardo Sánchez-Sáez.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder(s) nor the names of any contributors
may be used to endorse or promote products derived from this software without
specific prior written permission. No license is granted to the trademarks of
the copyright holders even if such marks are included in this software.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import ResearchKit
func randomColorArray(number: Int) -> [UIColor] {
func random() -> CGFloat {
return CGFloat(Float(arc4random()) / Float(UINT32_MAX))
}
var colors: [UIColor] = []
for _ in 0 ..< number {
colors.append(UIColor(red: random(), green: random(), blue: random(), alpha: 1))
}
return colors
}
let NumberOfPieChartSegments = 13
class ColorlessPieChartDataSource: NSObject, ORKPieChartViewDataSource {
func numberOfSegmentsInPieChartView(pieChartView: ORKPieChartView ) -> Int {
return NumberOfPieChartSegments
}
func pieChartView(pieChartView: ORKPieChartView, valueForSegmentAtIndex index: Int) -> CGFloat {
return CGFloat(index + 1)
}
func pieChartView(pieChartView: ORKPieChartView, titleForSegmentAtIndex index: Int) -> String {
return "Title \(index + 1)"
}
}
class RandomColorPieChartDataSource: ColorlessPieChartDataSource {
lazy var backingStore: [UIColor] = {
return randomColorArray(NumberOfPieChartSegments)
}()
func pieChartView(pieChartView: ORKPieChartView, colorForSegmentAtIndex index: Int) -> UIColor {
return backingStore[index]
}
}
class BaseFloatRangeGraphChartDataSource: NSObject, ORKValueRangeGraphChartViewDataSource {
var plotPoints: [[ORKValueRange]] = [[]]
func numberOfPlotsInGraphChartView(graphChartView: ORKGraphChartView) -> Int {
return plotPoints.count
}
func graphChartView(graphChartView: ORKGraphChartView, dataPointForPointIndex pointIndex: Int, plotIndex: Int) -> ORKValueRange {
return plotPoints[plotIndex][pointIndex]
}
func graphChartView(graphChartView: ORKGraphChartView, numberOfDataPointsForPlotIndex plotIndex: Int) -> Int {
return plotPoints[plotIndex].count
}
}
class BaseFloatStackGraphChartDataSource: NSObject, ORKValueStackGraphChartViewDataSource {
var plotPoints: [[ORKValueStack]] = [[]]
func numberOfPlotsInGraphChartView(graphChartView: ORKGraphChartView) -> Int {
return plotPoints.count
}
func graphChartView(graphChartView: ORKGraphChartView, dataPointForPointIndex pointIndex: Int, plotIndex: Int) -> ORKValueStack {
return plotPoints[plotIndex][pointIndex]
}
func graphChartView(graphChartView: ORKGraphChartView, numberOfDataPointsForPlotIndex plotIndex: Int) -> Int {
return plotPoints[plotIndex].count
}
}
class LineGraphChartDataSource: BaseFloatRangeGraphChartDataSource {
override init() {
super.init()
plotPoints =
[
[
ORKValueRange(),
ORKValueRange(value: 20),
ORKValueRange(value: 25),
ORKValueRange(),
ORKValueRange(value: 30),
ORKValueRange(value: 40),
ORKValueRange(),
],
[
ORKValueRange(value: 2),
ORKValueRange(value: 4),
ORKValueRange(value: 8),
ORKValueRange(value: 16),
ORKValueRange(value: 32),
ORKValueRange(value: 50),
ORKValueRange(value: 64),
],
[
ORKValueRange(),
ORKValueRange(),
ORKValueRange(),
ORKValueRange(value: 20),
ORKValueRange(value: 25),
ORKValueRange(),
ORKValueRange(value: 30),
ORKValueRange(value: 40),
ORKValueRange(),
],
]
}
func maximumValueForGraphChartView(graphChartView: ORKGraphChartView) -> Double {
return 70
}
func minimumValueForGraphChartView(graphChartView: ORKGraphChartView) -> Double {
return 0
}
func numberOfDivisionsInXAxisForGraphChartView(graphChartView: ORKGraphChartView) -> Int {
return 10
}
func graphChartView(graphChartView: ORKGraphChartView, titleForXAxisAtPointIndex pointIndex: Int) -> String? {
return (pointIndex % 2 == 0) ? nil : "\(pointIndex + 1)"
}
func graphChartView(graphChartView: ORKGraphChartView, drawsVerticalReferenceLineAtPointIndex pointIndex: Int) -> Bool {
return (pointIndex % 2 == 1) ? false : true
}
func scrubbingPlotIndexForGraphChartView(graphChartView: ORKGraphChartView) -> Int {
return 2
}
}
class ColoredLineGraphChartDataSource: LineGraphChartDataSource {
func graphChartView(graphChartView: ORKGraphChartView, colorForPlotIndex plotIndex: Int) -> UIColor {
let color: UIColor
switch plotIndex {
case 0:
color = UIColor.cyanColor()
case 1:
color = UIColor.magentaColor()
case 2:
color = UIColor.yellowColor()
default:
color = UIColor.redColor()
}
return color
}
func graphChartView(graphChartView: ORKGraphChartView, fillColorForPlotIndex plotIndex: Int) -> UIColor {
let color: UIColor
switch plotIndex {
case 0:
color = UIColor.blueColor().colorWithAlphaComponent(0.6)
case 1:
color = UIColor.redColor().colorWithAlphaComponent(0.6)
case 2:
color = UIColor.greenColor().colorWithAlphaComponent(0.6)
default:
color = UIColor.cyanColor().colorWithAlphaComponent(0.6)
}
return color
}
}
class DiscreteGraphChartDataSource: BaseFloatRangeGraphChartDataSource {
override init() {
super.init()
plotPoints =
[
[
ORKValueRange(),
ORKValueRange(minimumValue: 0, maximumValue: 2),
ORKValueRange(minimumValue: 1, maximumValue: 3),
ORKValueRange(minimumValue: 2, maximumValue: 6),
ORKValueRange(minimumValue: 3, maximumValue: 9),
ORKValueRange(minimumValue: 4, maximumValue: 13),
],
[
ORKValueRange(value: 1),
ORKValueRange(minimumValue: 2, maximumValue: 4),
ORKValueRange(minimumValue: 3, maximumValue: 8),
ORKValueRange(minimumValue: 5, maximumValue: 11),
ORKValueRange(minimumValue: 7, maximumValue: 13),
ORKValueRange(minimumValue: 10, maximumValue: 13),
ORKValueRange(minimumValue: 12, maximumValue: 15),
],
[
ORKValueRange(),
ORKValueRange(minimumValue: 5, maximumValue: 6),
ORKValueRange(),
ORKValueRange(minimumValue: 2, maximumValue: 15),
ORKValueRange(minimumValue: 4, maximumValue: 11),
],
]
}
func numberOfDivisionsInXAxisForGraphChartView(graphChartView: ORKGraphChartView) -> Int {
return 8
}
func graphChartView(graphChartView: ORKGraphChartView, titleForXAxisAtPointIndex pointIndex: Int) -> String {
return "\(pointIndex + 1)"
}
func scrubbingPlotIndexForGraphChartView(graphChartView: ORKGraphChartView) -> Int {
return 2
}
}
class ColoredDiscreteGraphChartDataSource: DiscreteGraphChartDataSource {
func graphChartView(graphChartView: ORKGraphChartView, colorForPlotIndex plotIndex: Int) -> UIColor {
let color: UIColor
switch plotIndex {
case 0:
color = UIColor.cyanColor()
case 1:
color = UIColor.magentaColor()
case 2:
color = UIColor.yellowColor()
default:
color = UIColor.redColor()
}
return color
}
}
class BarGraphChartDataSource: BaseFloatStackGraphChartDataSource {
override init() {
super.init()
plotPoints =
[
[
ORKValueStack(),
ORKValueStack(stackedValues: [0, 2, 5]),
ORKValueStack(stackedValues: [1, 3, 2]),
ORKValueStack(stackedValues: [2, 6, 1]),
ORKValueStack(stackedValues: [3, 9, 4]),
ORKValueStack(stackedValues: [4, 13, 2]),
],
[
ORKValueStack(stackedValues: [1]),
ORKValueStack(stackedValues: [2, 4]),
ORKValueStack(stackedValues: [3, 8]),
ORKValueStack(stackedValues: [5, 11]),
ORKValueStack(stackedValues: [7, 13]),
ORKValueStack(stackedValues: [10, 13]),
ORKValueStack(stackedValues: [12, 15]),
],
[
ORKValueStack(),
ORKValueStack(stackedValues: [5, 6]),
ORKValueStack(stackedValues: [2, 15]),
ORKValueStack(stackedValues: [4, 11]),
ORKValueStack(),
ORKValueStack(stackedValues: [6, 16]),
],
]
}
func numberOfDivisionsInXAxisForGraphChartView(graphChartView: ORKGraphChartView) -> Int {
return 8
}
func graphChartView(graphChartView: ORKGraphChartView, titleForXAxisAtPointIndex pointIndex: Int) -> String {
return "\(pointIndex + 1)"
}
func scrubbingPlotIndexForGraphChartView(graphChartView: ORKGraphChartView) -> Int {
return 2
}
}
class ColoredBarGraphChartDataSource: BarGraphChartDataSource {
func graphChartView(graphChartView: ORKGraphChartView, colorForPlotIndex plotIndex: Int) -> UIColor {
let color: UIColor
switch plotIndex {
case 0:
color = UIColor.cyanColor()
case 1:
color = UIColor.magentaColor()
case 2:
color = UIColor.yellowColor()
default:
color = UIColor.redColor()
}
return color
}
}
class PerformanceLineGraphChartDataSource: BaseFloatRangeGraphChartDataSource {
override init() {
super.init()
plotPoints =
[
[
ORKValueRange(),
ORKValueRange(value: 20),
ORKValueRange(value: 25),
ORKValueRange(),
ORKValueRange(value: 30),
ORKValueRange(value: 40),
ORKValueRange(),
ORKValueRange(),
ORKValueRange(value: 20),
ORKValueRange(value: 25),
ORKValueRange(),
ORKValueRange(value: 30),
ORKValueRange(value: 40),
ORKValueRange(),
ORKValueRange(),
ORKValueRange(value: 20),
ORKValueRange(value: 25),
ORKValueRange(),
ORKValueRange(value: 30),
ORKValueRange(value: 40),
ORKValueRange(),
ORKValueRange(),
ORKValueRange(value: 20),
ORKValueRange(value: 25),
ORKValueRange(),
ORKValueRange(value: 30),
ORKValueRange(value: 40),
ORKValueRange(),
],
[
ORKValueRange(value: 2),
ORKValueRange(value: 4),
ORKValueRange(value: 8),
ORKValueRange(value: 16),
ORKValueRange(value: 32),
ORKValueRange(value: 50),
ORKValueRange(value: 64),
ORKValueRange(value: 2),
ORKValueRange(value: 4),
ORKValueRange(value: 8),
ORKValueRange(value: 16),
ORKValueRange(value: 32),
ORKValueRange(value: 50),
ORKValueRange(value: 64),
ORKValueRange(value: 2),
ORKValueRange(value: 4),
ORKValueRange(value: 8),
ORKValueRange(value: 16),
ORKValueRange(value: 32),
ORKValueRange(value: 50),
ORKValueRange(value: 64),
ORKValueRange(value: 2),
ORKValueRange(value: 4),
ORKValueRange(value: 8),
ORKValueRange(value: 16),
ORKValueRange(value: 32),
ORKValueRange(value: 50),
ORKValueRange(value: 64),
],
[
ORKValueRange(),
ORKValueRange(),
ORKValueRange(),
ORKValueRange(value: 20),
ORKValueRange(value: 25),
ORKValueRange(),
ORKValueRange(value: 30),
ORKValueRange(value: 40),
ORKValueRange(),
ORKValueRange(),
ORKValueRange(),
ORKValueRange(),
ORKValueRange(value: 20),
ORKValueRange(value: 25),
ORKValueRange(),
ORKValueRange(value: 30),
ORKValueRange(value: 40),
ORKValueRange(),
ORKValueRange(),
ORKValueRange(),
ORKValueRange(),
ORKValueRange(value: 20),
ORKValueRange(value: 25),
ORKValueRange(),
ORKValueRange(value: 30),
ORKValueRange(value: 40),
ORKValueRange(),
ORKValueRange(),
ORKValueRange(),
ORKValueRange(),
ORKValueRange(value: 20),
ORKValueRange(value: 25),
ORKValueRange(),
ORKValueRange(value: 30),
ORKValueRange(value: 40),
ORKValueRange(),
],
]
}
func maximumValueForGraphChartView(graphChartView: ORKGraphChartView) -> Double {
return 70
}
func minimumValueForGraphChartView(graphChartView: ORKGraphChartView) -> Double {
return 0
}
func numberOfDivisionsInXAxisForGraphChartView(graphChartView: ORKGraphChartView) -> Int {
return 10
}
func graphChartView(graphChartView: ORKGraphChartView, titleForXAxisAtPointIndex pointIndex: Int) -> String? {
return (pointIndex % 2 == 0) ? nil : "\(pointIndex + 1)"
}
func graphChartView(graphChartView: ORKGraphChartView, drawsVerticalReferenceLineAtPointIndex pointIndex: Int) -> Bool {
return (pointIndex % 2 == 1) ? false : true
}
func scrubbingPlotIndexForGraphChartView(graphChartView: ORKGraphChartView) -> Int {
return 2
}
}
| bsd-3-clause | 574c3848b23937f13eb3a84fb3d25a0d | 35.923747 | 133 | 0.563134 | 6.098597 | false | false | false | false |
ngquerol/Diurna | App/Sources/View Controllers/UserLoginViewController.swift | 1 | 3232 | //
// UserLoginViewController.swift
// Diurna
//
// Created by Nicolas Gaulard-Querol on 29/07/2020.
// Copyright © 2020 Nicolas Gaulard-Querol. All rights reserved.
//
import AppKit
import HackerNewsAPI
import OSLog
// MARK: - UserLoginViewControllerDelegate
@objc protocol UserLoginViewControllerDelegate: class {
func userDidLogin(with user: String)
func userDidCancelLogin()
}
// MARK: - UserLoginViewController
class UserLoginViewController: NSViewController {
// MARK: Outlets
@IBOutlet weak var userNameTextField: NSTextField! {
didSet {
userNameTextField.delegate = self
}
}
@IBOutlet weak var userPasswordTextField: NSSecureTextField! {
didSet {
userPasswordTextField.delegate = self
}
}
@IBOutlet weak var cancelButton: NSButton! {
didSet {
cancelButton.action = #selector(self.cancel(_:))
}
}
@IBOutlet weak var loginButton: NSButton! {
didSet {
loginButton.isEnabled = false
loginButton.action = #selector(self.login(_:))
}
}
// MARK: Properties
weak var delegate: UserLoginViewControllerDelegate?
var progressOverlayView: NSView?
// MARK: Methods
@objc private func login(_ sender: Any?) {
showProgressOverlay(
with: "Logging in as \"\(userNameTextField.stringValue)\"…"
)
webClient.login(
withAccount: userNameTextField.stringValue,
andPassword: userPasswordTextField.stringValue
) { [weak self] loginResult in
switch loginResult {
case let .success(user):
self?.delegate?.userDidLogin(with: user)
case let .failure(error):
self?.handleError(error)
}
self?.hideProgressOverlay()
}
}
@objc private func cancel(_ sender: Any?) {
delegate?.userDidCancelLogin()
}
private func handleError(_ error: Error) {
os_log(
"Failed to authenticate user \"%s\": %s",
log: .webRequests,
type: .error,
userNameTextField.stringValue,
error.localizedDescription
)
NSAlert.showModal(
withTitle: "Failed to log in",
andText: """
You may need to verify your login using a captcha;
For now this is unsupported.
"""
)
}
}
// MARK: - NSNib.Name
extension NSNib.Name {
static let userLoginViewController = "UserLoginViewController"
}
// MARK: - NSTextFieldDelegate
extension UserLoginViewController: NSTextFieldDelegate {
func controlTextDidChange(_ obj: Notification) {
func isNotBlank(_ string: String) -> Bool {
string.trimmingCharacters(in: .whitespaces).count > 0
}
let inputs = [
userNameTextField.stringValue,
userPasswordTextField.stringValue,
]
loginButton.isEnabled = inputs.allSatisfy(isNotBlank)
}
}
// MARK: - HNWebConsumer
extension UserLoginViewController: HNWebConsumer {}
// MARK: - ProgressShowing
extension UserLoginViewController: ProgressShowing {}
| mit | 65a8cbe118c2788c2620fa2518840d43 | 23.648855 | 71 | 0.613812 | 5.174679 | false | false | false | false |
Monte9/MoviesDBApp-CodePathU | Project1-FlickM/MovieInfoViewController.swift | 2 | 7351 | //
// MovieInfoViewController.swift
// Project1-FlickM
//
// Created by Monte's Pro 13" on 1/18/16.
// Copyright © 2016 MonteThakkar. All rights reserved.
//
import UIKit
import MBProgressHUD
class MovieInfoViewController: UIViewController {
@IBOutlet weak var posterImageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var overviewLabel: UILabel!
var movie : NSDictionary!
var detailMovie : NSDictionary!
var similarMovies : [NSDictionary]!
var movieID : Int!
@IBOutlet weak var genreLabel: UILabel!
@IBOutlet weak var movieLengthLabel: UILabel!
@IBOutlet weak var tagIineLabel: UILabel!
@IBOutlet weak var ratingLabel: UILabel!
@IBOutlet weak var popularLabel: UILabel!
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var infoView: UIView!
@IBOutlet var parentView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// scrollView.contentSize = CGSize(width: parentView.frame.size.width, height: parentView.frame.size.height)
//infoView.frame.origin.y + infoView.frame.size.height)
movieID = movie["id"] as! Int
// print(movieID)
getMovieInfo()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func getMovieInfo() {
let apiKey = "a07e22bc18f5cb106bfe4cc1f83ad8ed"
let url = NSURL(string:"https://api.themoviedb.org/3/movie/\(movieID)?api_key=\(apiKey)")
let request = NSURLRequest(URL: url!)
let session = NSURLSession(
configuration: NSURLSessionConfiguration.defaultSessionConfiguration(),
delegate:nil,
delegateQueue:NSOperationQueue.mainQueue()
)
let task : NSURLSessionDataTask = session.dataTaskWithRequest(request,
completionHandler: { (dataOrNil, response, error) in
if let data = dataOrNil {
if let responseDictionary = try! NSJSONSerialization.JSONObjectWithData(
data, options:[]) as? NSDictionary {
if (responseDictionary["status_code"] == nil ) {
self.detailMovie = responseDictionary
print("Connection to API successful! here....")
// print(self.detailMovie)
self.getSimilarMovies()
//set all the labels
self.titleLabel.text = self.detailMovie["title"] as? String
self.overviewLabel.text = self.detailMovie["overview"] as? String
self.overviewLabel.sizeToFit()
self.popularLabel.text = String(self.detailMovie["popularity"] as! Int * 10) + " %"
self.ratingLabel.text = String(self.detailMovie["vote_average"] as! Int) + "/10"
self.movieLengthLabel.text = String(self.detailMovie["runtime"] as! Int) + " mins"
self.tagIineLabel.text = self.detailMovie["tagline"] as! String
var genres = self.detailMovie.valueForKeyPath("genres") as? [NSDictionary!]
var genreList = ""
for var genreDict in genres! {
genreList = genreList + String(genreDict["name"] as! String) + ", "
}
self.genreLabel.text = genreList
let baseImageURL = "http://image.tmdb.org/t/p/w500/"
if let imagePath = self.detailMovie["backdrop_path"] as? String {
let imageURL = NSURL(string: baseImageURL + imagePath)
self.posterImageView.setImageWithURL(imageURL!)
} else {
self.posterImageView.image = UIImage(named: "black")
}
}
else {
print("error")
}
// Hide HUD once network request comes back (must be done on main UI thread)
MBProgressHUD.hideHUDForView(self.view, animated: true)
}
}
});
task.resume()
}
func getSimilarMovies() {
let apiKey = "a07e22bc18f5cb106bfe4cc1f83ad8ed"
let url = NSURL(string:"https://api.themoviedb.org/3/movie/\(movieID)/similar?api_key=\(apiKey)")
let request = NSURLRequest(URL: url!)
let session = NSURLSession(
configuration: NSURLSessionConfiguration.defaultSessionConfiguration(),
delegate:nil,
delegateQueue:NSOperationQueue.mainQueue()
)
let task : NSURLSessionDataTask = session.dataTaskWithRequest(request,
completionHandler: { (dataOrNil, response, error) in
if let data = dataOrNil {
if let responseDictionary = try! NSJSONSerialization.JSONObjectWithData(
data, options:[]) as? NSDictionary {
if (responseDictionary["status_code"] == nil ) {
self.similarMovies = responseDictionary["results"] as? [NSDictionary]
print("Similar movies get successful!")
// print(self.searchedMovies)
// print(self.similarMovies)
}
else {
print("error")
}
// Hide HUD once network request comes back (must be done on main UI thread)
MBProgressHUD.hideHUDForView(self.view, animated: true)
}
}
});
task.resume()
}
/*
// 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.
}
*/
}
| mit | 57b7085e3a3b30e20b4767e38c1c6093 | 40.525424 | 116 | 0.479456 | 6.150628 | false | false | false | false |
tlax/GaussSquad | GaussSquad/Model/LinearEquations/Plot/MLinearEquationsPlotRender.swift | 1 | 2923 | import UIKit
import MetalKit
class MLinearEquationsPlotRender:MetalRenderableProtocol
{
private weak var device:MTLDevice?
private var projection:MTLBuffer
private var indeterminates:[MLinearEquationsPlotRenderIndeterminate]
private let texturePoint:MTLTexture?
private let textureLine:MTLTexture?
private let cartesian:MLinearEquationsPlotRenderCartesian?
init(device:MTLDevice)
{
let textureLoader:MTKTextureLoader = MTKTextureLoader(device:device)
texturePoint = textureLoader.loadImage(
image:#imageLiteral(resourceName: "assetTexturePoint"))
if let textureLine:MTLTexture = textureLoader.loadImage(
image:#imageLiteral(resourceName: "assetTextureLine"))
{
self.textureLine = textureLine
cartesian = MLinearEquationsPlotRenderCartesian(
device:device,
texture:textureLine)
}
else
{
self.textureLine = nil
cartesian = nil
}
projection = MetalProjection.projectionMatrix(device:device)
indeterminates = []
self.device = device
}
//MARK: public
func updateProjection(width:CGFloat, height:CGFloat)
{
guard
let device:MTLDevice = self.device
else
{
return
}
projection = MetalProjection.projectionMatrix(
device:device,
width:width,
height:height)
}
func addIndeterminate(
device:MTLDevice,
positionX:Double,
positionY:Double,
color:UIColor)
{
guard
let texturePoint:MTLTexture = self.texturePoint,
let textureLine:MTLTexture = self.textureLine
else
{
return
}
let floatPositionX:Float = Float(positionX)
let floatPositionY:Float = Float(positionY)
let indeterminate:MLinearEquationsPlotRenderIndeterminate = MLinearEquationsPlotRenderIndeterminate(
device:device,
texturePoint:texturePoint,
textureLine:textureLine,
positionX:floatPositionX,
positionY:floatPositionY,
color:color)
indeterminates.insert(indeterminate, at:0)
}
func clearIndeterminates()
{
indeterminates = []
}
//MARK: renderable Protocol
func render(renderEncoder:MTLRenderCommandEncoder)
{
renderEncoder.projectionMatrix(
projection:projection)
cartesian?.render(renderEncoder:renderEncoder)
for indeterminate:MLinearEquationsPlotRenderIndeterminate in indeterminates
{
indeterminate.render(
renderEncoder:renderEncoder)
}
}
}
| mit | f21e2594a57e6e379e1d71ec9bc0a0cf | 26.575472 | 108 | 0.601437 | 6.166667 | false | false | false | false |
eduarenas/GithubClient | Sources/GitHubClient/Models/Request/OrganizationUpdate.swift | 1 | 1911 | //
// OrganizationUpdate.swift
// GitHubClient
//
// Created by Eduardo Arenas on 4/23/18.
//
import Foundation
public struct OrganizationUpdate: Encodable {
public let billingEmail: String?
public let company: String?
public let email: String?
public let location: String?
public let name: String?
public let description: String?
public let hasOrganizationProjects: Bool?
public let hasRepositoryProjects: Bool?
public let defaultRepositoryPermissions: String? // TODO: strong type
public let membersCanCreateRepositories: Bool?
public init(billingEmail: String? = nil,
company: String? = nil,
email: String? = nil,
location: String? = nil,
name: String? = nil,
description: String? = nil,
hasOrganizationProjects: Bool? = nil,
hasRepositoryProjects: Bool? = nil,
defaultRepositoryPermissions: String? = nil,
membersCanCreateRepositories: Bool? = nil) {
self.billingEmail = billingEmail
self.company = company
self.email = email
self.location = location
self.name = name
self.description = description
self.hasOrganizationProjects = hasOrganizationProjects
self.hasRepositoryProjects = hasRepositoryProjects
self.defaultRepositoryPermissions = defaultRepositoryPermissions
self.membersCanCreateRepositories = membersCanCreateRepositories
}
}
extension OrganizationUpdate {
enum CodingKeys: String, CodingKey {
case billingEmail = "billing_email"
case company
case email
case location
case name
case description
case hasOrganizationProjects = "has_organization_projects"
case hasRepositoryProjects = "has_repository_projects"
case defaultRepositoryPermissions = "default_repository_permissions"
case membersCanCreateRepositories = "members_can_create_repositories"
}
}
| mit | 7c8912095f4e63c41e7b99e40e1d9441 | 31.389831 | 73 | 0.70853 | 4.887468 | false | false | false | false |
omaralbeik/SwifterSwift | Tests/SwiftStdlibTests/SignedNumericExtensionsTests.swift | 1 | 1242 | //
// SignedNumericExtensionsTests.swift
// SwifterSwift
//
// Created by Omar Albeik on 10/7/17.
// Copyright © 2017 SwifterSwift
//
import XCTest
@testable import SwifterSwift
final class SignedNumericExtensionsTests: XCTestCase {
func testString() {
let number1: Double = -1.2
XCTAssertEqual(number1.string, "-1.2")
let number2: Float = 2.3
XCTAssertEqual(number2.string, "2.3")
}
func testAsLocaleCurrency() {
let number1: Double = 3.2
XCTAssertEqual(number1.asLocaleCurrency, "$3.20")
let number2 = Double(10.23)
if let symbol = Locale.current.currencySymbol {
XCTAssertNotNil(number2.asLocaleCurrency!)
XCTAssert(number2.asLocaleCurrency!.contains(symbol))
}
XCTAssertNotNil(number2.asLocaleCurrency!)
XCTAssert(number2.asLocaleCurrency!.contains("\(number2)"))
let number3 = 10
if let symbol = Locale.current.currencySymbol {
XCTAssertNotNil(number3.asLocaleCurrency)
XCTAssert(number3.asLocaleCurrency!.contains(symbol))
}
XCTAssertNotNil(number3.asLocaleCurrency)
XCTAssert(number3.asLocaleCurrency!.contains("\(number3)"))
}
}
| mit | caca165912be56fbd916c083ed92c3e3 | 27.860465 | 67 | 0.65834 | 4.613383 | false | true | false | false |
AgaKhanFoundation/WCF-iOS | Pods/FirebaseCoreInternal/FirebaseCore/Internal/Sources/HeartbeatLogging/StorageFactory.swift | 3 | 2453 | // Copyright 2021 Google 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 Foundation
private enum Constants {
/// The name of the file system directory where heartbeat data is stored.
static let heartbeatFileStorageDirectoryPath = "google-heartbeat-storage"
/// The name of the user defaults suite where heartbeat data is stored.
static let heartbeatUserDefaultsSuiteName = "com.google.heartbeat.storage"
}
/// A factory type for `Storage`.
protocol StorageFactory {
static func makeStorage(id: String) -> Storage
}
// MARK: - FileStorage + StorageFactory
extension FileStorage: StorageFactory {
static func makeStorage(id: String) -> Storage {
let rootDirectory = FileManager.default.applicationSupportDirectory
let heartbeatDirectoryPath = Constants.heartbeatFileStorageDirectoryPath
// Sanitize the `id` so the heartbeat file name does not include a ":".
let sanitizedID = id.replacingOccurrences(of: ":", with: "_")
let heartbeatFilePath = "heartbeats-\(sanitizedID)"
let storageURL = rootDirectory
.appendingPathComponent(heartbeatDirectoryPath, isDirectory: true)
.appendingPathComponent(heartbeatFilePath, isDirectory: false)
return FileStorage(url: storageURL)
}
}
extension FileManager {
var applicationSupportDirectory: URL {
urls(for: .applicationSupportDirectory, in: .userDomainMask).first!
}
}
// MARK: - UserDefaultsStorage + StorageFactory
extension UserDefaultsStorage: StorageFactory {
static func makeStorage(id: String) -> Storage {
let suiteName = Constants.heartbeatUserDefaultsSuiteName
// It's safe to force unwrap the below defaults instance because the
// initializer only returns `nil` when the bundle id or `globalDomain`
// is passed in as the `suiteName`.
let defaults = UserDefaults(suiteName: suiteName)!
let key = "heartbeats-\(id)"
return UserDefaultsStorage(defaults: defaults, key: key)
}
}
| bsd-3-clause | b7b96f7f5213a0016b214cb2b670108e | 36.166667 | 76 | 0.748471 | 4.753876 | false | false | false | false |
audiokit/AudioKit | Sources/AudioKit/MIDI/Listeners/MIDIObserverMaster.swift | 3 | 1581 | // Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
import Foundation
/// Observer protocol
public protocol ObserverProtocol {
/// Equality test
/// - Parameter listener: Another listener
func isEqualTo(_ listener: ObserverProtocol) -> Bool
}
extension ObserverProtocol {
/// Equality test
/// - Parameter listener: Another listener
func isEqualTo(_ listener: ObserverProtocol) -> Bool {
return self == listener
}
}
func == (lhs: ObserverProtocol, rhs: ObserverProtocol) -> Bool {
return lhs.isEqualTo(rhs)
}
class MIDIObserverMaster<P> where P: ObserverProtocol {
var observers: [P] = []
/// Add an observer that conforms to the observer protocol
/// - Parameter observer: Object conforming to the observer protocol
public func addObserver(_ observer: P) {
observers.append(observer)
}
/// Remove an observer that conforms to the observer protocol
/// - Parameter observer: Object conforming to the observer protocol
public func removeObserver(_ observer: P) {
observers.removeAll { (anObserver: P) -> Bool in
return anObserver.isEqualTo(observer)
}
}
/// Remove all observers
public func removeAllObserver(_ observer: P) {
observers.removeAll()
}
/// Do something to all observers
/// - Parameter block: Block to call on each observer
public func forEachObserver(_ block: (P) -> Void ) {
observers.forEach { (observer) in
block(observer)
}
}
}
| mit | dfb018b81132603ce55ab91e2e62f30d | 28.277778 | 100 | 0.662872 | 4.864615 | false | false | false | false |
open-telemetry/opentelemetry-swift | Sources/Importers/SwiftMetricsShim/SwiftMetricsShim.swift | 1 | 4141 | /*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import CoreMetrics
import OpenTelemetryApi
public class OpenTelemetrySwiftMetrics: MetricsFactory {
internal let meter: Meter
internal var metrics = [MetricKey: SwiftMetric]()
internal let lock = Lock()
public init(meter: Meter) {
self.meter = meter
}
// MARK: - Make
/// Counter: A counter is a cumulative metric that represents a single monotonically increasing counter whose value can only increase or be reset to zero on
/// restart. For example, you can use a counter to represent the number of requests served, tasks completed, or errors.
public func makeCounter(label: String, dimensions: [(String, String)]) -> CounterHandler {
lock.withLock {
if let existing = metrics[.init(name: label, type: .counter)] {
return existing as! CounterHandler
}
let metric = SwiftCounterMetric(name: label, labels: dimensions.dictionary, meter: meter)
storeMetric(metric)
return metric
}
}
/// Recorder: A recorder collects observations within a time window (usually things like response sizes) and can provide aggregated information about the
/// data sample, for example count, sum, min, max and various quantiles.
///
/// Gauge: A Gauge is a metric that represents a single numerical value that can arbitrarily go up and down. Gauges are typically used for measured values
/// like temperatures or current memory usage, but also "counts" that can go up and down, like the number of active threads. Gauges are modeled as a
/// Recorder with a sample size of 1 that does not perform any aggregation.
public func makeRecorder(label: String, dimensions: [(String, String)], aggregate: Bool) -> RecorderHandler {
lock.withLock {
if let existing = metrics[.init(name: label, type: .histogram)] {
return existing as! RecorderHandler
}
if let existing = metrics[.init(name: label, type: .gauge)] {
return existing as! RecorderHandler
}
let metric: SwiftMetric & RecorderHandler = aggregate ?
SwiftHistogramMetric(name: label, labels: dimensions.dictionary, meter: meter) :
SwiftGaugeMetric(name: label, labels: dimensions.dictionary, meter: meter)
storeMetric(metric)
return metric
}
}
/// Timer: A timer collects observations within a time window (usually things like request duration) and provides aggregated information about the data sample,
/// for example min, max and various quantiles. It is similar to a Recorder but specialized for values that represent durations.
public func makeTimer(label: String, dimensions: [(String, String)]) -> TimerHandler {
lock.withLock {
if let existing = metrics[.init(name: label, type: .summary)] {
return existing as! TimerHandler
}
let metric = SwiftSummaryMetric(name: label, labels: dimensions.dictionary, meter: meter)
storeMetric(metric)
return metric
}
}
private func storeMetric(_ metric: SwiftMetric) {
metrics[.init(name: metric.metricName, type: metric.metricType)] = metric
}
// MARK: - Destroy
public func destroyCounter(_ handler: CounterHandler) {
destroyMetric(handler as? SwiftMetric)
}
public func destroyRecorder(_ handler: RecorderHandler) {
destroyMetric(handler as? SwiftMetric)
}
public func destroyTimer(_ handler: TimerHandler) {
destroyMetric(handler as? SwiftMetric)
}
private func destroyMetric(_ metric: SwiftMetric?) {
lock.withLock {
if let name = metric?.metricName, let type = metric?.metricType {
metrics.removeValue(forKey: .init(name: name, type: type))
}
}
}
}
| apache-2.0 | aef39c71a94ff1b1f0872864f1ad8d8c | 40 | 163 | 0.634388 | 5.043849 | 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.