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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Elm-Tree-Island/Shower | Shower/Carthage/Checkouts/ReactiveCocoa/ReactiveCocoaTests/AppKit/NSImageViewSpec.swift | 4 | 1232 | import Quick
import Nimble
import ReactiveSwift
import ReactiveCocoa
import AppKit
import enum Result.NoError
class NSImageViewSpec: QuickSpec {
override func spec() {
var imageView: NSImageView!
weak var _imageView: NSImageView?
beforeEach {
imageView = NSImageView(frame: .zero)
_imageView = imageView
}
afterEach {
imageView = nil
expect(_imageView).to(beNil())
}
it("should accept changes from bindings to its enabling state") {
imageView.isEnabled = false
let (pipeSignal, observer) = Signal<Bool, NoError>.pipe()
imageView.reactive.isEnabled <~ SignalProducer(pipeSignal)
observer.send(value: true)
expect(imageView.isEnabled) == true
observer.send(value: false)
expect(imageView.isEnabled) == false
}
it("should accept changes from bindings to its image") {
let (pipeSignal, observer) = Signal<NSImage?, NoError>.pipe()
imageView.reactive.image <~ SignalProducer(pipeSignal)
#if swift(>=4.0)
let theImage = NSImage(named: .user)
#else
let theImage = NSImage(named: NSImageNameUser)
#endif
observer.send(value: theImage)
expect(imageView.image) == theImage
observer.send(value: nil)
expect(imageView.image).to(beNil())
}
}
}
| gpl-3.0 | b698aedeb35cbde0d8b0f88112664191 | 21.4 | 67 | 0.709416 | 3.767584 | false | false | false | false |
christophhagen/Signal-iOS | Signal/src/views/AudioProgressView.swift | 1 | 2715 | //
// Copyright (c) 2017 Open Whisper Systems. All rights reserved.
//
import UIKit
import SignalServiceKit
@objc class AudioProgressView: UIView {
override var bounds: CGRect {
didSet {
if oldValue != bounds {
updateSubviews()
}
}
}
override var frame: CGRect {
didSet {
if oldValue != frame {
updateSubviews()
}
}
}
var horizontalBarColor = UIColor.black {
didSet {
updateContent()
}
}
var progressColor = UIColor.blue {
didSet {
updateContent()
}
}
private let horizontalBarLayer: CAShapeLayer
private let progressLayer: CAShapeLayer
var progress: CGFloat = 0 {
didSet {
if oldValue != progress {
updateContent()
}
}
}
@available(*, unavailable, message:"use other constructor instead.")
required init?(coder aDecoder: NSCoder) {
fatalError("\(#function) is unimplemented.")
}
public required init() {
self.horizontalBarLayer = CAShapeLayer()
self.progressLayer = CAShapeLayer()
super.init(frame:CGRect.zero)
self.layer.addSublayer(self.horizontalBarLayer)
self.layer.addSublayer(self.progressLayer)
}
internal func updateSubviews() {
AssertIsOnMainThread()
self.horizontalBarLayer.frame = self.bounds
self.progressLayer.frame = self.bounds
updateContent()
}
internal func updateContent() {
AssertIsOnMainThread()
let horizontalBarPath = UIBezierPath()
let horizontalBarHeightFraction = CGFloat(0.25)
let horizontalBarHeight = bounds.size.height * horizontalBarHeightFraction
horizontalBarPath.append(UIBezierPath(rect: CGRect(x: 0, y:(bounds.size.height - horizontalBarHeight) * 0.5, width:bounds.size.width, height:horizontalBarHeight)))
horizontalBarLayer.path = horizontalBarPath.cgPath
horizontalBarLayer.fillColor = horizontalBarColor.cgColor
let progressHeight = bounds.self.height
let progressWidth = progressHeight * 0.15
let progressX = (bounds.self.width - progressWidth) * max(0.0, min(1.0, progress))
let progressBounds = CGRect(x:progressX, y:0, width:progressWidth, height:progressHeight)
let progressCornerRadius = progressWidth * 0.5
let progressPath = UIBezierPath()
progressPath.append(UIBezierPath(roundedRect: progressBounds, cornerRadius: progressCornerRadius))
progressLayer.path = progressPath.cgPath
progressLayer.fillColor = progressColor.cgColor
}
}
| gpl-3.0 | 0e321d9bef3453babf7e2960894ba3db | 28.193548 | 171 | 0.634991 | 5.151803 | false | false | false | false |
ggu/SimpleGridView | SimpleGridView/views/TileView.swift | 1 | 955 | //
// TileView.swift
// SimpleGridView
//
// Created by Gabriel Uribe on 11/25/15.
//
import UIKit
var TILE_WIDTH = 40
var TILE_HEIGHT = 40
var TILE_MARGIN = 1
internal class TileView : UIView {
private var tile : Tile
override init(frame: CGRect) {
tile = Tile()
super.init(frame: frame)
backgroundColor = Color.inactiveTile
}
func setActive() {
backgroundColor = Color.activeTile
tile.setActive()
}
func reset() {
backgroundColor = Color.inactiveTile
tile.reset()
}
func containsPoint(point: CGPoint) -> Bool {
return frame.contains(point)
}
static func changeTileWidth(width: Int) {
TILE_WIDTH = width
}
static func changeTileHeight(height: Int) {
TILE_HEIGHT = height
}
static func changeTileMargin(margin: Int) {
TILE_MARGIN = margin
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | f1ca71640a85b9221bc12002266989c9 | 17.365385 | 55 | 0.650262 | 3.715953 | false | false | false | false |
leoneparise/iLog | iLogUI/TimelineViewController.swift | 1 | 8905 | //
// TimelineViewController.swift
// StumpExample
//
// Created by Leone Parise Vieira da Silva on 05/05/17.
// Copyright © 2017 com.leoneparise. All rights reserved.
//
import UIKit
open class TimelineViewController: UITableViewController {
public var dataSource:TimelineDatasource!
private var searchController:UISearchController!
private var logManager:LogManager!
fileprivate var logLevel = LogLevel.debug {
didSet { refresh() }
}
fileprivate var searchText:String? = nil {
didSet { refresh() }
}
override open func viewDidLoad() {
super.viewDidLoad()
title = "Log Viewer"
// Configure log manager
logManager = LogManager.shared
NotificationCenter.default
.addObserver(self,
selector: #selector(didLog(notification:)),
name: Notification.Name.LogManagerDidLog,
object: nil)
// Configure datasource
if dataSource == nil {
dataSource = TimelineDatasource()
}
dataSource.configureCell = { cell, entry, isLast in
guard let entryCell = cell as? TimelineTableViewCell else { return }
entryCell.configure(TimelineTableViewCell.ViewModel(entry: entry, isLast: isLast))
}
dataSource.didSet = { [unowned self] _ in
self.tableView.reloadData()
}
dataSource.didAppend = { [unowned self] changes in
self.tableView.reloadData()
}
dataSource.didInsert = { [unowned self] changes in
let addChanges = changes.filter{ $0.type == .add }
let updateChanges = changes.filter{ $0.type == .sectionUpdate }
self.apply(changes: addChanges, withAddAnimation: .top)
self.apply(changes: updateChanges)
}
tableView.dataSource = dataSource
tableView.delegate = self
tableView.estimatedRowHeight = 70
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedSectionHeaderHeight = 50
tableView.tableFooterView = UIView()
tableView.keyboardDismissMode = .onDrag
// Register cell
let bundle = Bundle(for: TimelineViewController.self)
let cellNib = UINib(nibName: "TimelineTableViewCell", bundle: bundle)
tableView.register(cellNib, forCellReuseIdentifier: TimelineDatasource.cellIdentifier)
// Configure navigation bar
let closeButton = CloseButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
closeButton.padding = 6
closeButton.lineWidth = 2
closeButton.addTarget(self, action: #selector(close), for: .touchUpInside)
self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: closeButton)
let filterButton = FilterButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
filterButton.padding = 5
filterButton.lineWidth = 2
filterButton.spacing = 5
filterButton.addTarget(self, action: #selector(showActions), for: .touchUpInside)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: filterButton)
// Configure the search controller
searchController = UISearchController(searchResultsController: nil)
searchController.searchResultsUpdater = self
searchController.searchBar.placeholder = "Search logs"
searchController.searchBar.autocorrectionType = .no
searchController.searchBar.autocapitalizationType = .none
searchController.dimsBackgroundDuringPresentation = false
searchController.hidesNavigationBarDuringPresentation = false
navigationItem.titleView = searchController.searchBar
// Sets this view controller as presenting view controller for the search interface
definesPresentationContext = true
}
override open func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
logManager.filter(level: logLevel, text: searchText) { entries in
self.dataSource.set(entries: entries ?? [])
}
}
override open func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = TimelineTableViewHeader.fromNib()
view.isFirst = section == 0
view.date = dataSource.getGroup(forSection: section).timestamp
return view
}
override open func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let (section, row) = (indexPath.section, indexPath.row)
let rowCount = dataSource.count(forSection: section)
if section >= max(0, (2 / 3) * dataSource.count)
&& row >= max(0, (2 / 3) * rowCount) {
logManager.filter(level: logLevel, text: searchText, offset: dataSource.offset) { [weak self] entries in
self?.dataSource.append(entries: entries ?? [])
}
}
}
override open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: false)
guard
let cell = tableView.cellForRow(at: indexPath) as? TimelineTableViewCellType
else { return }
self.tableView.beginUpdates()
cell.expanded = !cell.expanded
self.tableView.endUpdates()
}
// MARK: - Selectors
@objc private func close() {
if let nav = self.navigationController {
nav.dismiss(animated: true, completion: nil)
} else {
self.dismiss(animated: true, completion: nil)
}
}
@objc private func clear() {
logManager.clear()
refresh()
}
@objc private func didLog(notification:Notification) {
guard let entry = notification.object as? LogEntry else { return }
// We shouldn't add new logs if there is a search happening
if entry.level >= logLevel && (searchText?.isEmpty ?? true) && !searchController.isActive {
self.dataSource.prepend(entries: [entry])
}
}
private func apply(changes:[Change], withAddAnimation addAnimation: UITableView.RowAnimation = .top) {
self.tableView.beginUpdates()
for change in changes {
if change.createSection {
self.tableView.insertSections([change.indexPath.section], with: addAnimation)
}
switch change.type {
case .add: self.tableView.insertRows(at: [change.indexPath], with: addAnimation)
case .update: self.tableView.reloadRows(at: [change.indexPath], with: .none)
case .sectionUpdate: self.tableView.reloadSections([change.indexPath.section], with: .none)
}
}
self.tableView.endUpdates()
}
fileprivate func refresh() {
logManager.filter(level: logLevel, text: searchText) { [weak self] entries in
self?.dataSource.set(entries: entries ?? [])
}
}
@objc private func showActions() {
func createAction(level:LogLevel) -> UIAlertAction {
let isSelected = logLevel == level
let title = isSelected ? "- \(level.stringValue) -" : level.stringValue
let action = UIAlertAction(title: title, style: .default) { [unowned self] _ in
self.logLevel = level
}
action.isEnabled = !isSelected
return action
}
let alert = UIAlertController(title: nil, message: "Log level", preferredStyle: .actionSheet)
alert.addAction(createAction(level: .debug))
alert.addAction(createAction(level: .info))
alert.addAction(createAction(level: .warn))
alert.addAction(createAction(level: .error))
alert.addAction(UIAlertAction(title: "Clear logs", style: .destructive, handler: { (_) in
self.clear()
}))
alert.addAction(UIAlertAction(title: "Close", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
extension TimelineViewController: UISearchResultsUpdating {
public func updateSearchResults(for searchController: UISearchController) {
performTrottled(label: "search", delay: 0.5) { [weak self] in
guard let text = searchController.searchBar.text, !text.isEmpty else {
self?.searchText = nil
return
}
self?.searchText = text
}
}
}
| mit | 462993b95359ea56e638e4dd188a7670 | 37.37931 | 126 | 0.618037 | 5.243816 | false | false | false | false |
bustoutsolutions/siesta | Source/Siesta/Request/Request.swift | 1 | 11400 | //
// Request.swift
// Siesta
//
// Created by Paul on 2015/7/20.
// Copyright © 2016 Bust Out Solutions. All rights reserved.
//
import Foundation
/**
HTTP request methods.
See the various `Resource.request(...)` methods.
*/
public enum RequestMethod: String, CaseIterable
{
/// OPTIONS
case options
/// GET
case get
/// HEAD. The HTTP method, not the body part.
case head
/// POST. Just POST. Doc comment is the same as the enum.
case post
/// So you’re really reading the docs for all these, huh?
case put
/// OK then, I’ll reward your diligence. Or punish it, depending on your level of refinement.
///
/// What’s the difference between a poorly maintained Greyhound terminal and a lobster with breast implants?
case patch
/// One’s a crusty bus station, and the other’s a busty crustacean.
///
/// I’m here all week! Thank you for reading the documentation!
case delete
}
/**
An API request. Provides notification hooks about the status of the request, and allows cancellation.
Note that this represents only a _single request_, whereas `ResourceObserver`s receive notifications about
_all_ resource load requests, no matter who initiated them. Note also that these hooks are available for _all_
requests, whereas `ResourceObserver`s only receive notifications about changes triggered by `load()`, `loadIfNeeded()`,
and `overrideLocalData(...)`.
`Request` guarantees that it will call any given callback _at most_ one time.
Callbacks are always called on the main thread.
- Note:
There is no race condition between a callback being added and a response arriving. If you add a callback after the
response has already arrived, the callback is still called as usual. In other words, when attaching a hook, you
**do not need to worry** about where the request is in its lifecycle. Except for how soon it’s called, your hook
will see the same behavior regardless of whether the request has not started yet, is in progress, or is completed.
*/
public protocol Request: AnyObject
{
/**
Call the closure once when the request finishes for any reason.
*/
@discardableResult
func onCompletion(_ callback: @escaping (ResponseInfo) -> Void) -> Request
/// Call the closure once if the request succeeds.
@discardableResult
func onSuccess(_ callback: @escaping (Entity<Any>) -> Void) -> Request
/// Call the closure once if the request succeeds and the data changed.
@discardableResult
func onNewData(_ callback: @escaping (Entity<Any>) -> Void) -> Request
/// Call the closure once if the request succeeds with a 304.
@discardableResult
func onNotModified(_ callback: @escaping () -> Void) -> Request
/// Call the closure once if the request fails for any reason.
@discardableResult
func onFailure(_ callback: @escaping (RequestError) -> Void) -> Request
/**
Immediately start this request if it was deferred. Does nothing if the request is already started.
You rarely need to call this method directly, because most requests are started for you automatically:
- Any request you receive from `Resource.request(...)` or `Resource.load()` is already started.
- Requests start automatically when you use `RequestChainAction.passTo` in a chain.
When do you need this method, then? It’s rare. There are two situations:
- `Configuration.decorateRequests(...)` can defer a request by hanging on to it while returning a different request.
You can use this method to manually start a request that was deferred this way.
- `Request.repeated()` does not automatically start the request it returns. This is to allow you to implement
time-delayed retries.
*/
@discardableResult
func start() -> Request
/**
Indicates whether this request is waiting to be started, in progress, or completed and has a response already.
- Note:
It is _always_ valid to call any of `Request`’s methods, including hooks (`onCompletion(...)` and friends),
no matter what state the request is in. You do not need to defensively check this property before working with
a request; in fact, if you find yourself wanting it at all, you are probably doing something awkward and
unnecessarily complicated.
*/
var state: RequestState { get }
/**
An estimate of the progress of the request, taking into account request transfer, response transfer, and latency.
Result is either in [0...1], or is NAN if insufficient information is available.
The property will always be 1 if a request is completed. Note that the converse is not true: a value of 1 does
not necessarily mean the request is completed; it means only that we estimate the request _should_ be completed
by now. Use the `isCompleted` property to test for actual completion.
*/
var progress: Double { get }
/**
Call the given closure with progress updates at regular intervals while the request is in progress.
Will _always_ receive a call with a value of 1 when the request completes.
*/
@discardableResult
func onProgress(_ callback: @escaping (Double) -> Void) -> Request
/**
Cancel the request if it is still in progress. Has no effect if a response has already been received.
If this method is called while the request is in progress, it immediately triggers the `failure`/`completion`
callbacks, with the error’s `cause` set to `RequestError.Cause.RequestCancelled`.
Note that `cancel()` is not guaranteed to stop the request from reaching the server. In fact, it is not guaranteed
to have any effect at all on the underlying request, subject to the whims of the `NetworkingProvider`. Therefore,
after calling this method on a mutating request (POST, PUT, etc.), you should consider the service-side state of
the resource to be unknown. Is it safest to immediately call either `Resource.load()` or `Resource.wipe()`.
This method _does_ guarantee, however, that after it is called, even if a network response does arrive it will be
ignored and not trigger any callbacks.
*/
func cancel()
/**
Send the same request again, returning a new `Request` instance for the new attempt. You can combine this with
`Request.chained(...)` to retry failed requests with updated headers.
The returned request is **not** already started. You must call `start()` when you are ready for it to begin.
- Warning:
Use with caution! Repeating a failed request for any HTTP method other than GET is potentially unsafe,
because you do not always know whether the server processed your request before the error occurred. **Ensure
that it is safe to repeat a request before calling this method.**
This method picks up certain contextual changes:
- It **will** honor any changes to `Configuration.headers` made since the original request.
- It **will** rerun the `requestMutation` closure you passed to `Resource.request(...)` (if you passed one).
- It **will not** redecorate the request, and **will not** pick up any changes to
`Configuration.decorateRequests(...)` since the original call. This is so that a request wrapper can safely
retry its nested request without triggering a brain-bending hall of mirrors effect.
Note that this means the new request may not be indentical to the original one.
- Warning:
Because `repeated()` will pick up header changes from configuration, it is possible for a request to run
again with different auth credentials. This is intentional: one of the primary use cases for this dangerous
method is automatically retrying a request with an updated auth token. However, the onus is on you to ensure
that you do not hold on to and repeat a request after a user logs out. Put those safety goggles on.
- Note:
The new `Request` does **not** attach all the callbacks (e.g. `onCompletion(_:)`) from the old one.
Doing so would violate the API contract of `Request` that any callback will be called at most once.
After calling `repeated()`, you will need to attach new callbacks to the new request. Otherwise nobody will
hear about the response when it arrives. (Q: If a request completes and nobody’s around to hear it, does it
make a response? A: Yes, because it still uses bandwidth, and potentially changes state on the server.)
By the same principle, repeating a `load()` request will trigger a second network call, but will not cause the
resource’s state to be updated again with the result.
*/
func repeated() -> Request
}
/**
Indicates whether a `Request` has been started, and whether it has completed.
- SeeAlso: `Request.state`
*/
public enum RequestState
{
/**
The request is frozen, waiting for a call to `Request.start()`. You can still attach completion hooks to this
request, but they will not be called until the request stars.
*/
case notStarted
/**
The request has started, and is waiting for a response. Its state will eventually transition to `completed`.
*/
case inProgress
/**
The request has a response, and its state will note change any further. A request may be in this state because it
received and handled a server response, encountered a pre-request client-side side error, or was cancelled.
*/
case completed
}
/**
The outcome of a network request: either success (with an entity representing the resource’s current state), or
failure (with an error).
*/
public typealias Response = Result<Entity<Any>, RequestError>
extension Response
{
/// True if this is a cancellation response
public var isCancellation: Bool
{
if case .failure(let error) = self
{ return error.cause is RequestError.Cause.RequestCancelled }
else
{ return false }
}
}
extension Response: CustomStringConvertible
{
/// :nodoc:
public var description: String
{
switch self
{
case .success(let value): return debugStr(value)
case .failure(let value): return debugStr(value)
}
}
}
/// A `Response`, plus metadata about the nature of the response.
public struct ResponseInfo
{
/// The result of a `Request`.
public var response: Response
/// Indicates whether `response` is newly received data, or the resource’s existing data reused.
/// Used to distinguish `ResourceEvent.newData` from `ResourceEvent.notModified`.
public var isNew: Bool
/// Creates new responseInfo, with `isNew` true by default.
public init(response: Response, isNew: Bool = true)
{
self.response = response
self.isNew = isNew
}
internal static let cancellation =
ResponseInfo(
response: .failure(RequestError(
userMessage: NSLocalizedString("Request cancelled", comment: "userMessage"),
cause: RequestError.Cause.RequestCancelled(networkError: nil))))
}
| mit | b6f2a69c0671b06efafc2a6e9a52e386 | 41.588015 | 122 | 0.689825 | 4.801943 | false | false | false | false |
smartystreets/smartystreets-ios-sdk | Sources/SmartyStreets/USExtract/USExtractLookup.swift | 1 | 1350 | import Foundation
@objcMembers public class USExtractLookup: NSObject, Codable {
// In addition to holding all of the input data for this lookup, this class also will contain the result
// of the lookup after it comes back from the API.
//
// See "https://smartystreets.com/docs/cloud/us-extract-api#http-request-input-fields"
public var result:USExtractResult?
public var html:Bool?
public var aggressive:Bool?
public var addressesHaveLineBreaks:Bool?
public var addressesPerLine:Int?
public var text:String?
override public init() {
self.aggressive = false
self.addressesHaveLineBreaks = true
self.addressesPerLine = 0
}
public func withText(text: String) -> USExtractLookup {
self.text = text
return self
}
public func specifyHtmlInput(html: Bool) {
self.html = html
}
public func setAggressive(aggressive: Bool) {
self.aggressive = aggressive
}
public func isHtml() -> Bool {
if let html = self.html {
return html
} else {
return false
}
}
public func isAggressive() -> Bool {
if let aggressive = self.aggressive {
return aggressive
} else {
return false
}
}
}
| apache-2.0 | d2078ba1d0e087a40a6b4adca32cdd0d | 26 | 111 | 0.604444 | 4.340836 | false | false | false | false |
creister/SwiftCharts | Examples/Examples/EqualSpacingExample.swift | 3 | 2969 | //
// EqualSpacingExample.swift
// SwiftCharts
//
// Created by ischuetz on 04/05/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
import SwiftCharts
class EqualSpacingExample: UIViewController {
private var chart: Chart? // arc
override func viewDidLoad() {
super.viewDidLoad()
let labelSettings = ChartLabelSettings(font: ExamplesDefaults.labelFont)
let chartPoints = [
ChartPoint(x: ChartAxisValueDoubleScreenLoc(screenLocDouble: 1, actualDouble: 2, labelSettings: labelSettings), y: ChartAxisValueDouble(2)),
ChartPoint(x: ChartAxisValueDoubleScreenLoc(screenLocDouble: 2, actualDouble: 100, labelSettings: labelSettings), y: ChartAxisValueDouble(5)),
ChartPoint(x: ChartAxisValueDoubleScreenLoc(screenLocDouble: 3, actualDouble: 100.1, labelSettings: labelSettings), y: ChartAxisValueDouble(1)),
ChartPoint(x: ChartAxisValueDoubleScreenLoc(screenLocDouble: 4, actualDouble: 900000, labelSettings: labelSettings), y: ChartAxisValueDouble(10))
]
let xValues = chartPoints.map{$0.x}
let yValues = ChartAxisValuesGenerator.generateYAxisValuesWithChartPoints(chartPoints, minSegmentCount: 10, maxSegmentCount: 20, multiple: 2, axisValueGenerator: {ChartAxisValueDouble($0, labelSettings: labelSettings)}, addPaddingSegmentIfEdge: false)
let xModel = ChartAxisModel(axisValues: xValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings))
let yModel = ChartAxisModel(axisValues: yValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings.defaultVertical()))
let chartFrame = ExamplesDefaults.chartFrame(self.view.bounds)
let chartSettings = ExamplesDefaults.chartSettings
chartSettings.trailing = 40
let coordsSpace = ChartCoordsSpaceLeftBottomSingleAxis(chartSettings: chartSettings, chartFrame: chartFrame, xModel: xModel, yModel: yModel)
let (xAxis, yAxis, innerFrame) = (coordsSpace.xAxis, coordsSpace.yAxis, coordsSpace.chartInnerFrame)
let lineModel = ChartLineModel(chartPoints: chartPoints, lineColor: UIColor.redColor(), animDuration: 1, animDelay: 0)
let chartPointsLineLayer = ChartPointsLineLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, lineModels: [lineModel])
let settings = ChartGuideLinesDottedLayerSettings(linesColor: UIColor.blackColor(), linesWidth: ExamplesDefaults.guidelinesWidth)
let guidelinesLayer = ChartGuideLinesDottedLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, settings: settings)
let chart = Chart(
frame: chartFrame,
layers: [
xAxis,
yAxis,
guidelinesLayer,
chartPointsLineLayer
]
)
self.view.addSubview(chart.view)
self.chart = chart
}
}
| apache-2.0 | 93315a17511003c1ea7b1580a939bbca | 50.189655 | 259 | 0.707309 | 5.666031 | false | false | false | false |
awind/Pixel | Pixel/String+Extension.swift | 1 | 2677 | //
// String.swift
// Pixel
//
// Created by SongFei on 15/12/6.
// Copyright © 2015年 SongFei. All rights reserved.
//
import Foundation
extension String {
func indexOf(sub: String) -> Int? {
var pos: Int?
if let range = self.rangeOfString(sub) {
if !range.isEmpty {
pos = self.startIndex.distanceTo(range.startIndex)
}
}
return pos
}
subscript (r: Range<Int>) -> String {
get {
let startIndex = self.startIndex.advancedBy(r.startIndex)
let endIndex = self.startIndex.advancedBy(r.endIndex - r.startIndex)
return self[Range(start: startIndex, end: endIndex)]
}
}
func urlEncodedStringWithEncoding(encoding: NSStringEncoding) -> String {
let charactersToBeEscaped = ":/>&=;+!@#$()',*" as CFStringRef
let charactersToLeaveUnescaped = "[]." as CFStringRef
let str = self as NSString
let result = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, str as CFString, charactersToLeaveUnescaped, charactersToBeEscaped, CFStringConvertNSStringEncodingToEncoding(encoding)) as NSString
return result as String
}
func paramtersFromQueryString() -> Dictionary<String, String> {
var parameters = Dictionary<String, String>()
let scanner = NSScanner(string: self)
var key: NSString?
var value: NSString?
while !scanner.atEnd {
key = nil
scanner.scanUpToString("=", intoString: &key)
scanner.scanString("=", intoString: nil)
value = nil
scanner.scanUpToString("&", intoString: &value)
scanner.scanString("&", intoString: nil)
if key != nil && value != nil {
parameters.updateValue(value! as String, forKey: key! as String)
}
}
return parameters
}
func SHA1DigestWithKey(key: String) -> NSData {
let str = self.cStringUsingEncoding(NSUTF8StringEncoding)
let strLen = self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)
let digestLen = Int(CC_SHA1_DIGEST_LENGTH)
let result = UnsafeMutablePointer<Void>.alloc(digestLen)
let keyStr = key.cStringUsingEncoding(NSUTF8StringEncoding)!
let keyLen = key.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA1), keyStr, keyLen, str!, strLen, result)
return NSData(bytes: result, length: digestLen)
}
}
| apache-2.0 | bd2b37a05199fd400289ccaf9911a0e5 | 31.609756 | 214 | 0.596859 | 5.182171 | false | false | false | false |
BluechipSystems/viper-module-generator | VIPERGenDemo/VIPERGenDemo/Libraries/Swifter/Swifter/SwifterOAuthClient.swift | 4 | 8064 | //
// SwifterOAuthClient.swift
// Swifter
//
// Copyright (c) 2014 Matt Donnelly.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import Accounts
internal class SwifterOAuthClient: SwifterClientProtocol {
struct OAuth {
static let version = "1.0"
static let signatureMethod = "HMAC-SHA1"
}
var consumerKey: String
var consumerSecret: String
var credential: SwifterCredential?
var dataEncoding: NSStringEncoding
init(consumerKey: String, consumerSecret: String) {
self.consumerKey = consumerKey
self.consumerSecret = consumerSecret
self.dataEncoding = NSUTF8StringEncoding
}
init(consumerKey: String, consumerSecret: String, accessToken: String, accessTokenSecret: String) {
self.consumerKey = consumerKey
self.consumerSecret = consumerSecret
let credentialAccessToken = SwifterCredential.OAuthAccessToken(key: accessToken, secret: accessTokenSecret)
self.credential = SwifterCredential(accessToken: credentialAccessToken)
self.dataEncoding = NSUTF8StringEncoding
}
func get(path: String, baseURL: NSURL, parameters: Dictionary<String, AnyObject>, uploadProgress: SwifterHTTPRequest.UploadProgressHandler?, downloadProgress: SwifterHTTPRequest.DownloadProgressHandler?, success: SwifterHTTPRequest.SuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let url = NSURL(string: path, relativeToURL: baseURL)!
let method = "GET"
let request = SwifterHTTPRequest(URL: url, method: method, parameters: parameters)
request.headers = ["Authorization": self.authorizationHeaderForMethod(method, url: url, parameters: parameters, isMediaUpload: false)]
request.downloadProgressHandler = downloadProgress
request.successHandler = success
request.failureHandler = failure
request.dataEncoding = self.dataEncoding
request.start()
}
func post(path: String, baseURL: NSURL, var parameters: Dictionary<String, AnyObject>, uploadProgress: SwifterHTTPRequest.UploadProgressHandler?, downloadProgress: SwifterHTTPRequest.DownloadProgressHandler?, success: SwifterHTTPRequest.SuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) {
let url = NSURL(string: path, relativeToURL: baseURL)!
let method = "POST"
var postData: NSData?
var postDataKey: String?
if let key: AnyObject = parameters[Swifter.DataParameters.dataKey] {
if let keyString = key as? String {
postDataKey = keyString
postData = parameters[postDataKey!] as? NSData
parameters.removeValueForKey(Swifter.DataParameters.dataKey)
parameters.removeValueForKey(postDataKey!)
}
}
var postDataFileName: String?
if let fileName: AnyObject = parameters[Swifter.DataParameters.fileNameKey] {
if let fileNameString = fileName as? String {
postDataFileName = fileNameString
parameters.removeValueForKey(fileNameString)
}
}
let request = SwifterHTTPRequest(URL: url, method: method, parameters: parameters)
request.headers = ["Authorization": self.authorizationHeaderForMethod(method, url: url, parameters: parameters, isMediaUpload: postData != nil)]
request.downloadProgressHandler = downloadProgress
request.successHandler = success
request.failureHandler = failure
request.dataEncoding = self.dataEncoding
request.encodeParameters = postData == nil
if postData != nil {
let fileName = postDataFileName ?? "media.jpg"
request.addMultipartData(postData!, parameterName: postDataKey!, mimeType: "application/octet-stream", fileName: fileName)
}
request.start()
}
func authorizationHeaderForMethod(method: String, url: NSURL, parameters: Dictionary<String, AnyObject>, isMediaUpload: Bool) -> String {
var authorizationParameters = Dictionary<String, AnyObject>()
authorizationParameters["oauth_version"] = OAuth.version
authorizationParameters["oauth_signature_method"] = OAuth.signatureMethod
authorizationParameters["oauth_consumer_key"] = self.consumerKey
authorizationParameters["oauth_timestamp"] = String(Int(NSDate().timeIntervalSince1970))
authorizationParameters["oauth_nonce"] = NSUUID().UUIDString
if self.credential?.accessToken != nil {
authorizationParameters["oauth_token"] = self.credential!.accessToken!.key
}
for (key, value: AnyObject) in parameters {
if key.hasPrefix("oauth_") {
authorizationParameters.updateValue(value, forKey: key)
}
}
let combinedParameters = authorizationParameters +| parameters
let finalParameters = isMediaUpload ? authorizationParameters : combinedParameters
authorizationParameters["oauth_signature"] = self.oauthSignatureForMethod(method, url: url, parameters: finalParameters, accessToken: self.credential?.accessToken)
var authorizationParameterComponents = authorizationParameters.urlEncodedQueryStringWithEncoding(self.dataEncoding).componentsSeparatedByString("&") as [String]
authorizationParameterComponents.sort { $0 < $1 }
var headerComponents = [String]()
for component in authorizationParameterComponents {
let subcomponent = component.componentsSeparatedByString("=") as [String]
if subcomponent.count == 2 {
headerComponents.append("\(subcomponent[0])=\"\(subcomponent[1])\"")
}
}
return "OAuth " + join(", ", headerComponents)
}
func oauthSignatureForMethod(method: String, url: NSURL, parameters: Dictionary<String, AnyObject>, accessToken token: SwifterCredential.OAuthAccessToken?) -> String {
var tokenSecret: NSString = ""
if token != nil {
tokenSecret = token!.secret.urlEncodedStringWithEncoding(self.dataEncoding)
}
let encodedConsumerSecret = self.consumerSecret.urlEncodedStringWithEncoding(self.dataEncoding)
let signingKey = "\(encodedConsumerSecret)&\(tokenSecret)"
var parameterComponents = parameters.urlEncodedQueryStringWithEncoding(self.dataEncoding).componentsSeparatedByString("&") as [String]
parameterComponents.sort { $0 < $1 }
let parameterString = join("&", parameterComponents)
let encodedParameterString = parameterString.urlEncodedStringWithEncoding(self.dataEncoding)
let encodedURL = url.absoluteString!.urlEncodedStringWithEncoding(self.dataEncoding)
let signatureBaseString = "\(method)&\(encodedURL)&\(encodedParameterString)"
let signature = signatureBaseString.SHA1DigestWithKey(signingKey)
return signatureBaseString.SHA1DigestWithKey(signingKey).base64EncodedStringWithOptions(nil)
}
}
| mit | bbedac488838165180897736ac6b4938 | 44.559322 | 304 | 0.710317 | 5.627355 | false | false | false | false |
NUKisZ/MyTools | MyTools/MyTools/Tools/ZKTools.swift | 1 | 20207 | //
// MyTools.swift
// MengWuShe
//
// Created by zhangk on 16/10/17.
// Copyright © 2016年 zhangk. All rights reserved.
//
import UIKit
//判断真机还是模拟器
struct Platform {
static let isSimulator: Bool = {
var isSim = false
#if arch(i386) || arch(x86_64)
isSim = true
#endif
return isSim
}()
}
extension UIColor{
class func colorWithRGBA(red r:CGFloat,green g:CGFloat,blue b:CGFloat, alpha a:CGFloat)->UIColor {
//返回一个颜色
return UIColor(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: a/1.0)
}
class func colorWithHexStringAndAlpha (hex: String, alpha:CGFloat) -> UIColor {
//接收到十六进制的颜色字符串和透明度,返回一个颜色
var cString: String = hex.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines).uppercased()
if (cString.hasPrefix("#")) {
cString = (cString as NSString).substring(from: 1)
}
if (cString.characters.count != 6) {
return UIColor.gray
}
let rString = (cString as NSString).substring(to: 2)
let gString = ((cString as NSString).substring(from: 2) as NSString).substring(to: 2)
let bString = ((cString as NSString).substring(from: 4) as NSString).substring(to: 2)
var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
Scanner(string: rString).scanHexInt32(&r)
Scanner(string: gString).scanHexInt32(&g)
Scanner(string: bString).scanHexInt32(&b)
return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: alpha)
}
}
class ZKTools: NSObject {
class func colorWithRGBA(red r:CGFloat,green g:CGFloat,blue b:CGFloat, alpha a:CGFloat)->UIColor {
//返回一个颜色
return UIColor(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: a/1.0)
}
class func colorWithHexString (hex: String) -> UIColor {
//接收到十六进制的颜色字符串,返回一个颜色
//var cs:String = hex.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines).uppercased()
var cString: String = hex.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines).uppercased()
if (cString.hasPrefix("#")) {
cString = (cString as NSString).substring(from: 1)
}
if (cString.characters.count != 6) {
return UIColor.gray
}
let rString = (cString as NSString).substring(to: 2)
let gString = ((cString as NSString).substring(from: 2) as NSString).substring(to: 2)
let bString = ((cString as NSString).substring(from: 4) as NSString).substring(to: 2)
var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
Scanner(string: rString).scanHexInt32(&r)
Scanner(string: gString).scanHexInt32(&g)
Scanner(string: bString).scanHexInt32(&b)
return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(1))
}
class func colorWithHexStringAndAlpha (hex: String, alpha:CGFloat) -> UIColor {
//接收到十六进制的颜色字符串和透明度,返回一个颜色
//var cs:String = hex.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines).uppercased()
var cString: String = hex.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines).uppercased()
if (cString.hasPrefix("#")) {
cString = (cString as NSString).substring(from: 1)
}
if (cString.characters.count != 6) {
return UIColor.gray
}
let rString = (cString as NSString).substring(to: 2)
let gString = ((cString as NSString).substring(from: 2) as NSString).substring(to: 2)
let bString = ((cString as NSString).substring(from: 4) as NSString).substring(to: 2)
var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
Scanner(string: rString).scanHexInt32(&r)
Scanner(string: gString).scanHexInt32(&g)
Scanner(string: bString).scanHexInt32(&b)
return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: alpha)
}
class func createButton(_ frame:CGRect,title:String?,imageName:String?,bgImageName:String?,target:AnyObject?,action:Selector?)->UIButton {
let btn = UIButton(type: .custom)
btn.frame = frame
if let btnTitle = title{
btn.setTitle(btnTitle, for: UIControlState())
btn.setTitleColor(UIColor.black, for: .normal)
}
if let btnImageName = imageName{
btn.setImage(UIImage(named: btnImageName), for: .normal)
}
if let btnBgImageName = bgImageName{
btn.setBackgroundImage(UIImage(named: btnBgImageName), for: .normal)
}
if let btnTarget = target {
if let btnAction = action{
btn.addTarget(btnTarget, action: btnAction, for: .touchUpInside)
}
}
return btn
}
class func createLabel(_ frame:CGRect,title:String?,textAlignment:NSTextAlignment?,font:UIFont?,textColor:UIColor?)->UILabel{
let label = UILabel(frame: frame)
if let labelTitle = title{
label.text = labelTitle
}
if let labelFont = font{
label.font = labelFont
}
if let labelTextColor = textColor{
label.textColor = labelTextColor
}
if let labelTextAlignment = textAlignment{
label.textAlignment = labelTextAlignment
}
return label
}
class func createImageView(_ frame:CGRect,imageName:String?,imageUrl:String?)->UIImageView{
let imageView = UIImageView(frame: frame)
if let name = imageName{
imageView.image = UIImage(named: name)
}
if let urlString = imageUrl{
let url = URL(string: urlString)
imageView.kf.setImage(with: url)
}
return imageView
}
class func alertViewCtroller(vc:UIViewController,title:String?,message:String?,cancelActionTitle:String?,sureActionTitle:String,action:((UIAlertAction)->Void)?){
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let sureAction = UIAlertAction(title: sureActionTitle, style: .default, handler: action)
_ = UIAlertAction(title: "", style: .cancel, handler: action)
alert.addAction(sureAction)
if let cancelString = cancelActionTitle{
let cancelAction = UIAlertAction(title: cancelString, style: .cancel, handler: nil)
alert.addAction(cancelAction)
}
vc.present(alert, animated: true, completion: nil)
}
class func showAlert(_ msg:String,onViewController vc :UIViewController){
let alert = UIAlertController(title: "提示", message: msg, preferredStyle: .alert)
let action = UIAlertAction(title: "确定", style: .default, handler: nil)
alert.addAction(action)
vc.present(alert, animated: true, completion: nil)
}
class func showAlertInWindowsLast(_ msg:String,onViewController vc :UIViewController){
// let window = UIApplication.shared.windows.last
// if (window?.isKind(of: UIViewController.self))!{
// let vc = window as UIViewController
// ZKTools.showAlert(msg, onViewController: vc)
// }
}
#if false
class func weiXinLogin(vc:UIViewController){
let req = SendAuthReq()
req.scope = "snsapi_userinfo"
req.state = "code"
WXApi.send(req)
}
class func login(vc:UIViewController){
//检测手机有没有安装微信
//1.在info.plist中把weixin和wechat加入白名单中
//2.在app中加入下面判断isWXAppInstalled是否安装微信
//3.isWXAppSupportApi当前版本是否支持
if(!WXApi.isWXAppInstalled())&&(!WXApi.isWXAppSupport()){
//检测到手机没有安装微信
let alert = UIAlertController(title: "登录", message: "您还没有登陆,是否登录?", preferredStyle: .alert)
let sureAction = UIAlertAction(title: "登录", style: .default) { (alert) in
//帐号登陆
let loginCtrl = LoginViewController()
vc.hidesBottomBarWhenPushed = true
loginCtrl.navigationController?.navigationBar.isHidden = false
vc.navigationController?.pushViewController(loginCtrl, animated: true)
vc.hidesBottomBarWhenPushed = false
}
alert.addAction(sureAction)
let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
alert.addAction(cancelAction)
vc.present(alert, animated: true, completion: nil)
}else{
//手机已安装微信并且版本支持
let alert = UIAlertController(title: "登录", message: "您还没有登陆,是否登录?", preferredStyle: .alert)
let sureAction = UIAlertAction(title: "登录", style: .default) { (alert) in
//微信登录
let req = SendAuthReq()
req.scope = "snsapi_userinfo"
req.state = "code"
WXApi.send(req)
}
alert.addAction(sureAction)
let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
alert.addAction(cancelAction)
vc.present(alert, animated: true, completion: nil)
}
}
#endif
#if false
//分享
class func shareClick(vc:UIViewController,title:String,desc:String,imageurl:String,urlString:String){
let aSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
var t:String = ""
var d:String = ""
var i:String = ""
if title == "title"{
t = "分享"
}else{
t = MyTools.urlEncodingToString(str: title)
}
if desc == "desc"{
d = "萌物社分享"
}else{
d = MyTools.urlEncodingToString(str: desc)
}
if imageurl == "imageurl"{
i = MWSShareImageUrl
}else{
i = imageurl
}
let weChatAction = UIAlertAction(title: "分享至微信", style: .default) {
(alert) in
let alert = UIAlertController(title: t, message: d, preferredStyle: .alert)
let friendsAction = UIAlertAction(title: "分享给好友", style: .default) { (alert) in
let message = WXMediaMessage()
message.title = t
message.description = d
message.setThumbImage(UIImage(named: "appIcon"))
let webPageObject = WXWebpageObject()
webPageObject.webpageUrl = urlString
message.mediaObject = webPageObject
let req = SendMessageToWXReq()
req.message = message
req.bText = false
req.scene = Int32(UInt32(WXSceneSession.rawValue))
WXApi.send(req)
}
alert.addAction(friendsAction)
let momentsAction = UIAlertAction(title: "分享到朋友圈", style: .default) { (alert) in
let message = WXMediaMessage()
message.title = t
message.description = d
message.setThumbImage(UIImage(named: "appIcon"))
let webPageObject = WXWebpageObject()
webPageObject.webpageUrl = urlString
message.mediaObject = webPageObject
let req = SendMessageToWXReq()
req.message = message
req.bText = false
req.scene = Int32(UInt32(WXSceneTimeline.rawValue))
WXApi.send(req)
}
alert.addAction(momentsAction)
let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
alert.addAction(cancelAction)
vc.present(alert, animated: true, completion: nil)
}
aSheet.addAction(weChatAction)
let tencent = UIAlertAction(title: "分享至QQ", style: .default) { (alert) in
shareTencent(urlString: urlString, title: t, desc: d, imageUrl: i)
}
aSheet.addAction(tencent)
let cancel = UIAlertAction(title: "取消", style: .cancel, handler: nil)
aSheet.addAction(cancel)
vc.present(aSheet, animated: true, completion: nil)
}
//分享到QQ好友
class func shareTencent(urlString:String,title:String,desc:String,imageUrl:String){
let shareUrl = QQApiURLObject(url: URL(string:urlString), title: title, description: desc, previewImageURL: URL(string:imageUrl), targetContentType: QQApiURLTargetTypeNews)
let req = SendMessageToQQReq(content: shareUrl)
QQApiInterface.send(req)
}
//微信支付
class func payWithWeiChat(partnerId:String,prepayId:String,package:String="Sign=WXPay",nonceStr:String,timeStamp:String,sign:String){
let request = PayReq()
request.partnerId = partnerId
request.prepayId = prepayId
request.package = package
request.nonceStr = nonceStr
request.timeStamp = UInt32(timeStamp)!
request.sign = sign
WXApi.send(request)
}
#endif
//data编码转字符串
class func stringWithData(data:Data)->String{
let string = (NSString(data: data, encoding: String.Encoding.utf8.rawValue))! as String
return string
}
//url编码转字符串
class func urlEncodingToString (str:String)->String{
let string = NSString(string: str).removingPercentEncoding
return string!
}
//字符串转url编码
class func stringToUrlEncoding(string:String)->String?{
return string.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!
}
class func httpToHttps(string:String)->String{
var str:String=string
if string.hasPrefix("http://"){
let arr = string.components(separatedBy: "http://")
str = "https://" + arr[1]
}
return str
}
//大图片得到小图片
class func getSamllImageWithBigImage(bigImage:UIImage,sizeChange:CGSize,compressionQuality:CGFloat=0.1,name:String="samllImage.jpeg")->Data?{
// var imageData = Data()
var image = bigImage
// imageData = UIImagePNGRepresentation(image)!
UIGraphicsBeginImageContextWithOptions(sizeChange, false, 0.0)
image.draw(in: CGRect(origin: CGPoint(x:0.0,y:0.0), size: sizeChange))
image = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndPDFContext()
let imageSmall = UIImageJPEGRepresentation(image, compressionQuality)
let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last
let path = docDir?.appendingFormat("/%@", name)
let url = URL(fileURLWithPath: path!)
print(path ?? "path nil")
do{
try imageSmall?.write(to: url, options: NSData.WritingOptions.atomicWrite)
}catch{
print(error)
}
return imageSmall
}
//检测一个手机号
class func testPhoneNumber(phoneNumber:String)->Bool{
let str = "^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\\d{8}$"
let p = NSPredicate(format: "self matches %@", str)
let ret = p.evaluate(with: phoneNumber)
if (ret && (phoneNumber.characters.count) == 11){
//是手机号
return true
}else{
return false
}
}
class func stringToMD5(string:String)->String {
let str = string.cString(using: String.Encoding.utf8)
let strLen = CC_LONG(string.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = Int(CC_MD5_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
CC_MD5(str!, strLen, result)
let hash = NSMutableString()
for i in 0 ..< digestLen {
hash.appendFormat("%02x", result[i])
}
result.deinitialize()
return String(format: hash as String)
}
}
public extension UIDevice {
var modelName: String {
var systemInfo = utsname()
uname(&systemInfo)
let machineMirror = Mirror(reflecting: systemInfo.machine)
let identifier = machineMirror.children.reduce("") { identifier, element in
guard let value = element.value as? Int8 , value != 0 else { return identifier }
return identifier + String(UnicodeScalar(UInt8(value)))
}
switch identifier {
case "iPod5,1": return "iPod Touch 5"
case "iPod7,1": return "iPod Touch 6"
case "iPhone3,1", "iPhone3,2", "iPhone3,3": return "iPhone 4"
case "iPhone4,1": return "iPhone 4s"
case "iPhone5,1", "iPhone5,2": return "iPhone 5"
case "iPhone5,3", "iPhone5,4": return "iPhone 5c"
case "iPhone6,1", "iPhone6,2": return "iPhone 5s"
case "iPhone7,2": return "iPhone 6"
case "iPhone7,1": return "iPhone 6 Plus"
case "iPhone8,1": return "iPhone 6s"
case "iPhone8,2": return "iPhone 6s Plus"
case "iPhone8,4": return "iPhone SE"
case "iPhone9,1": return "iPhone 7 (CDMA)"
case "iPhone9,3": return "iPhone 7 (GSM)"
case "iPhone9,2": return "iPhone 7 Plus (CDMA)"
case "iPhone9,4": return "iPhone 7 Plus (GSM)"
case "iPhone10,1", "iPhone10,4": return "iPhone 8"
case "iPhone10,2", "iPhone10,5": return "iPhone 8 Plus"
case "iPhone10,3", "iPhone10,6": return "iPhone X"
case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2"
case "iPad3,1", "iPad3,2", "iPad3,3": return "iPad 3"
case "iPad3,4", "iPad3,5", "iPad3,6": return "iPad 4"
case "iPad4,1", "iPad4,2", "iPad4,3": return "iPad Air"
case "iPad5,3", "iPad5,4": return "iPad Air 2"
case "iPad2,5", "iPad2,6", "iPad2,7": return "iPad Mini"
case "iPad4,4", "iPad4,5", "iPad4,6": return "iPad Mini 2"
case "iPad4,7", "iPad4,8", "iPad4,9": return "iPad Mini 3"
case "iPad5,1", "iPad5,2": return "iPad Mini 4"
case "iPad6,7", "iPad6,8": return "iPad Pro"
case "AppleTV5,3": return "Apple TV"
case "i386", "x86_64": return "Simulator"
default: return identifier
}
}
}
func UIImage2CGimage(_ image: UIImage?) -> CGImage? {
if let tryImage = image, let tryCIImage = CIImage(image: tryImage) {
return CIContext().createCGImage(tryCIImage, from: tryCIImage.extent)
}
return nil
}
| mit | 58f13fa1b435895f9522399e7dfdec34 | 39.35729 | 180 | 0.568383 | 4.385096 | false | false | false | false |
niunaruto/DeDaoAppSwift | testSwift/Pods/RxSwift/RxSwift/Observables/AddRef.swift | 20 | 1369 | //
// AddRef.swift
// RxSwift
//
// Created by Junior B. on 30/10/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
final class AddRefSink<Observer: ObserverType> : Sink<Observer>, ObserverType {
typealias Element = Observer.Element
override init(observer: Observer, cancel: Cancelable) {
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<Element>) {
switch event {
case .next:
self.forwardOn(event)
case .completed, .error:
self.forwardOn(event)
self.dispose()
}
}
}
final class AddRef<Element> : Producer<Element> {
private let _source: Observable<Element>
private let _refCount: RefCountDisposable
init(source: Observable<Element>, refCount: RefCountDisposable) {
self._source = source
self._refCount = refCount
}
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element {
let releaseDisposable = self._refCount.retain()
let sink = AddRefSink(observer: observer, cancel: cancel)
let subscription = Disposables.create(releaseDisposable, self._source.subscribe(sink))
return (sink: sink, subscription: subscription)
}
}
| mit | 224ad5af17591d88c0a2e446496b431d | 30.090909 | 171 | 0.649123 | 4.456026 | false | false | false | false |
blstream/TOZ_iOS | TOZ_iOS/Color.swift | 1 | 8669 | //
// Color.swift
// TOZ_iOS
//
// Copyright © 2017 intive. All rights reserved.
//
import UIKit
import Foundation
// swiftlint:disable nesting
struct Color {
struct LoginTextView {
struct TextField {
static let background = UIColor.white
struct Border {
//light blue
static var active = UIColor(red: 50.0/255.0, green: 155.0/255.0, blue: 245.0/255.0, alpha: 1.0).cgColor
//light gray
static let passive = UIColor(red: 238.0/255.0, green: 238.0/255.0, blue: 238.0/255.0, alpha: 1.0).cgColor
}
struct Text {
//red
static let error = UIColor(red: 245.0/255.0, green: 75.0/255.0, blue: 94.0/255.0, alpha: 1.0)
//black
static let regular = UIColor(red: 54.0/255.0, green: 54.0/255.0, blue: 54.0/255.0, alpha: 1.0)
}
}
struct Label {
//red
static let error = UIColor(red: 245.0/255.0, green: 75.0/255.0, blue: 94.0/255.0, alpha: 1.0)
//green
static let success = UIColor(red: 76.0/255.0, green: 211.0/255.0, blue: 116.0/255.0, alpha: 1.0)
}
}
struct TableView {
//light blue
static let separator = UIColor(red: 50.0/255.0, green: 155.0/255.0, blue: 245.0/255.0, alpha: 1.0)
static let background = UIColor.white
}
struct Background {
static let primary = UIColor.white
static let secondary = UIColor(red: 238.0/255.0, green: 238.0/255.0, blue: 238.0/255.0, alpha: 1.0)
}
struct TitleBar {
struct Background {
//green
static let primary = UIColor(red: 76.0/255.0, green: 211.0/255.0, blue: 116.0/255.0, alpha: 1.0)
}
struct Button {
static let primary = UIColor.white
//light blue
static let pressed = UIColor(red: 50.0/255.0, green: 155.0/255.0, blue: 245.0/255.0, alpha: 1.0)
}
}
struct TabBar {
struct Background {
//black
static let primary = UIColor(red: 54.0/255.0, green: 54.0/255.0, blue: 54.0/255.0, alpha: 1.0)
}
struct Icons {
//gray
static let primary = UIColor(red: 185.0/255.0, green: 185.0/255.0, blue: 185.0/255.0, alpha: 1.0)
//white
static let pressed = UIColor(red: 255.0/255.0, green: 255.0/255.0, blue: 255.0/255.0, alpha: 1.0)
}
}
struct NewsDetailView {
struct Font {
//gray
static let date = UIColor(red: 185.0/255.0, green: 185.0/255.0, blue: 185.0/255.0, alpha: 1.0)
//black
static let title = UIColor(red: 54.0/255.0, green: 54.0/255.0, blue: 54.0/255.0, alpha: 1.0)
//gray
static let content = UIColor(red: 185.0/255.0, green: 185.0/255.0, blue: 185.0/255.0, alpha: 1.0)
}
struct Background {
//light gray
static let primary = UIColor(red: 238.0/255.0, green: 238.0/255.0, blue: 238.0/255.0, alpha: 1.0)
static let secondary = UIColor.white
}
}
struct Cell {
struct Background {
//light gray
static let primary = UIColor(red: 238.0/255.0, green: 238.0/255.0, blue: 238.0/255.0, alpha: 1.0)
static let secondary = UIColor.white
}
struct Font {
//black
static let title = UIColor(red: 54.0/255.0, green: 54.0/255.0, blue: 54.0/255.0, alpha: 1.0)
//gray
static let content = UIColor(red: 175.0/255.0, green: 175.0/255.0, blue: 175.0/255.0, alpha: 1.0)
//gray
static let date = UIColor(red: 175.0/255.0, green: 175.0/255.0, blue: 175.0/255.0, alpha: 1.0)
}
struct Button {
//orange
static let primary = UIColor(red: 253.0/255.0, green: 137.0/255.0, blue: 36.0/255.0, alpha: 1.0)
static let text = UIColor.white
//light blue
static let secondary = UIColor(red: 50.0/255.0, green: 155.0/255.0, blue: 245.0/255.0, alpha: 1.0)
//light blue
static let pressed = UIColor(red: 122.0/255.0, green: 122.0/255.0, blue: 122.0/255.0, alpha: 1.0)
struct Icon {
//light blue
static let primary = UIColor(red: 50.0/255.0, green: 155.0/255.0, blue: 245.0/255.0, alpha: 1.0)
//light blue
static let secondary = UIColor(red: 50.0/255.0, green: 155.0/255.0, blue: 245.0/255.0, alpha: 1.0)
//light blue
static let pressed = UIColor(red: 50.0/255.0, green: 155.0/255.0, blue: 245.0/255.0, alpha: 1.0)
}
}
}
struct HelpUIViews {
static let background = UIColor(red: 238.0/255.0, green: 238.0/255.0, blue: 238.0/255.0, alpha: 1.0)
}
struct Calendar {
static let background = UIColor.white
//light gray
static let separator = UIColor(red: 238.0/255.0, green: 238.0/255.0, blue: 238.0/255.0, alpha: 1.0)
struct DataLabel {
//black
static let text = UIColor(red: 54.0/255.0, green: 54.0/255.0, blue: 54.0/255.0, alpha: 1.0)
static let background = UIColor.white
}
struct PreviousButton {
//gray
static let text = UIColor(red: 185.0/255.0, green: 185.0/255.0, blue: 185.0/255.0, alpha: 1.0)
static let background = UIColor.white
}
struct NextButton {
static let text = UIColor.white
//green
static let background = UIColor(red: 76.0/255.0, green: 211.0/255.0, blue: 116.0/255.0, alpha: 1.0)
}
struct WeekDayControl {
struct DayName {
struct primary {
//green
static let text = UIColor(red: 76.0/255.0, green: 211.0/255.0, blue: 116.0/255.0, alpha: 1.0)
static let background = UIColor.white
static let border = UIColor.white
}
struct pressed {
//green
static let text = UIColor(red: 76.0/255.0, green: 211.0/255.0, blue: 116.0/255.0, alpha: 1.0)
static let background = UIColor.white
static let border = UIColor.white
}
}
struct DayNumber {
struct primary {
//dark green
static let text = UIColor(red: 40.0/255.0, green: 174.0/255.0, blue: 97.0/255.0, alpha: 1.0)
static let background = UIColor.white
static let border = UIColor.white
}
struct pressed {
//light gray
static let text = UIColor(red: 238.0/255.0, green: 238.0/255.0, blue: 238.0/255.0, alpha: 1.0)
static let background = UIColor.white
//gray
static let border = UIColor(red: 185.0/255.0, green: 185.0/255.0, blue: 185.0/255.0, alpha: 1.0)
}
}
}
struct ScheduleControl {
struct primary {
static let text = UIColor.white
static let background = UIColor.white
//gray
static let border = UIColor(red: 185.0/255.0, green: 185.0/255.0, blue: 185.0/255.0, alpha: 1.0)
}
struct pressed {
static let text = UIColor.white
//green
static let background = UIColor(red: 76.0/255.0, green: 211.0/255.0, blue: 116.0/255.0, alpha: 1.0)
//dark green
static let border = UIColor(red: 40.0/255.0, green: 174.0/255.0, blue: 97.0/255.0, alpha: 1.0)
}
}
}
struct LoginViewController {
static let background = UIColor.white
struct Button {
//orange
static let background = UIColor(red: 253.0/255.0, green: 137.0/255.0, blue: 36.0/255.0, alpha: 1.0)
//white
static let tint = UIColor.white
}
}
struct SignUpViewController {
static let background = UIColor.white
struct Button {
static let background = UIColor(red: 1.00, green: 0.53, blue: 0.22, alpha: 1.0)
static let tint = UIColor.white
}
struct SegmentedControl {
static let background = UIColor.white
static let tint = UIColor(red: 1.00, green: 0.53, blue: 0.22, alpha: 1.0)
}
}
}
| apache-2.0 | 05fd9e7e62bba4e987710d8464cb093f | 38.761468 | 121 | 0.518228 | 3.495161 | false | false | false | false |
nanthi1990/Project-RainMan | Stormy/SpringAnimation.swift | 3 | 3520 | //
// SpringAnimation.swift
// Stormy
// Created by Aaron A
// Big Thanks goes out to Meng To for this :) Check out his site https://designcode.io
import Foundation
import UIKit
var duration = 0.7
var delay = 0.0
var damping = 0.7
var velocity = 0.7
func spring(duration: NSTimeInterval, animations: (() -> Void)!) {
UIView.animateWithDuration(duration, delay: delay, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.7, options: nil, animations: {
animations()
}, completion: { finished in
})
}
func springWithDelay(duration: NSTimeInterval, delay: NSTimeInterval, animations: (() -> Void)!) {
UIView.animateWithDuration(duration, delay: delay, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.8, options: nil, animations: {
animations()
}, completion: { finished in
})
}
func slideUp(duration: NSTimeInterval, animations: (() -> Void)!) {
UIView.animateWithDuration(duration, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.8, options: nil, animations: {
animations()
}, completion: nil)
}
func springWithCompletion(duration: NSTimeInterval, animations: (() -> Void)!, completion: ((Bool) -> Void)!) {
UIView.animateWithDuration(duration, delay: delay, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.7, options: nil, animations: {
animations()
}, completion: { finished in
completion(true)
})
}
func springScaleFrom (view: UIView, x: CGFloat, y: CGFloat, scaleX: CGFloat, scaleY: CGFloat) {
let translation = CGAffineTransformMakeTranslation(x, y)
let scale = CGAffineTransformMakeScale(scaleX, scaleY)
view.transform = CGAffineTransformConcat(translation, scale)
UIView.animateWithDuration(0.7, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.7, options: nil, animations: {
let translation = CGAffineTransformMakeTranslation(0, 0)
let scale = CGAffineTransformMakeScale(1, 1)
view.transform = CGAffineTransformConcat(translation, scale)
}, completion: nil)
}
func springScaleTo (view: UIView, x: CGFloat, y: CGFloat, scaleX: CGFloat, scaleY: CGFloat) {
let translation = CGAffineTransformMakeTranslation(0, 0)
let scale = CGAffineTransformMakeScale(1, 1)
view.transform = CGAffineTransformConcat(translation, scale)
UIView.animateWithDuration(duration, delay: delay, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.7, options: nil, animations: {
let translation = CGAffineTransformMakeTranslation(x, y)
let scale = CGAffineTransformMakeScale(scaleX, scaleY)
view.transform = CGAffineTransformConcat(translation, scale)
}, completion: nil)
}
func popoverTopRight(view: UIView) {
view.hidden = false
var translate = CGAffineTransformMakeTranslation(200, -200)
var scale = CGAffineTransformMakeScale(0.3, 0.3)
view.alpha = 0
view.transform = CGAffineTransformConcat(translate, scale)
UIView.animateWithDuration(0.6, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0.8, options: nil, animations: {
var translate = CGAffineTransformMakeTranslation(0, 0)
var scale = CGAffineTransformMakeScale(1, 1)
view.transform = CGAffineTransformConcat(translate, scale)
view.alpha = 1
}, completion: nil)
} | mit | e54c38d02b7e4a2cc12b8ac0438baa18 | 34.21 | 139 | 0.674432 | 4.828532 | false | false | false | false |
likojack/wedrive_event_management | weDrive/EventManagementViewController.swift | 2 | 2780 | //
// EventManagementViewController.swift
// weDrive
//
// Created by Michelle Lau on 21/07/2015.
// Copyright (c) 2015 michelle. All rights reserved.
//
import UIKit
import CoreData
class EventManagementViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var eventListTableView: UITableView!
@IBOutlet weak var createButton: UIBarButtonItem!
var eventlist : [Event] = []
var selectedEvent : Event? = nil
override func viewDidLoad() {
super.viewDidLoad()
self.eventListTableView.dataSource = self
self.eventListTableView.delegate = self
}
override func viewWillAppear(animated: Bool) {
var context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext!
var request = NSFetchRequest(entityName: "Event")
var results = context.executeFetchRequest(request, error: nil)
if results != nil {
self.eventlist = results! as! [Event]
}
}
// func createEvent(){
// var context = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext!
//
// var event = NSEntityDescription.insertNewObjectForEntityForName("Event", inManagedObjectContext: context) as Event
//
// event.name = "Picnic On Sunday!"
// event.from = "anu"
// event.people = "ahsjdh"
// event.previewimage = UIImageJPEGRepresentation(UIImage(named:"Tidbinbilla.jpg"), 1)
//
// context.save(nil)
// }
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.eventlist.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = UITableViewCell()
var event = self.eventlist[indexPath.row]
cell.textLabel!.text = event.name
cell.imageView!.image = UIImage(data: event.previewimage)
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.selectedEvent = self.eventlist[indexPath.row]
self.performSegueWithIdentifier("eventDetialSegue", sender: self)
}
@IBAction func createTapped(sender: AnyObject) {
self.performSegueWithIdentifier("createSegue", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "eventDetialSegue" {
var detailViewController = segue.destinationViewController as! EventDetailViewController
detailViewController.event = self.selectedEvent
}
}
}
| apache-2.0 | 983e76106b20b21e861d8782ace99109 | 32.095238 | 124 | 0.661511 | 5.036232 | false | false | false | false |
diesmal/thisorthat | ThisOrThat/Code/Services/TOTAPI/TOTAuthorizationData.swift | 1 | 1250 | //
// TOTAuthorizationData.swift
// ThisOrThat
//
// Created by Ilya Nikolaenko on 27/01/2017.
// Copyright © 2017 Ilya Nikolaenko. All rights reserved.
//
import UIKit
class TOTAuthorizationData {
static private let keychainAccess = KeychainAccess()
static private let tokenKeychanId = Bundle.main.bundleIdentifier! + ".tottoken"
static private let userKeychanId = Bundle.main.bundleIdentifier! + ".totuserid"
static var token: String? {
get {
return keychainAccess.getPasscode(identifier: tokenKeychanId)
}
set {
if let newValue = newValue {
keychainAccess.setPasscode(identifier: tokenKeychanId, passcode: newValue)
} else {
keychainAccess.deletePasscode(identifier: tokenKeychanId)
}
}
}
static var userId: String? {
get {
return keychainAccess.getPasscode(identifier: userKeychanId)
}
set {
if let newValue = newValue {
keychainAccess.setPasscode(identifier: userKeychanId, passcode: newValue)
} else {
keychainAccess.deletePasscode(identifier: userKeychanId)
}
}
}
}
| apache-2.0 | 46af9d1e7da0a05a85e1afff13334e6b | 26.755556 | 90 | 0.611689 | 4.731061 | false | false | false | false |
ljubinkovicd/Lingo-Chat | Pods/SkyFloatingLabelTextField/Sources/SkyFloatingLabelTextField.swift | 1 | 19581 | // Copyright 2016-2017 Skyscanner Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed
// on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License
// for the specific language governing permissions and limitations under the License.
import UIKit
/**
A beautiful and flexible textfield implementation with support for title label, error message and placeholder.
*/
@IBDesignable
open class SkyFloatingLabelTextField: UITextField { // swiftlint:disable:this type_body_length
/**
A Boolean value that determines if the language displayed is LTR.
Default value set automatically from the application language settings.
*/
open var isLTRLanguage = UIApplication.shared.userInterfaceLayoutDirection == .leftToRight {
didSet {
updateTextAligment()
}
}
fileprivate func updateTextAligment() {
if isLTRLanguage {
textAlignment = .left
titleLabel.textAlignment = .left
} else {
textAlignment = .right
titleLabel.textAlignment = .right
}
}
// MARK: Animation timing
/// The value of the title appearing duration
dynamic open var titleFadeInDuration: TimeInterval = 0.2
/// The value of the title disappearing duration
dynamic open var titleFadeOutDuration: TimeInterval = 0.3
// MARK: Colors
fileprivate var cachedTextColor: UIColor?
/// A UIColor value that determines the text color of the editable text
@IBInspectable
override dynamic open var textColor: UIColor? {
set {
cachedTextColor = newValue
updateControl(false)
}
get {
return cachedTextColor
}
}
/// A UIColor value that determines text color of the placeholder label
@IBInspectable dynamic open var placeholderColor: UIColor = UIColor.lightGray {
didSet {
updatePlaceholder()
}
}
/// A UIFont value that determines text color of the placeholder label
dynamic open var placeholderFont: UIFont? {
didSet {
updatePlaceholder()
}
}
fileprivate func updatePlaceholder() {
if let placeholder = placeholder, let font = placeholderFont ?? font {
attributedPlaceholder = NSAttributedString(
string: placeholder,
attributes: [NSForegroundColorAttributeName: placeholderColor, NSFontAttributeName: font]
)
}
}
/// A UIFont value that determines the text font of the title label
dynamic open var titleFont: UIFont = .systemFont(ofSize: 13) {
didSet {
updateTitleLabel()
}
}
/// A UIColor value that determines the text color of the title label when in the normal state
@IBInspectable dynamic open var titleColor: UIColor = .gray {
didSet {
updateTitleColor()
}
}
/// A UIColor value that determines the color of the bottom line when in the normal state
@IBInspectable dynamic open var lineColor: UIColor = .lightGray {
didSet {
updateLineView()
}
}
/// A UIColor value that determines the color used for the title label and line when the error message is not `nil`
@IBInspectable dynamic open var errorColor: UIColor = .red {
didSet {
updateColors()
}
}
/// A UIColor value that determines the text color of the title label when editing
@IBInspectable dynamic open var selectedTitleColor: UIColor = .blue {
didSet {
updateTitleColor()
}
}
/// A UIColor value that determines the color of the line in a selected state
@IBInspectable dynamic open var selectedLineColor: UIColor = .black {
didSet {
updateLineView()
}
}
// MARK: Line height
/// A CGFloat value that determines the height for the bottom line when the control is in the normal state
@IBInspectable dynamic open var lineHeight: CGFloat = 0.5 {
didSet {
updateLineView()
setNeedsDisplay()
}
}
/// A CGFloat value that determines the height for the bottom line when the control is in a selected state
@IBInspectable dynamic open var selectedLineHeight: CGFloat = 1.0 {
didSet {
updateLineView()
setNeedsDisplay()
}
}
// MARK: View components
/// The internal `UIView` to display the line below the text input.
open var lineView: UIView!
/// The internal `UILabel` that displays the selected, deselected title or error message based on the current state.
open var titleLabel: UILabel!
// MARK: Properties
/**
The formatter used before displaying content in the title label.
This can be the `title`, `selectedTitle` or the `errorMessage`.
The default implementation converts the text to uppercase.
*/
open var titleFormatter: ((String) -> String) = { (text: String) -> String in
return text.uppercased()
}
/**
Identifies whether the text object should hide the text being entered.
*/
override open var isSecureTextEntry: Bool {
set {
super.isSecureTextEntry = newValue
fixCaretPosition()
}
get {
return super.isSecureTextEntry
}
}
/// A String value for the error message to display.
open var errorMessage: String? {
didSet {
updateControl(true)
}
}
/// The backing property for the highlighted property
fileprivate var _highlighted = false
/**
A Boolean value that determines whether the receiver is highlighted.
When changing this value, highlighting will be done with animation
*/
override open var isHighlighted: Bool {
get {
return _highlighted
}
set {
_highlighted = newValue
updateTitleColor()
updateLineView()
}
}
/// A Boolean value that determines whether the textfield is being edited or is selected.
open var editingOrSelected: Bool {
return super.isEditing || isSelected
}
/// A Boolean value that determines whether the receiver has an error message.
open var hasErrorMessage: Bool {
return errorMessage != nil && errorMessage != ""
}
fileprivate var _renderingInInterfaceBuilder: Bool = false
/// The text content of the textfield
@IBInspectable
override open var text: String? {
didSet {
updateControl(false)
}
}
/**
The String to display when the input field is empty.
The placeholder can also appear in the title label when both `title` `selectedTitle` and are `nil`.
*/
@IBInspectable
override open var placeholder: String? {
didSet {
setNeedsDisplay()
updatePlaceholder()
updateTitleLabel()
}
}
/// The String to display when the textfield is editing and the input is not empty.
@IBInspectable open var selectedTitle: String? {
didSet {
updateControl()
}
}
/// The String to display when the textfield is not editing and the input is not empty.
@IBInspectable open var title: String? {
didSet {
updateControl()
}
}
// Determines whether the field is selected. When selected, the title floats above the textbox.
open override var isSelected: Bool {
didSet {
updateControl(true)
}
}
// MARK: - Initializers
/**
Initializes the control
- parameter frame the frame of the control
*/
override public init(frame: CGRect) {
super.init(frame: frame)
init_SkyFloatingLabelTextField()
}
/**
Intialzies the control by deserializing it
- parameter coder the object to deserialize the control from
*/
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
init_SkyFloatingLabelTextField()
}
fileprivate final func init_SkyFloatingLabelTextField() {
borderStyle = .none
createTitleLabel()
createLineView()
updateColors()
addEditingChangedObserver()
updateTextAligment()
}
fileprivate func addEditingChangedObserver() {
self.addTarget(self, action: #selector(SkyFloatingLabelTextField.editingChanged), for: .editingChanged)
}
/**
Invoked when the editing state of the textfield changes. Override to respond to this change.
*/
open func editingChanged() {
updateControl(true)
updateTitleLabel(true)
}
// MARK: create components
fileprivate func createTitleLabel() {
let titleLabel = UILabel()
titleLabel.autoresizingMask = [.flexibleWidth, .flexibleHeight]
titleLabel.font = titleFont
titleLabel.alpha = 0.0
titleLabel.textColor = titleColor
addSubview(titleLabel)
self.titleLabel = titleLabel
}
fileprivate func createLineView() {
if lineView == nil {
let lineView = UIView()
lineView.isUserInteractionEnabled = false
self.lineView = lineView
configureDefaultLineHeight()
}
lineView.autoresizingMask = [.flexibleWidth, .flexibleTopMargin]
addSubview(lineView)
}
fileprivate func configureDefaultLineHeight() {
let onePixel: CGFloat = 1.0 / UIScreen.main.scale
lineHeight = 2.0 * onePixel
selectedLineHeight = 2.0 * self.lineHeight
}
// MARK: Responder handling
/**
Attempt the control to become the first responder
- returns: True when successfull becoming the first responder
*/
@discardableResult
override open func becomeFirstResponder() -> Bool {
let result = super.becomeFirstResponder()
updateControl(true)
return result
}
/**
Attempt the control to resign being the first responder
- returns: True when successfull resigning being the first responder
*/
@discardableResult
override open func resignFirstResponder() -> Bool {
let result = super.resignFirstResponder()
updateControl(true)
return result
}
// MARK: - View updates
fileprivate func updateControl(_ animated: Bool = false) {
updateColors()
updateLineView()
updateTitleLabel(animated)
}
fileprivate func updateLineView() {
if let lineView = lineView {
lineView.frame = lineViewRectForBounds(bounds, editing: editingOrSelected)
}
updateLineColor()
}
// MARK: - Color updates
/// Update the colors for the control. Override to customize colors.
open func updateColors() {
updateLineColor()
updateTitleColor()
updateTextColor()
}
fileprivate func updateLineColor() {
if hasErrorMessage {
lineView.backgroundColor = errorColor
} else {
lineView.backgroundColor = editingOrSelected ? selectedLineColor : lineColor
}
}
fileprivate func updateTitleColor() {
if hasErrorMessage {
titleLabel.textColor = errorColor
} else {
if editingOrSelected || isHighlighted {
titleLabel.textColor = selectedTitleColor
} else {
titleLabel.textColor = titleColor
}
}
}
fileprivate func updateTextColor() {
if hasErrorMessage {
super.textColor = errorColor
} else {
super.textColor = cachedTextColor
}
}
// MARK: - Title handling
fileprivate func updateTitleLabel(_ animated: Bool = false) {
var titleText: String? = nil
if hasErrorMessage {
titleText = titleFormatter(errorMessage!)
} else {
if editingOrSelected {
titleText = selectedTitleOrTitlePlaceholder()
if titleText == nil {
titleText = titleOrPlaceholder()
}
} else {
titleText = titleOrPlaceholder()
}
}
titleLabel.text = titleText
titleLabel.font = titleFont
updateTitleVisibility(animated)
}
fileprivate var _titleVisible = false
/*
* Set this value to make the title visible
*/
open func setTitleVisible(
_ titleVisible: Bool,
animated: Bool = false,
animationCompletion: ((_ completed: Bool) -> Void)? = nil
) {
if _titleVisible == titleVisible {
return
}
_titleVisible = titleVisible
updateTitleColor()
updateTitleVisibility(animated, completion: animationCompletion)
}
/**
Returns whether the title is being displayed on the control.
- returns: True if the title is displayed on the control, false otherwise.
*/
open func isTitleVisible() -> Bool {
return hasText || hasErrorMessage || _titleVisible
}
fileprivate func updateTitleVisibility(_ animated: Bool = false, completion: ((_ completed: Bool) -> Void)? = nil) {
let alpha: CGFloat = isTitleVisible() ? 1.0 : 0.0
let frame: CGRect = titleLabelRectForBounds(bounds, editing: isTitleVisible())
let updateBlock = { () -> Void in
self.titleLabel.alpha = alpha
self.titleLabel.frame = frame
}
if animated {
let animationOptions: UIViewAnimationOptions = .curveEaseOut
let duration = isTitleVisible() ? titleFadeInDuration : titleFadeOutDuration
UIView.animate(withDuration: duration, delay: 0, options: animationOptions, animations: { () -> Void in
updateBlock()
}, completion: completion)
} else {
updateBlock()
completion?(true)
}
}
// MARK: - UITextField text/placeholder positioning overrides
/**
Calculate the rectangle for the textfield when it is not being edited
- parameter bounds: The current bounds of the field
- returns: The rectangle that the textfield should render in
*/
override open func textRect(forBounds bounds: CGRect) -> CGRect {
let superRect = super.textRect(forBounds: bounds)
let titleHeight = self.titleHeight()
let rect = CGRect(
x: superRect.origin.x,
y: titleHeight,
width: superRect.size.width,
height: superRect.size.height - titleHeight - selectedLineHeight
)
return rect
}
/**
Calculate the rectangle for the textfield when it is being edited
- parameter bounds: The current bounds of the field
- returns: The rectangle that the textfield should render in
*/
override open func editingRect(forBounds bounds: CGRect) -> CGRect {
let superRect = super.editingRect(forBounds: bounds)
let titleHeight = self.titleHeight()
let rect = CGRect(
x: superRect.origin.x,
y: titleHeight,
width: superRect.size.width,
height: superRect.size.height - titleHeight - selectedLineHeight
)
return rect
}
/**
Calculate the rectangle for the placeholder
- parameter bounds: The current bounds of the placeholder
- returns: The rectangle that the placeholder should render in
*/
override open func placeholderRect(forBounds bounds: CGRect) -> CGRect {
let rect = CGRect(
x: 0,
y: titleHeight(),
width: bounds.size.width,
height: bounds.size.height - titleHeight() - selectedLineHeight
)
return rect
}
// MARK: - Positioning Overrides
/**
Calculate the bounds for the title label. Override to create a custom size title field.
- parameter bounds: The current bounds of the title
- parameter editing: True if the control is selected or highlighted
- returns: The rectangle that the title label should render in
*/
open func titleLabelRectForBounds(_ bounds: CGRect, editing: Bool) -> CGRect {
if editing {
return CGRect(x: 0, y: 0, width: bounds.size.width, height: titleHeight())
}
return CGRect(x: 0, y: titleHeight(), width: bounds.size.width, height: titleHeight())
}
/**
Calculate the bounds for the bottom line of the control.
Override to create a custom size bottom line in the textbox.
- parameter bounds: The current bounds of the line
- parameter editing: True if the control is selected or highlighted
- returns: The rectangle that the line bar should render in
*/
open func lineViewRectForBounds(_ bounds: CGRect, editing: Bool) -> CGRect {
let height = editing ? selectedLineHeight : lineHeight
return CGRect(x: 0, y: bounds.size.height - height, width: bounds.size.width, height: height)
}
/**
Calculate the height of the title label.
-returns: the calculated height of the title label. Override to size the title with a different height
*/
open func titleHeight() -> CGFloat {
if let titleLabel = titleLabel,
let font = titleLabel.font {
return font.lineHeight
}
return 15.0
}
/**
Calcualte the height of the textfield.
-returns: the calculated height of the textfield. Override to size the textfield with a different height
*/
open func textHeight() -> CGFloat {
return self.font!.lineHeight + 7.0
}
// MARK: - Layout
/// Invoked when the interface builder renders the control
override open func prepareForInterfaceBuilder() {
if #available(iOS 8.0, *) {
super.prepareForInterfaceBuilder()
}
borderStyle = .none
isSelected = true
_renderingInInterfaceBuilder = true
updateControl(false)
invalidateIntrinsicContentSize()
}
/// Invoked by layoutIfNeeded automatically
override open func layoutSubviews() {
super.layoutSubviews()
titleLabel.frame = titleLabelRectForBounds(bounds, editing: isTitleVisible() || _renderingInInterfaceBuilder)
lineView.frame = lineViewRectForBounds(bounds, editing: editingOrSelected || _renderingInInterfaceBuilder)
}
/**
Calculate the content size for auto layout
- returns: the content size to be used for auto layout
*/
override open var intrinsicContentSize: CGSize {
return CGSize(width: bounds.size.width, height: titleHeight() + textHeight())
}
// MARK: - Helpers
fileprivate func titleOrPlaceholder() -> String? {
guard let title = title ?? placeholder else {
return nil
}
return titleFormatter(title)
}
fileprivate func selectedTitleOrTitlePlaceholder() -> String? {
guard let title = selectedTitle ?? title ?? placeholder else {
return nil
}
return titleFormatter(title)
}
} // swiftlint:disable:this file_length
| mit | eacf56999051756f5d23436ab6802072 | 30.531401 | 120 | 0.628671 | 5.4241 | false | false | false | false |
rsrose21/cluelist | ClueList/ClueList/ToDoItem.swift | 1 | 6763 | //
// ToDoItem.swift
// ClueList
//
// Created by Ryan Rose on 10/12/15.
// Copyright © 2015 GE. All rights reserved.
//
import UIKit
import CoreData
//make ToDoItem available to Objective-C code
@objc(ToDoItem)
//make ToDoItem a subclass of NSManagedObject
class ToDoItem: NSManagedObject {
class var entityName: String {
return "ToDoItem"
}
let DEFAULT_PRIORITY = 0
// current selected random factoid displayed for this ToDoItem
var factoid: String?
var editing: Bool = false
var requesting: Bool = false
@NSManaged var id: String
// A text description of this item.
@NSManaged var text: String
// A Boolean value that determines the completed state of this item.
@NSManaged var completed: Bool
// The subject extracted from the description text used to find a related factoid
@NSManaged var clue: String
// A short factoid displayed in place of text description based on keyword
@NSManaged var factoids: [Factoid]
// The timestamp when the ToDoItem was created
@NSManaged var created: NSDate
// The user assigned priority - used for tableview section sorting
@NSManaged var priority: NSNumber
// The timestamp when the ToDoItem is due
@NSManaged var deadline: NSDate?
@NSManaged var metaData: ToDoMetaData
//convenience method that returns whether or not an item is overdue
var isOverdue: Bool {
if self.deadline != nil {
return (NSDate().compare(self.deadline!) == NSComparisonResult.OrderedDescending) // deadline is earlier than current date
} else {
return false
}
}
override func awakeFromInsert() {
super.awakeFromInsert()
//each todo has a mandatory relation with a meta data object, which is created upon insert
metaData = NSEntityDescription.insertNewObjectForEntityForName(ToDoMetaData.entityName, inManagedObjectContext: managedObjectContext!) as! ToDoMetaData
}
// remove any scheduled notifications for this ToDoItem when deleted
override func prepareForDeletion() {
super.prepareForDeletion()
ToDoList.sharedInstance.removeItem(self)
}
// Include this standard Core Data init method.
override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) {
super.init(entity: entity, insertIntoManagedObjectContext: context)
}
// Returns a ToDoItem initialized with the given text and default completed value.
init(dictionary: [String : AnyObject?], context: NSManagedObjectContext) {
// Get the entity associated with the "Pin" type. This is an object that contains
// the information from the VirtualTourist.xcdatamodeld file.
let entity = NSEntityDescription.entityForName("ToDoItem", inManagedObjectContext: context)!
// Now we can call an init method that we have inherited from NSManagedObject. Remember that
// the Pin class is a subclass of NSManagedObject. This inherited init method does the
// work of "inserting" our object into the context that was passed in as a parameter
super.init(entity: entity, insertIntoManagedObjectContext: context)
// After the Core Data work has been taken care of we can init the properties from the
// dictionary. This works in the same way that it did before we started on Core Data
// A id could be passed in from the notifications bar
if let id = dictionary["id"] as? String {
self.id = id
} else {
// generate uid in swift: http://stackoverflow.com/questions/24428250/generate-uuid-in-xcode-swift
self.id = NSUUID().UUIDString
}
text = dictionary["text"] as! String
if let completed = dictionary["completed"] as? Bool {
self.completed = completed
} else {
self.completed = false
}
if let clue = dictionary["clue"] as? String {
self.clue = clue
} else {
self.clue = ""
}
//set created timestamp to current date/time
created = NSDate()
if let priority = dictionary["priority"] as? Int {
self.priority = selectedPriority(priority).rawValue
} else {
self.priority = selectedPriority(DEFAULT_PRIORITY).rawValue
}
//set the order for the table row
metaData.internalOrder = ToDoMetaData.maxInternalOrder(context)+1
metaData.updateSectionIdentifier()
}
func selectedPriority(priority: Int) -> ToDoPriority {
switch priority {
case 0: return .None
case 1: return .Low
case 2: return .Medium
case 3: return .High
default: return .None
}
}
func getRandomFactoid() -> String? {
//return the currently selected factoid if available
if let item = factoid {
return item
}
//select a random factoid from our saved array
if factoids.count > 0 {
let randomIndex = Int(arc4random_uniform(UInt32(factoids.count)))
//decode the Base64 encoded string from the API
factoid = factoids[randomIndex].text.htmlDecoded()
return factoid!
}
return nil
}
func refreshFactoid() -> String? {
var newFactoid: String
if let item = factoid {
//reset value so we get a new random factoid
factoid = nil
newFactoid = getRandomFactoid()!
//if we randomly selected the same factoid and there is more than one to choose, choose another
if factoids.count > 1 && newFactoid == item {
factoid = nil
//iterate through factoids, exiting loop once we find a different factoid
for f in factoids {
if (f != item) {
factoid = f.text.htmlDecoded()
if factoid != "" {
return factoid
}
}
}
}
} else {
//nothing previously selected, choose a random factoid and select it
newFactoid = getRandomFactoid()!
}
return newFactoid
}
// remove all factoids from this ToDoItem
func deleteAll() {
let context:NSManagedObjectContext = self.managedObjectContext!
for f in factoids {
context.deleteObject(f as NSManagedObject)
try! context.save()
}
}
}
| mit | f8cf4bc1986c000b32d1236be06b904d | 34.589474 | 159 | 0.61609 | 5.146119 | false | false | false | false |
harlanhaskins/swift | test/SPI/local_spi_decls.swift | 1 | 4054 | // Checks for SPI declarations and limited exposability
// RUN: %empty-directory(%t)
// RUN: %target-typecheck-verify-swift -I %t -verify-ignore-unknown -enable-library-evolution -swift-version 5
// SPI declarations
@_spi(MySPI) public func spiFunc() {} // expected-note {{global function 'spiFunc()' is not '@usableFromInline' or public}}
@_spi(+) public func invalidSPIName() {} // expected-error {{expected an SPI identifier as subject of the '@_spi' attribute}}
@_spi(🤔) public func emojiNamedSPI() {}
@_spi() public func emptyParensSPI() {} // expected-error {{expected an SPI identifier as subject of the '@_spi' attribute}}
@_spi(set) public func keywordSPI() {} // expected-error {{expected an SPI identifier as subject of the '@_spi' attribute}}
@_spi(S) public class SPIClass {} // expected-note 2 {{type declared here}}
// expected-note @-1 2 {{class 'SPIClass' is not '@usableFromInline' or public}}
class InternalClass {} // expected-note 2 {{type declared here}}
private class PrivateClass {} // expected-note 2 {{type declared here}}
@_spi(S) public protocol SPIProtocol {} // expected-note {{type declared here}}
@_spi(S) public func useOfSPITypeOk(_ p0: SPIProtocol, p1: SPIClass) -> SPIClass { fatalError() } // OK
public func useOfSPITypeInvalid() -> SPIClass { fatalError() } // expected-error {{function cannot be declared public because its result uses an '@_spi' type}}
@_spi(S) public func spiUseOfInternalType() -> InternalClass { fatalError() } // expected-error{{function cannot be declared '@_spi' because its result uses an internal type}}
@_spi(S) public func spiUseOfPrivateType(_ a: PrivateClass) { fatalError() } // expected-error{{function cannot be declared '@_spi' because its parameter uses a private type}}
@inlinable
func inlinable() -> SPIClass { // expected-error {{class 'SPIClass' is '@_spi' and cannot be referenced from an '@inlinable' function}}
spiFunc() // expected-error {{global function 'spiFunc()' is '@_spi' and cannot be referenced from an '@inlinable' function}}
_ = SPIClass() // expected-error {{class 'SPIClass' is '@_spi' and cannot be referenced from an '@inlinable' function}}
}
@_spi(S) public struct SPIStruct {} // expected-note 2 {{struct 'SPIStruct' is not '@usableFromInline' or public}}
@frozen public struct FrozenStruct {
@_spi(S) public var spiInFrozen = SPIStruct() // expected-error {{struct 'SPIStruct' is '@_spi' and cannot be referenced from a property initializer in a '@frozen' type}}
// expected-error @-1 {{stored property 'spiInFrozen' cannot be declared '@_spi' in a '@frozen' struct}}
var asdf = SPIStruct() // expected-error {{struct 'SPIStruct' is '@_spi' and cannot be referenced from a property initializer in a '@frozen' type}}
}
private protocol PrivateProtocol {} // expected-note {{type declared here}}
@_spi(S) public class BadSubclass : InternalClass {} // expected-error{{class cannot be declared public because its superclass is internal}}
@_spi(S) public class OkSPISubclass : SPIClass {} // OK
public class BadPublicClass : SPIClass {} // expected-error {{class cannot be declared public because its superclass is '@_spi'}}
@_spi(S) public class BadSPIClass : PrivateClass {} // expected-error {{class cannot be declared public because its superclass is private}}
@_spi(s) public func genFunc<T: PrivateProtocol>(_ t: T) {} // expected-error {{global function cannot be declared public because its generic parameter uses a private type}}
public func genFuncBad<T: SPIProtocol>(_ t: T) {} // expected-error {{global function cannot be declared public because its generic parameter uses an '@_spi' type}}
@_spi(S) public func genFuncSPI<T: SPIProtocol>(_ t: T) {} // OK
@_spi(S) private func privateCantBeSPI() {} // expected-error{{private global function cannot be declared '@_spi' because only public and open declarations can be '@_spi'}} {{1-10=}}
@_spi(S) func internalCantBeSPI() {} // expected-error{{internal global function cannot be declared '@_spi' because only public and open declarations can be '@_spi'}} {{1-10=}}
| apache-2.0 | d1dcda8c248c141015c8a81f1b7d19b1 | 76.903846 | 182 | 0.719082 | 4.075453 | false | false | false | false |
asp2insp/CodePathVines | CodePathVines/StatusNotification.swift | 1 | 824 | //
// StatusNotification.swift
// CodePathVines
//
// Created by Josiah Gaskin on 5/10/15.
// Copyright (c) 2015 Josiah Gaskin. All rights reserved.
//
import Foundation
public class StatusNotification : UIView, ReactorResponder {
var lastNetworkState : Bool = true
public func onUpdate() {
let networkOn = Reactor.instance.evaluateToSwift(NETWORK_STATUS) as? Bool ?? false
if lastNetworkState != networkOn {
let targetHeight : CGFloat = networkOn ? 0.0 : 50.0
var frame = self.frame
UIView.animateWithDuration(0.5, animations: {
self.frame = CGRectMake(frame.minX, frame.minY, frame.width, targetHeight)
self.hidden = networkOn
return
})
lastNetworkState = networkOn
}
}
} | mit | 3ee22028108e4b11a1eb449fda8408d0 | 29.555556 | 90 | 0.620146 | 4.359788 | false | false | false | false |
eonil/state-series.swift | Sources/StateSeries.swift | 1 | 3862 | //
// StateSeries.swift
// EonilStateSeries
//
// Created by Hoon H. on 2017/10/01.
//
//
import EonilTimePoint
///
/// A series of states.
///
/// This is analogue of time-series data.
/// State-series is built with multiple state-points.
/// Each point has ordered unique ID which provide equality test and
/// order comparison.
///
/// Equalty of Point ID
/// -------------------
/// Point ID represents relative distance and order between two points in
/// a series. Point IDs between two different serieses are awalys inequal.
/// Also point ID is pure value semantic. If you copy a state-series, and
/// append one new state, their point IDs are equal because they have
/// same relative distance from previous point.
/// Please take care that point ID keeps all instances alive between the
/// oldest one to the newest one in the chain. You should erase all
/// unnecessary old point IDs as soon as possible to save memory.
///
public struct StateSeries<Snapshot>: StateSeriesType, CustomDebugStringConvertible {
fileprivate typealias RawPoint = (id: TimePoint, state: Snapshot)
private var rawPoints = [RawPoint]()
public static var defaultMaxUnavailableKeySpaceCount: Int { return 1024 * 1024 }
public typealias Point = (id: PointID, state: Snapshot)
///
/// - Parameter capacity:
/// Hard limit of total number of points.
///
public init(capacity: Int = .max) {
}
public var points: PointCollection {
return PointCollection(rawPoints)
}
public mutating func append(_ state: Snapshot) {
let p = (TimeLine.spawn(), state)
rawPoints.append(p)
}
public mutating func append<S>(contentsOf states: S) where S: Sequence, S.Element == Snapshot {
states.forEach({ append($0) })
}
public mutating func removeFirst() {
rawPoints.removeFirst()
}
public mutating func removeFirst(_ n: Int) {
rawPoints.removeFirst(n)
}
public var debugDescription: String {
let c = points.map({ "\t(id: \($0.id.debugDescription), state: \($0.state))," }).joined(separator: "\n")
return "StateSeries(points: [\n\(c)\n])"
}
}
public extension StateSeries {
///
/// Strongly typed point ID for collection's element type.
///
/// Basically, you can compare equality or ordering only with same typed
/// point IDs. But that's just a safety-net, and you can escape from it
/// be using `timePoint` property.
///
public struct PointID: Comparable, Hashable, CustomDebugStringConvertible {
public let timePoint: TimePoint
fileprivate init(_ p: TimePoint) {
timePoint = p
}
public var hashValue: Int {
return timePoint.hashValue
}
public static func == (_ a: PointID, _ b: PointID) -> Bool {
return a.timePoint == b.timePoint
}
public static func < (_ a: PointID, _ b: PointID) -> Bool {
return a.timePoint < b.timePoint
}
public var debugDescription: String {
return "PointID(\(timePoint)"
}
}
public struct PointCollection: RandomAccessCollection {
private let rawPoints: [RawPoint]
fileprivate init(_ ps: [RawPoint]) {
rawPoints = ps
}
public typealias Index = Int
public var startIndex: Index { return rawPoints.startIndex }
public var endIndex: Int { return rawPoints.endIndex }
public subscript(position: Int) -> Point {
let raw = rawPoints[position]
let pid = PointID(raw.id)
let ps = raw.state
return (pid, ps)
}
}
}
extension StateSeries: ExpressibleByArrayLiteral {
public init(arrayLiteral elements: Snapshot...) {
self = StateSeries()
append(contentsOf: elements)
}
}
| mit | 3b5c68c501c0dd38f874c49241c7f632 | 31.453782 | 112 | 0.632574 | 4.388636 | false | false | false | false |
dunkelstern/twohundred | TwoHundred/request.swift | 1 | 730 | //
// request.swift
// twohundred
//
// Created by Johannes Schriewer on 01/11/15.
// Copyright © 2015 Johannes Schriewer. All rights reserved.
//
import UnchainedIPAddress
/// HTTP Request
public struct HTTPRequest {
/// IP of the remote host
public var remoteIP: IPAddress!
/// Request header
public var header: RequestHeader
/// Body data, optional
public var data:[UInt8]? = nil
/// space for custom data from middleware
public var middlewareData = [String:Any]()
/// default initializer
public init(remoteIP: IPAddress?, header: RequestHeader, data: [UInt8]?) {
self.remoteIP = remoteIP
self.header = header
self.data = data
}
}
| bsd-3-clause | 456e754f2f2c6c729d4665b9acfd82e9 | 21.78125 | 78 | 0.640604 | 4.313609 | false | false | false | false |
Oscareli98/Moya | Moya/RxSwift/Moya+RxSwift.swift | 1 | 2813 | import Foundation
import RxSwift
/// Subclass of MoyaProvider that returns Observable instances when requests are made. Much better than using completion closures.
public class RxMoyaProvider<T where T: MoyaTarget>: MoyaProvider<T> {
/// Current requests that have not completed or errored yet.
/// Note: Do not access this directly. It is public only for unit-testing purposes (sigh).
public var inflightRequests = Dictionary<Endpoint<T>, Observable<MoyaResponse>>()
/// Initializes a reactive provider.
override public init(endpointClosure: MoyaEndpointsClosure = MoyaProvider.DefaultEndpointMapping, endpointResolver: MoyaEndpointResolution = MoyaProvider.DefaultEnpointResolution, stubBehavior: MoyaStubbedBehavior = MoyaProvider.NoStubbingBehavior, networkActivityClosure: Moya.NetworkActivityClosure? = nil) {
super.init(endpointClosure: endpointClosure, endpointResolver: endpointResolver, stubBehavior: stubBehavior, networkActivityClosure: networkActivityClosure)
}
/// Designated request-making method.
public func request(token: T) -> Observable<MoyaResponse> {
let endpoint = self.endpoint(token)
return defer { [weak self] () -> Observable<MoyaResponse> in
if let existingObservable = self?.inflightRequests[endpoint] {
return existingObservable
}
let observable: Observable<MoyaResponse> = AnonymousObservable { observer in
let cancellableToken = self?.request(token) { (data, statusCode, response, error) -> () in
if let error = error {
if let statusCode = statusCode {
sendError(observer, NSError(domain: error.domain, code: statusCode, userInfo: error.userInfo))
} else {
sendError(observer, error)
}
} else {
if let data = data {
sendNext(observer, MoyaResponse(statusCode: statusCode!, data: data, response: response))
}
sendCompleted(observer)
}
}
return AnonymousDisposable {
if let weakSelf = self {
objc_sync_enter(weakSelf)
weakSelf.inflightRequests[endpoint] = nil
cancellableToken?.cancel()
objc_sync_exit(weakSelf)
}
}
}
if let weakSelf = self {
objc_sync_enter(weakSelf)
weakSelf.inflightRequests[endpoint] = observable
objc_sync_exit(weakSelf)
}
return observable
}
}
}
| mit | 5e1ee04db859ddde6cb11e6ba0530039 | 46.677966 | 314 | 0.592961 | 6.036481 | false | false | false | false |
mightydeveloper/swift | validation-test/compiler_crashers/27271-swift-typechecker-validatedecl.swift | 9 | 2359 | // RUN: not --crash %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class A : P {func a
class
b : A
func a{
{{struct d B {
struct c<T where f
struct b
class B<T where k:d B : A{
f
class a: e{enum S<T
class B<T=a{enum S<I : b : b
struct B<d { }
let a
}
let a{
class d{
b {
class b{enum e
protocol c<T where k:d=[Void{
class d=a{
class C<A{}
class A
let a
}
}
}
}protocol a {class a{
}
}}}
}
protocol a {
let f<T where H:d where H:a{{typealias d:T=Dictionary<T where T{
if true {
protocol P{
f=[]
struct B<S<S<T where H:NSObject
<T where j: a:a{
struct Q<T where H:b<T : P {}
var b : a{
l
let:NSObject
class A{
var f: a{}
var b : T where f<d { }protocol c {func a{
}
{
struct c{
class C<I : e{
var _=B{func a:{
class A
struct c
class A{
"" \(a{enum S<c<T where H:SequenceType
class B<T=k
a {
class d=k
}
var
class
protocol c<T where I : a{
class d=[Void{
class d{func p )"[ 0
class A
}
}}
let
func f {}
class d{enum C<T where j: b {
struct c<T where j: e{
enum S<T where d=[Void{
}class d{
class b:{let f=[]
protocol c
var f:T>
f:a{
class d:c
func p )"" "[ 0
f: A{
func x(a<T{
let:{
<d { }{
enum S<T : A{struct B<k
}
let:a:a{
T where d{
struct S
}
{
class d{
}
class A {
{
if true{
}{
Void{
class A : A {
}
}
}}
class b{
class d:SequenceType
}func b{}protocol P{
class d=c
}
let
{
struct d:CollectionType
}
protocol c : Poid{
let f
let:T{
class b<T where g:CollectionType
func a<T : a{
let f
class B{
}
class b{
var a
struct d=c{struct B{
class C{
f:CollectionType
class A{struct B<T where H:SequenceType
var a:a{
class a{
func x(a<T : b:a= []
let a{
class B
}
protocol c<T where I : a{
enum S
protocol c<T where H:{
}
let f:CollectionType
enum S< > S >
class d}{struct B
protocol c {
f
class A
protocol c
}}}
struct Q<h where I : A{
}
f=a{struct B{
enum S<
class C<
func a{enum e
{
protocol P{struct c<T>Bool [ 0
func x(a{typealias d=c
class B<T>
class A{
func x(a<T where j: e A {struct d{}struct Q<c<T where d}
T where f:T=[Void{}
{
}
enum e{
protocol c{}
class b{
var f
let c<T where T>i<a
class a{
let a
protocol c {
class a<h where j: A : A{
struct S<T{
struct d{
struct B{
}
func x(a{
let a
class a<T where h:{
protocol A {
}
f=[Void{
{
let a{
<T where h:T
let
struct S< {let f:CollectionType
{
let
| apache-2.0 | da2cfcbe7336bc74af5f19b5c4ed98a4 | 11.614973 | 87 | 0.641797 | 2.319567 | false | false | false | false |
vknabel/Taps | Tests/TapsTests/RxTapeTests.swift | 1 | 7904 | import XCTest
@testable import Taps
@testable import TestHarness
func withoutTests() -> [(Taps) -> Void] {
return []
}
func emptyTest(_ taps: Taps) -> Void {
return taps.test("empty test") {
$0.end()
}
}
func passingTest(_ taps: Taps) -> Void {
return taps.test("passing test") {
$0.pass()
$0.end()
}
}
func withOneTest(_ test: @escaping (Taps) -> Void = emptyTest) -> [(Taps) -> Void] {
return [emptyTest]
}
func withManyTests(_ test: @escaping (Taps) -> Void = emptyTest) -> [(Taps) -> Void] {
return [emptyTest, passingTest, describeReadmeExamples]
}
public class TapsTests: XCTestCase {
public func testStartsWithoutTests() {
let expectation = self.expectation(description: "Starts Taps run")
_ = Taps.run(
with: TapsHarness.testHarness { reports in
XCTAssertNotNil(reports.first)
XCTAssertEqual(reports.first!, TapsOutput.started, "First report must be .started")
expectation.fulfill()
},
testing: withoutTests()
)
waitForExpectations(timeout: 0.1)
}
public func testStartsWithOneTest() {
let expectation = self.expectation(description: "Starts Taps run")
_ = Taps.run(
with: .testHarness { reports in
XCTAssertNotNil(reports.first)
XCTAssertEqual(reports.first!, TapsOutput.started, "First report must be .started")
expectation.fulfill()
},
testing: withOneTest()
)
waitForExpectations(timeout: 0.1)
}
public func testStartsWithManyTests() {
let expectation = self.expectation(description: "Starts Taps run")
_ = Taps.run(
with: .testHarness { reports in
XCTAssertNotNil(reports.first)
XCTAssertEqual(reports.first!, TapsOutput.started, "First report must be .started")
expectation.fulfill()
},
testing: withManyTests()
)
waitForExpectations(timeout: 0.1)
}
public func testNaive() {
do {
let counts = try Taps.runner(testing: [
describeTestEnd,
describeTestDoesNotThrow,
describeTestDoesThrow,
describeTestOk,
describeTestNotOk,
describeTestEqual,
describeTestNotEqual,
describeTestFail,
describeTestPass,
describeTapsTodo,
describeTapsSkip
]).toBlocking().single()
XCTAssertEqual(counts?.failures, 0, "Naive tests have failed")
} catch {
XCTFail("Taps.runner.toBlocking.single failed with \(error)")
}
}
public func testReadmeExamplesStart() {
let expectation = self.expectation(description: "Starts Taps run")
_ = Taps.run(
with: .testHarness { reports in
XCTAssertNotNil(reports.first)
XCTAssertEqual(reports.first!, TapsOutput.started, "First report must be .started")
expectation.fulfill()
},
testing: [describeReadmeExamples]
)
waitForExpectations(timeout: 0.1)
}
public func testReadmeExamplesFinish() {
let expectation = self.expectation(description: "Starts Taps run")
_ = Taps.run(
with: .testHarness { reports in
XCTAssertEqual(reports.count, 10)
XCTAssertNotNil(reports.last)
XCTAssertEqual(
reports.last!,
TapsOutput.finished(TestCount(passes: 4, failures: 1)),
"Last report must be .finished"
)
expectation.fulfill()
},
testing: [describeReadmeExamples]
)
waitForExpectations(timeout: 0.1)
}
public func testReadmeExamplesFinishOnce() {
let expectation = self.expectation(description: "Starts Taps run")
var called = false
_ = Taps.run(
with: .testHarness { _ in
called = !called
XCTAssertTrue(called, "must only finish once")
expectation.fulfill()
},
testing: [describeReadmeExamples]
)
waitForExpectations(timeout: 0.1)
}
public func testReadmeExamplesAsynchronous() {
let expectation = self.expectation(description: "Starts Taps run")
_ = Taps.run(
with: .testHarness { reports in
XCTAssertEqual(reports[1], TapsOutput.testCase("asynchronous test", directive: nil), "Start test")
if case let .testPoint(testPoint, count: count, directive: directive) = reports[2] {
XCTAssertEqual(testPoint.message, "pass", "pass test")
XCTAssertEqual(testPoint.isOk, true, "pass always succeeds")
XCTAssertEqual(count.tests, 1, "first test")
XCTAssertEqual(count.passes, 1, "first test passed")
XCTAssertEqual(count.failures, 0, "none failed")
XCTAssertNil(directive, "declared without directive")
} else {
XCTFail("expected test point as output got: \(reports[2])")
}
expectation.fulfill()
},
testing: [describeReadmeExamples]
)
waitForExpectations(timeout: 200)
}
public func testReadmeExamplesSynchronous() {
let expectation = self.expectation(description: "Starts Taps run")
_ = Taps.run(
with: .testHarness { reports in
XCTAssertEqual(reports[3], TapsOutput.testCase("synchronous test", directive: nil), "Start test")
if case let .testPoint(testPoint, count: count, directive: directive) = reports[4] {
XCTAssertEqual(testPoint.message, "are equal", "equal test 1 == 1")
XCTAssertEqual(testPoint.isOk, true, "equal 1 == 1 succeeds")
XCTAssertEqual(count.tests, 2, "first test")
XCTAssertEqual(count.passes, 2, "first test passed")
XCTAssertEqual(count.failures, 0, "none failed")
XCTAssertNil(directive, "declared without directive")
} else {
XCTFail("expected test point as output")
}
expectation.fulfill()
},
testing: [describeReadmeExamples]
)
waitForExpectations(timeout: 0.1)
}
public func testReadmeExamplesReactive() {
let expectation = self.expectation(description: "Starts Taps run")
_ = Taps.run(
with: .testHarness { reports in
XCTAssertEqual(reports[5], TapsOutput.testCase("reactive test", directive: nil), "Start test")
if case let .testPoint(testPoint, count: count, directive: directive) = reports[6] {
XCTAssertEqual(testPoint.message, "should only emit 3", "equal test 3 == 3")
XCTAssertEqual(testPoint.isOk, true, "equal 3 == 3 succeeds")
XCTAssertEqual(count.tests, 3, "first test")
XCTAssertEqual(count.passes, 3, "first test passed")
XCTAssertEqual(count.failures, 0, "none failed")
XCTAssertNil(directive, "declared without directive")
} else {
XCTFail("expected test point as output")
}
if case let .testPoint(testPoint, count: count, directive: directive) = reports[7] {
XCTAssertEqual(testPoint.message, "should only emit 3", "equal test 3 == 4")
XCTAssertEqual(testPoint.isOk, false, "equal 3 == 4 fails")
XCTAssertEqual(count.tests, 4, "first test")
XCTAssertEqual(count.passes, 3, "first test passed")
XCTAssertEqual(count.failures, 1, "this failed")
XCTAssertNil(directive, "declared without directive")
} else {
XCTFail("expected test point as output")
}
if case let .testPoint(testPoint, count: count, directive: directive) = reports[8] {
XCTAssertEqual(testPoint.message, "should only emit 3", "equal test 3 == 3")
XCTAssertEqual(testPoint.isOk, true, "equal 3 == 3 succeeds")
XCTAssertEqual(count.tests, 5, "first test")
XCTAssertEqual(count.passes, 4, "first test passed")
XCTAssertEqual(count.failures, 1, "previous failed")
XCTAssertNil(directive, "declared without directive")
} else {
XCTFail("expected test point as output")
}
expectation.fulfill()
},
testing: [describeReadmeExamples]
)
waitForExpectations(timeout: 0.1)
}
}
| mit | af77ae3a28fea595ba97d6d23d667829 | 34.443946 | 106 | 0.642713 | 4.290988 | false | true | false | false |
linhaosunny/smallGifts | 小礼品/小礼品/Classes/Module/Me/Chat/DataModel/MessageModel.swift | 1 | 2706 | //
// MessageModel.swift
// 小礼品
//
// Created by 李莎鑫 on 2017/4/27.
// Copyright © 2017年 李莎鑫. All rights reserved.
// IM 消息基本模型定义
import UIKit
import QorumLogs
//MARK: 消息所有者
public enum MessageOwner : Int {
case user //: 用户
case group //: 用户群
}
//MARK: 消息来源
public enum MessageSource : Int {
case unknown //: 未知消息
case system //: 系统消息
case myself //: 用户自己
case friends //: 对方发送
}
//MARK: 消息发送状态
public enum MessageSendState : Int {
case success //: 发送成功
case fail //: 发送失败
}
//MARK: 消息发送状态
public enum MessageReadState : Int {
case unRead //: 未读取
case readed //: 已经读取
}
//MARK: 消息类型
public enum MessageType : Int {
case unknown //: 未知
case text //: 文本
case image //: 图片
case Expression //: 表情
case voice //: 语音
case video //: 视频
case url //: 链接
case postion //: 位置
case card //: 名片
case system //: 系统
case other //: 其他
}
//MARK: 消息读取状态
class MessageModel: NSObject {
//: 消息ID
var id:String?
//: 发送者ID
var uid:String?
//: 接收者ID
var fid:String?
//: 讨论组ID
var groupID:String?
//: 消息发送时间
var date:Date?
//: 发送用户信息
var fromUsr:UserModel?
//: 消息来源
var source:MessageSource = MessageSource(rawValue: 0)! {
didSet{
//: 如果是发送消息自动获取时间
if source == .myself {
date = Date()
fromUsr = AccountModel.shareAccount()!.toUserModel()
}
}
}
//: 消息所有者
var owner:MessageOwner = MessageOwner(rawValue: 0)!
//: 消息类型
var type:MessageType = MessageType(rawValue: 0)!
//: 消息读取状态
var readState:MessageReadState = MessageReadState(rawValue: 0)!
//: 消息发送状态
var sendState:MessageSendState = MessageSendState(rawValue: 0)!
//MARK: 构造方法
override init() {
super.init()
//: 初始化消息id
id = String(format: "%lld", UInt(Date().timeIntervalSince1970 * 1000))
}
//MARK: 外部接口
//: 判断是否为同一个模型
func isEqualModel(_ model: MessageModel) -> Bool {
return ((type == model.type) && (id == model.id)) ? true : false
}
}
| mit | e91196e879b635d3b53daa1f336c0c29 | 17.148438 | 78 | 0.521739 | 3.801964 | false | false | false | false |
Plotac/DouYu | DouYu/DouYu/Classes/Tools/Extension/UIBarButtonItem+Extension.swift | 2 | 1548 | //
// UIBarButtonItem+Extension.swift
// DouYu
//
// Created by Plo on 2017/6/14.
// Copyright © 2017年 Plo. All rights reserved.
//
import UIKit
extension UIBarButtonItem {
/*类方法
class func dy_barButtonItem(imageName:String,highlightedImageName:String,itemSize:CGSize) -> UIBarButtonItem {
let button = UIButton(type: .custom)
button.setImage(UIImage(named:imageName), for: .normal)
button.setImage(UIImage(named:highlightedImageName), for: .highlighted)
button.frame = CGRect(origin: CGPoint.zero, size: itemSize)
return UIBarButtonItem(customView: button)
}
*/
//swift中推荐使用 便利构造函数
/*
必须满足两个条件:1.convenience开头
2.必须在函数中明确调用一个设计构造函数(这里是UIBarButtonItem(customView:)这个函数)
3.该设计函数必须使用self调用
*/
convenience init(imageName:String, highlightedImageName:String = "", itemSize:CGSize = CGSize.zero) {
let button = UIButton(type: .custom)
button.setImage(UIImage(named:imageName), for: .normal)
if highlightedImageName != "" {
button.setImage(UIImage(named:highlightedImageName), for: .highlighted)
}
if itemSize == CGSize.zero {
button.sizeToFit()
}else {
button.frame = CGRect(origin: CGPoint.zero, size: itemSize)
}
self.init(customView:button)
}
}
| apache-2.0 | 370fc6ef09da6770b9522f17f147a99e | 27.42 | 114 | 0.62069 | 4.306061 | false | false | false | false |
e-fas/tabijimanOSS-iOS | tabijiman/ModalViewController.swift | 1 | 2959 | //
// ModalViewController.swift
// tabijiman
//
// Copyright (c) 2016 FUKUI Association of information & system industry
//
// 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
protocol ModalViewControllerDelegate {
func modalDidFinished(response: Bool)
}
class ModalViewController : UIViewController {
var delegate: ModalViewControllerDelegate! = nil
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor(white: 0.5, alpha: 0.6)
/// UI言語判断と設定
let img = (AppSetting.langUi == "ja") ? UIImage(named: "go_fukui00.png") : UIImage(named: "go_fukui00-en.png")
let imgView = UIImageView(frame: CGRectMake(0,0,194,285))
imgView.image = img
imgView.layer.position = CGPoint(x: self.view.frame.width/2, y: self.view.frame.height/2)
self.view.addSubview(imgView)
imgView.userInteractionEnabled = true
imgView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "goSpecificLocation:"))
let closeMeBtn = UIButton(frame: CGRectMake(0, 0, 300, 50))
closeMeBtn.layer.position = CGPoint(x: self.view.frame.width/2, y: self.view.frame.height - 100)
closeMeBtn.setTitle("Close", forState: .Normal)
closeMeBtn.addTarget(self, action: "closeMe:", forControlEvents: .TouchUpInside)
self.view.addSubview(closeMeBtn)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func goSpecificLocation( sender: UITapGestureRecognizer ) {
dismissViewControllerAnimated(true, completion: nil)
let response: Bool = true
self.delegate.modalDidFinished(response)
}
func closeMe(sender: AnyObject) {
dismissViewControllerAnimated(true, completion: nil)
}
} | mit | 2d7be78720e05a62c5deb2a023783bbd | 37.25974 | 118 | 0.706282 | 4.330882 | false | false | false | false |
avito-tech/Marshroute | MarshrouteTests/Sources/Routers/ModalPresentationRouterTests/ModalPresentationRouterTests_BaseRouter.swift | 1 | 15277 | import XCTest
@testable import Marshroute
final class ModalPresentationRouterTests_BaseRouter: XCTestCase
{
var detailAnimatingTransitionsHandlerSpy: AnimatingTransitionsHandlerSpy!
var router: ModalPresentationRouter!
override func setUp() {
super.setUp()
let transitionIdGenerator = TransitionIdGeneratorImpl()
let peekAndPopTransitionsCoordinator = PeekAndPopUtilityImpl()
let transitionsCoordinator = TransitionsCoordinatorImpl(
stackClientProvider: TransitionContextsStackClientProviderImpl(),
peekAndPopTransitionsCoordinator: peekAndPopTransitionsCoordinator
)
detailAnimatingTransitionsHandlerSpy = AnimatingTransitionsHandlerSpy(
transitionsCoordinator: transitionsCoordinator
)
router = BaseRouter(
routerSeed: RouterSeed(
transitionsHandlerBox: .init(
animatingTransitionsHandler: detailAnimatingTransitionsHandlerSpy
),
transitionId: transitionIdGenerator.generateNewTransitionId(),
presentingTransitionsHandler: nil,
transitionsHandlersProvider: transitionsCoordinator,
transitionIdGenerator: transitionIdGenerator,
controllersProvider: RouterControllersProviderImpl()
)
)
}
// MARK: - UIViewController
func testThatRouterCallsItsTransitionsHandlerOn_PresentModalViewControllerDerivedFrom_WithCorrectPresentationContext() {
// Given
let targetViewController = UIViewController()
var nextModuleRouterSeed: RouterSeed!
// When
router.presentModalViewControllerDerivedFrom { (routerSeed) -> UIViewController in
nextModuleRouterSeed = routerSeed
return targetViewController
}
// Then
XCTAssert(detailAnimatingTransitionsHandlerSpy.performTransitionCalled)
let presentationContext = detailAnimatingTransitionsHandlerSpy.perFormTransitionContextParameter
XCTAssertEqual(presentationContext?.transitionId, nextModuleRouterSeed.transitionId)
XCTAssert(presentationContext?.targetViewController === targetViewController)
if case .some(.animating) = presentationContext?.targetTransitionsHandlerBox {} else { XCTFail() }
XCTAssert(presentationContext?.storableParameters! is NavigationTransitionStorableParameters)
if case .some(.modal(let launchingContext)) = presentationContext?.presentationAnimationLaunchingContextBox {
XCTAssert(launchingContext.targetViewController! == targetViewController)
} else { XCTFail() }
}
func testThatRouterCallsItsTransitionsHandlerOn_PresentModalViewControllerDerivedFrom_WithCorrectPresentationContext_IfCustomAnimator() {
// Given
let targetViewController = UIViewController()
var nextModuleRouterSeed: RouterSeed!
let modalTransitionsAnimator = ModalTransitionsAnimator()
// When
router.presentModalViewControllerDerivedFrom( { (routerSeed) -> UIViewController in
nextModuleRouterSeed = routerSeed
return targetViewController
}, animator: modalTransitionsAnimator
)
// Then
XCTAssert(detailAnimatingTransitionsHandlerSpy.performTransitionCalled)
let presentationContext = detailAnimatingTransitionsHandlerSpy.perFormTransitionContextParameter
XCTAssertEqual(presentationContext?.transitionId, nextModuleRouterSeed.transitionId)
XCTAssert(presentationContext?.targetViewController === targetViewController)
if case .some(.animating) = presentationContext?.targetTransitionsHandlerBox {} else { XCTFail() }
XCTAssert(presentationContext?.storableParameters! is NavigationTransitionStorableParameters)
if case .some(.modal(let launchingContext)) = presentationContext?.presentationAnimationLaunchingContextBox {
XCTAssert(launchingContext.animator === modalTransitionsAnimator)
XCTAssert(launchingContext.targetViewController! === targetViewController)
} else { XCTFail() }
}
// MARK: - UISplitViewController
func testThatRouterCallsItsTransitionsHandlerOn_PresentModalMasterDetailViewControllerDerivedFrom_WithCorrectPresentationContext() {
// Given
let targetMasterViewController = UIViewController()
let targetDetailViewController = UIViewController()
var nextMasterDetailModuleRouterSeed: MasterDetailRouterSeed!
var nextDetailModuleRouterSeed: RouterSeed!
// When
router.presentModalMasterDetailViewControllerDerivedFrom(
deriveMasterViewController: { (routerSeed) -> UIViewController in
nextMasterDetailModuleRouterSeed = routerSeed
return targetMasterViewController
},
deriveDetailViewController: { (routerSeed) -> UIViewController in
nextDetailModuleRouterSeed = routerSeed
return targetDetailViewController
}
)
// Then
XCTAssert(detailAnimatingTransitionsHandlerSpy.performTransitionCalled)
let presentationContext = detailAnimatingTransitionsHandlerSpy.perFormTransitionContextParameter
XCTAssertEqual(presentationContext?.transitionId, nextMasterDetailModuleRouterSeed.transitionId)
XCTAssertEqual(presentationContext?.transitionId, nextDetailModuleRouterSeed.transitionId)
if case .some(.containing) = presentationContext?.targetTransitionsHandlerBox {} else { XCTFail() }
XCTAssert(presentationContext?.storableParameters! is NavigationTransitionStorableParameters)
if case .some(.modalMasterDetail) = presentationContext?.presentationAnimationLaunchingContextBox {} else { XCTFail() }
}
func testThatRouterCallsItsTransitionsHandlerOn_PresentModalMasterDetailViewControllerDerivedFrom_WithCorrectPresentationContext_IfCustomAnimator() {
// Given
let targetMasterViewController = UIViewController()
let targetDetailViewController = UIViewController()
let modalMasterDetailTransitionsAnimator = ModalMasterDetailTransitionsAnimator()
var nextMasterDetailModuleRouterSeed: MasterDetailRouterSeed!
var nextDetailModuleRouterSeed: RouterSeed!
// When
router.presentModalMasterDetailViewControllerDerivedFrom(
deriveMasterViewController: { (routerSeed) -> UIViewController in
nextMasterDetailModuleRouterSeed = routerSeed
return targetMasterViewController
},
deriveDetailViewController: { (routerSeed) -> UIViewController in
nextDetailModuleRouterSeed = routerSeed
return targetDetailViewController
},
animator: modalMasterDetailTransitionsAnimator
)
// Then
XCTAssert(detailAnimatingTransitionsHandlerSpy.performTransitionCalled)
let presentationContext = detailAnimatingTransitionsHandlerSpy.perFormTransitionContextParameter
XCTAssertEqual(presentationContext?.transitionId, nextMasterDetailModuleRouterSeed.transitionId)
XCTAssertEqual(presentationContext?.transitionId, nextDetailModuleRouterSeed.transitionId)
if case .some(.containing) = presentationContext?.targetTransitionsHandlerBox {} else { XCTFail() }
XCTAssert(presentationContext?.storableParameters! is NavigationTransitionStorableParameters)
if case .some(.modalMasterDetail(let launchingContext)) = presentationContext?.presentationAnimationLaunchingContextBox {
XCTAssert(launchingContext.animator === modalMasterDetailTransitionsAnimator)
} else { XCTFail() }
}
func testThatRouterCallsItsTransitionsHandlerOn_PresentModalMasterDetailViewControllerDerivedFrom_WithCorrectPresentationContext_IfCustomAnimator_CustomMasterNavigationController_CustomDetailNavigationController_CustomSplitViewController() {
// Given
let targetMasterViewController = UIViewController()
let targetDetailViewController = UIViewController()
let splitViewController = UISplitViewController()
let modalMasterDetailTransitionsAnimator = ModalMasterDetailTransitionsAnimator()
var nextMasterDetailModuleRouterSeed: MasterDetailRouterSeed!
var nextDetailModuleRouterSeed: RouterSeed!
// When
router.presentModalMasterDetailViewControllerDerivedFrom(
deriveMasterViewController: { (routerSeed) -> UIViewController in
nextMasterDetailModuleRouterSeed = routerSeed
return targetMasterViewController
},
deriveDetailViewController: { (routerSeed) -> UIViewController in
nextDetailModuleRouterSeed = routerSeed
return targetDetailViewController
},
animator: modalMasterDetailTransitionsAnimator,
masterNavigationController: UINavigationController(),
detailNavigationController: UINavigationController(),
splitViewController: splitViewController
)
// Then
XCTAssert(detailAnimatingTransitionsHandlerSpy.performTransitionCalled)
let presentationContext = detailAnimatingTransitionsHandlerSpy.perFormTransitionContextParameter
XCTAssertEqual(presentationContext?.transitionId, nextMasterDetailModuleRouterSeed.transitionId)
XCTAssertEqual(presentationContext?.transitionId, nextDetailModuleRouterSeed.transitionId)
if case .some(.containing) = presentationContext?.targetTransitionsHandlerBox {} else { XCTFail() }
XCTAssert(presentationContext?.storableParameters! is NavigationTransitionStorableParameters)
if case .some(.modalMasterDetail(let launchingContext)) = presentationContext?.presentationAnimationLaunchingContextBox {
XCTAssert(launchingContext.animator === modalMasterDetailTransitionsAnimator)
XCTAssert(launchingContext.targetViewController! === splitViewController)
} else { XCTFail() }
}
// MARK: - UIViewController in UINavigationController
func testThatRouterCallsItsTransitionsHandlerOn_PresentModalNavigationControllerWithRootViewControllerDerivedFrom_WithCorrectPresentationContext() {
// Given
let targetViewController = UIViewController()
var nextModuleRouterSeed: RouterSeed!
// When
router.presentModalNavigationControllerWithRootViewControllerDerivedFrom { (routerSeed) -> UIViewController in
nextModuleRouterSeed = routerSeed
return targetViewController
}
// Then
XCTAssert(detailAnimatingTransitionsHandlerSpy.performTransitionCalled)
let presentationContext = detailAnimatingTransitionsHandlerSpy.perFormTransitionContextParameter
XCTAssertEqual(presentationContext?.transitionId, nextModuleRouterSeed.transitionId)
XCTAssert(presentationContext?.targetViewController === targetViewController)
if case .some(.animating) = presentationContext?.targetTransitionsHandlerBox {} else { XCTFail() }
XCTAssert(presentationContext?.storableParameters! is NavigationTransitionStorableParameters)
if case .some(.modalNavigation(let launchingContext)) = presentationContext?.presentationAnimationLaunchingContextBox {
XCTAssert(launchingContext.targetViewController! == targetViewController)
} else { XCTFail() }
}
func testThatRouterCallsItsTransitionsHandlerOn_PresentModalNavigationControllerWithRootViewControllerDerivedFrom_WithCorrectPresentationContext_IfCustomAnimator() {
// Given
let targetViewController = UIViewController()
var nextModuleRouterSeed: RouterSeed!
let modalNavigationTransitionsAnimator = ModalNavigationTransitionsAnimator()
// When
router.presentModalNavigationControllerWithRootViewControllerDerivedFrom( { (routerSeed) -> UIViewController in
nextModuleRouterSeed = routerSeed
return targetViewController
}, animator: modalNavigationTransitionsAnimator
)
// Then
XCTAssert(detailAnimatingTransitionsHandlerSpy.performTransitionCalled)
let presentationContext = detailAnimatingTransitionsHandlerSpy.perFormTransitionContextParameter
XCTAssertEqual(presentationContext?.transitionId, nextModuleRouterSeed.transitionId)
XCTAssert(presentationContext?.targetViewController === targetViewController)
if case .some(.animating) = presentationContext?.targetTransitionsHandlerBox {} else { XCTFail() }
XCTAssert(presentationContext?.storableParameters! is NavigationTransitionStorableParameters)
if case .some(.modalNavigation(let launchingContext)) = presentationContext?.presentationAnimationLaunchingContextBox {
XCTAssert(launchingContext.animator === modalNavigationTransitionsAnimator)
XCTAssert(launchingContext.targetViewController! === targetViewController)
} else { XCTFail() }
}
func testThatRouterCallsItsTransitionsHandlerOn_PresentModalNavigationControllerWithRootViewControllerDerivedFrom_WithCorrectPresentationContext_IfCustomAnimator_CustomNavigationController() {
// Given
let targetViewController = UIViewController()
let navigationController = UINavigationController()
var nextModuleRouterSeed: RouterSeed!
let modalNavigationTransitionsAnimator = ModalNavigationTransitionsAnimator()
// When
router.presentModalNavigationControllerWithRootViewControllerDerivedFrom( { (routerSeed) -> UIViewController in
nextModuleRouterSeed = routerSeed
return targetViewController
}, animator: modalNavigationTransitionsAnimator,
navigationController: navigationController
)
// Then
XCTAssert(detailAnimatingTransitionsHandlerSpy.performTransitionCalled)
let presentationContext = detailAnimatingTransitionsHandlerSpy.perFormTransitionContextParameter
XCTAssertEqual(presentationContext?.transitionId, nextModuleRouterSeed.transitionId)
XCTAssert(presentationContext?.targetViewController === targetViewController)
if case .some(.animating) = presentationContext?.targetTransitionsHandlerBox {} else { XCTFail() }
XCTAssert(presentationContext?.storableParameters! is NavigationTransitionStorableParameters)
if case .some(.modalNavigation(let launchingContext)) = presentationContext?.presentationAnimationLaunchingContextBox {
XCTAssert(launchingContext.animator === modalNavigationTransitionsAnimator)
XCTAssert(launchingContext.targetViewController! === targetViewController)
XCTAssert(launchingContext.targetNavigationController! === navigationController)
} else { XCTFail() }
}
}
| mit | 57bcc679413e7c7d22ce074550b2c46b | 53.173759 | 245 | 0.73411 | 7.327098 | false | false | false | false |
dobleuber/my-swift-exercises | Project10/Project10/ViewController.swift | 1 | 3344 | //
// ViewController.swift
// Project10
//
// Created by Wbert Castro on 27/06/17.
// Copyright © 2017 Wbert Castro. All rights reserved.
//
import UIKit
class ViewController: UICollectionViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var people = [Person]()
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addNewPerson))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return people.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Person", for: indexPath) as! PersonCell
let person = people[indexPath.item]
cell.name.text = person.name
let path = getDocumentsDirectory().appendingPathComponent(person.image)
cell.imageView.image = UIImage(contentsOfFile: path.path)
let layer = cell.imageView.layer
layer.borderColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.3).cgColor
layer.borderWidth = 2
layer.cornerRadius = 3
cell.layer.cornerRadius = 7
return cell
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let person = people[indexPath.item]
let ac = UIAlertController(title: "Rename person", message: nil, preferredStyle: .alert)
ac.addTextField()
ac.addAction(UIAlertAction(title: "Cancel", style: .cancel))
ac.addAction(UIAlertAction(title: "OK", style: .default) { [unowned self, ac] _ in
let newName = ac.textFields![0]
person.name = newName.text!
self.collectionView?.reloadData()
})
present(ac, animated: true)
}
func addNewPerson() {
let picker = UIImagePickerController()
picker.allowsEditing = true
picker.delegate = self
present(picker, animated: true)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
guard let image = info[UIImagePickerControllerEditedImage] as? UIImage else {
return
}
let imageName = UUID().uuidString
let imagePath = getDocumentsDirectory().appendingPathComponent(imageName)
if let jpegData = UIImageJPEGRepresentation(image, 80) {
try? jpegData.write(to: imagePath)
}
let person = Person(name: "Unknown", image: imageName)
people.append(person)
collectionView?.reloadData()
dismiss(animated: true)
}
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
return documentsDirectory
}
}
| mit | efef94641a2c773bdc9883f07fb5c56c | 33.822917 | 132 | 0.647622 | 5.391935 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureTransaction/Sources/FeatureTransactionUI/PendingTransactionPage/PendingTransactionStateProvider/SellPendingTransactionStateProvider.swift | 1 | 5025 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import FeatureTransactionDomain
import Foundation
import Localization
import MoneyKit
import PlatformKit
import RxSwift
final class SellPendingTransactionStateProvider: PendingTransactionStateProviding {
private typealias LocalizationIds = LocalizationConstants.Transaction.Sell.Completion
// MARK: - PendingTransactionStateProviding
func connect(state: Observable<TransactionState>) -> Observable<PendingTransactionPageState> {
state.compactMap { [weak self] state -> PendingTransactionPageState? in
guard let self = self else { return nil }
switch state.executionStatus {
case .inProgress, .pending, .notStarted:
return self.pending(state: state)
case .completed:
if state.source is NonCustodialAccount {
return self.successNonCustodial(state: state)
} else {
return self.success(state: state)
}
case .error:
return nil
}
}
}
// MARK: - Private Functions
private func successNonCustodial(state: TransactionState) -> PendingTransactionPageState {
PendingTransactionPageState(
title: String(
format: LocalizationIds.Pending.title,
state.source?.currencyType.code ?? "",
state.destination?.currencyType.code ?? ""
),
subtitle: LocalizationIds.Pending.description,
compositeViewType: .composite(
.init(
baseViewType: .image(state.asset.logoResource),
sideViewAttributes: .init(
type: .image(.local(name: "clock-error-icon", bundle: .platformUIKit)),
position: .radiusDistanceFromCenter
),
cornerRadiusRatio: 0.5
)
),
effect: .complete,
primaryButtonViewModel: .primary(with: LocalizationIds.Success.action),
action: state.action
)
}
private func success(state: TransactionState) -> PendingTransactionPageState {
PendingTransactionPageState(
title: String(
format: LocalizationIds.Success.title,
state.amount.displayString
),
subtitle: String(
format: LocalizationIds.Success.description,
state.destination?.currencyType.displayCode ?? ""
),
compositeViewType: .composite(
.init(
baseViewType: .image(state.asset.logoResource),
sideViewAttributes: .init(
type: .image(.local(name: "v-success-icon", bundle: .platformUIKit)),
position: .radiusDistanceFromCenter
),
cornerRadiusRatio: 0.5
)
),
effect: .complete,
primaryButtonViewModel: .primary(with: LocalizationIds.Success.action),
action: state.action
)
}
private func pending(state: TransactionState) -> PendingTransactionPageState {
let amount = state.amount
let received: MoneyValue
switch state.moneyValueFromDestination() {
case .success(let value):
received = value
case .failure:
switch state.destination {
case nil:
fatalError("Expected a Destination: \(state)")
case let account as SingleAccount:
received = MoneyValue.zero(currency: account.currencyType)
case let cryptoTarget as CryptoTarget:
received = MoneyValue.zero(currency: cryptoTarget.asset)
default:
fatalError("Unsupported state.destination: \(String(reflecting: state.destination))")
}
}
let title: String
if !received.isZero, !amount.isZero {
// If we have both sent and receive values:
title = String(
format: LocalizationIds.Pending.title,
amount.displayString,
received.displayString
)
} else {
// If we have invalid inputs but we should continue.
title = String(
format: LocalizationIds.Pending.title,
amount.displayCode,
received.displayCode
)
}
return .init(
title: title,
subtitle: LocalizationIds.Pending.description,
compositeViewType: .composite(
.init(
baseViewType: .image(state.asset.logoResource),
sideViewAttributes: .init(type: .loader, position: .radiusDistanceFromCenter),
cornerRadiusRatio: 0.5
)
),
action: state.action
)
}
}
| lgpl-3.0 | 495638d2cf64d76c2145dd32aa02db2b | 36.774436 | 101 | 0.56051 | 5.702611 | false | false | false | false |
ChrisLowe-Takor/ALCameraViewController | Example/ViewController.swift | 1 | 1744 | //
// ViewController.swift
// ALCameraViewController
//
// Created by Alex Littlejohn on 2015/06/17.
// Copyright (c) 2015 zero. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var croppingEnabled: Bool = false
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func openCamera(sender: AnyObject) {
let cameraViewController = ALCameraViewController(croppingEnabled: croppingEnabled) { (image) -> Void in
self.imageView.image = image
self.dismissViewControllerAnimated(true, completion: nil)
}
presentViewController(cameraViewController, animated: true, completion: nil)
}
@IBAction func openLibrary(sender: AnyObject) {
let libraryViewController = ALCameraViewController.imagePickerViewController(croppingEnabled) { (image) -> Void in
self.imageView.image = image
self.dismissViewControllerAnimated(true, completion: nil)
}
presentViewController(libraryViewController, animated: true, completion: nil)
}
@IBAction func openCropper(sender: AnyObject) {
let image = UIImage(named: "image.jpg")!
let croppingViewController = ALCameraViewController.croppingViewController(image, croppingEnabled: true) { image in
self.imageView.image = image
self.dismissViewControllerAnimated(true, completion: nil)
}
presentViewController(croppingViewController, animated: true, completion: nil)
}
@IBAction func croppingChanged(sender: AnyObject) {
croppingEnabled = !croppingEnabled
}
}
| mit | ef0843981731c9f5d777c533293f99cb | 31.296296 | 123 | 0.672018 | 5.253012 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureDashboard/Sources/FeatureDashboardUI/Components/PortfolioEmptyStateTableViewCell/PortfolioEmptyStateTableViewCell.swift | 1 | 2577 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import BlockchainComponentLibrary
import Foundation
import PlatformKit
import PlatformUIKit
import RxCocoa
import RxSwift
import SwiftUI
import UIComponentsKit
import UIKit
final class PortfolioEmptyStateTableViewCell: UITableViewCell {
// MARK: - Private Properties
private let title: UILabel = .init()
private let subtitle: UILabel = .init()
private let cta: ButtonView = .init()
private let presenter: PortfolioEmptyStatePresenter = .init()
private var minimalDoubleButton: UIHostingController<MinimalDoubleButton<Icon, Icon>>!
// MARK: - Setup
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setup()
}
@available(*, unavailable)
required init?(coder: NSCoder) { nil }
private func setup() {
minimalDoubleButton = UIHostingController(
rootView: MinimalDoubleButton(
leadingTitle: "Receive",
leadingLeadingView: { Icon.qrCode },
leadingAction: { [presenter] in
presenter.didTapReceive.accept(())
},
trailingTitle: "Deposit",
trailingLeadingView: { Icon.bank },
trailingAction: { [presenter] in
presenter.didTapDeposit.accept(())
}
)
)
title.numberOfLines = 0
subtitle.numberOfLines = 0
title.content = presenter.title
subtitle.content = presenter.subtitle
cta.viewModel = presenter.cta
let button: UIView! = minimalDoubleButton.view
contentView.addSubview(title)
contentView.addSubview(subtitle)
contentView.addSubview(cta)
contentView.addSubview(button)
title.layoutToSuperview(axis: .horizontal, offset: 24)
subtitle.layoutToSuperview(axis: .horizontal, offset: 24)
cta.layoutToSuperview(axis: .horizontal, offset: 24)
button.layoutToSuperview(axis: .horizontal, offset: 24)
title.layoutToSuperview(.top, offset: 70)
title.layout(dimension: .height, to: 32)
title.layout(edge: .bottom, to: .top, of: subtitle)
subtitle.layout(edge: .bottom, to: .top, of: cta, offset: -24)
cta.layout(dimension: .height, to: 48)
cta.layout(edge: .bottom, to: .top, of: button, offset: -16)
button.layoutToSuperview(.centerX)
button.layoutToSuperview(.bottom, offset: 24)
}
}
| lgpl-3.0 | 6f2d71145b3ea011953708b1fc9c6fcf | 33.346667 | 90 | 0.645186 | 4.77037 | false | false | false | false |
toshiapp/toshi-ios-client | Toshi/Views/Cells/AvatarTitleSubtitleDetailsBadgeCell.swift | 1 | 3736 | // Copyright (c) 2018 Token Browser, Inc
//
// This program 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.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import UIKit
final class AvatarTitleSubtitleDetailsBadgeCell: BasicTableViewCell {
override func prepareForReuse() {
super.prepareForReuse()
leftImageView.image = nil
titleTextField.text = nil
subtitleLabel.text = nil
detailsLabel.text = nil
badgeLabel.text = nil
}
override func addSubviewsAndConstraints() {
contentView.addSubview(leftImageView)
contentView.addSubview(titleTextField)
contentView.addSubview(subtitleLabel)
contentView.addSubview(detailsLabel)
contentView.addSubview(badgeView)
setupLeftImageView()
setupTitleTextField()
setupSubtitleLabel()
setupDetailsLabel()
setupBadgeView()
}
private func setupLeftImageView() {
leftImageView.size(CGSize(width: BasicTableViewCell.imageSize, height: BasicTableViewCell.imageSize))
leftImageView.centerY(to: contentView)
leftImageView.left(to: contentView, offset: BasicTableViewCell.horizontalMargin)
leftImageView.top(to: contentView, offset: BasicTableViewCell.imageMargin, relation: .equalOrGreater, priority: .defaultLow)
leftImageView.bottom(to: contentView, offset: -BasicTableViewCell.imageMargin, relation: .equalOrGreater, priority: .defaultLow)
}
private func setupTitleTextField() {
titleTextField.top(to: contentView, offset: BasicTableViewCell.horizontalMargin)
titleTextField.leftToRight(of: leftImageView, offset: BasicTableViewCell.largeInterItemMargin)
titleTextField.rightToLeft(of: detailsLabel, offset: -BasicTableViewCell.interItemMargin)
titleTextField.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
}
private func setupSubtitleLabel() {
subtitleLabel.topToBottom(of: titleTextField, offset: BasicTableViewCell.smallVerticalMargin)
subtitleLabel.leftToRight(of: leftImageView, offset: BasicTableViewCell.largeInterItemMargin)
subtitleLabel.rightToLeft(of: detailsLabel, offset: -BasicTableViewCell.horizontalMargin)
subtitleLabel.bottom(to: contentView, offset: -BasicTableViewCell.verticalMargin)
subtitleLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
}
private func setupDetailsLabel() {
detailsLabel.top(to: contentView, offset: BasicTableViewCell.horizontalMargin)
detailsLabel.right(to: contentView, offset: -BasicTableViewCell.horizontalMargin)
}
private func setupBadgeView() {
badgeView.bottom(to: contentView, offset: -BasicTableViewCell.horizontalMargin)
badgeView.right(to: contentView, offset: -BasicTableViewCell.horizontalMargin)
badgeView.height(BasicTableViewCell.badgeViewSize)
badgeView.width(BasicTableViewCell.badgeViewSize, relation: .equalOrGreater)
badgeView.setContentCompressionResistancePriority(.required, for: .horizontal)
badgeView.topToBottom(of: detailsLabel, offset: BasicTableViewCell.smallVerticalMargin)
}
}
| gpl-3.0 | e17736f391938ec0b703ea0e025cba09 | 45.7 | 136 | 0.748126 | 5.232493 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureAuthentication/Sources/FeatureAuthenticationData/WalletAuthentication/NetworkClients/DeviceVerificationClient/DeviceVerificationClient.swift | 1 | 7800 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Combine
import DIKit
import FeatureAuthenticationDomain
import Foundation
import NetworkKit
import ToolKit
final class DeviceVerificationClient: DeviceVerificationClientAPI {
// MARK: - Types
private enum Path {
static let wallet = ["wallet"]
static let emailReminder = ["auth", "email-reminder"]
static let pollWalletInfo = ["wallet", "poll-for-wallet-info"]
}
private enum Parameters {
enum AuthorizeApprove {
static let method = "method"
static let comfirmApproval = "confirm_approval"
static let token = "token"
}
enum AuthorizeVerifyDevice {
static let method = "method"
static let fromSessionId = "fromSessionId"
static let payload = "payload"
static let confirmDevice = "confirm_device"
}
}
private enum HeaderKey: String {
case cookie
}
// MARK: - Properties
private let walletRequestBuilder: RequestBuilder
private let defaultRequestBuilder: RequestBuilder
private let networkAdapter: NetworkAdapterAPI
// MARK: - Setup
init(
networkAdapter: NetworkAdapterAPI = resolve(),
walletRequestBuilder: RequestBuilder = resolve(tag: DIKitContext.wallet),
defaultRequestBuilder: RequestBuilder = resolve()
) {
self.networkAdapter = networkAdapter
self.walletRequestBuilder = walletRequestBuilder
self.defaultRequestBuilder = defaultRequestBuilder
}
// MARK: - Methods
func sendGuidReminder(
sessionToken: String,
emailAddress: String,
captcha: String
) -> AnyPublisher<Void, NetworkError> {
struct Payload: Encodable {
let email: String
let captcha: String
let siteKey: String
let product: String
}
let headers = [HttpHeaderField.authorization: "Bearer \(sessionToken)"]
let payload = Payload(
email: emailAddress,
captcha: captcha,
siteKey: AuthenticationKeys.googleRecaptchaSiteKey,
product: "WALLET"
)
let request = defaultRequestBuilder.post(
path: Path.emailReminder,
body: try? payload.encode(),
headers: headers
)!
return networkAdapter.perform(request: request)
}
func authorizeApprove(
sessionToken: String,
emailCode: String
) -> AnyPublisher<AuthorizeApproveResponse, NetworkError> {
let headers = [HeaderKey.cookie.rawValue: "SID=\(sessionToken)"]
let parameters = [
URLQueryItem(
name: Parameters.AuthorizeApprove.method,
value: "authorize-approve"
),
URLQueryItem(
name: Parameters.AuthorizeApprove.comfirmApproval,
value: "true"
),
URLQueryItem(
name: Parameters.AuthorizeApprove.token,
value: emailCode
)
]
let data = RequestBuilder.body(from: parameters)
let request = walletRequestBuilder.post(
path: Path.wallet,
body: data,
headers: headers,
contentType: .formUrlEncoded
)!
return networkAdapter.perform(request: request)
}
func pollForWalletInfo(
sessionToken: String
) -> AnyPublisher<WalletInfoPollResultResponse, NetworkError> {
let headers = [HttpHeaderField.authorization: "Bearer \(sessionToken)"]
let request = walletRequestBuilder.get(
path: Path.pollWalletInfo,
headers: headers
)!
func decodeType(
response: RawServerResponse
) -> AnyPublisher<WalletInfoPollResponse.ResponseType, NetworkError> {
Just(Result { try Data(response.data.utf8).decode(to: WalletInfoPollResponse.self).responseType })
.setFailureType(to: NetworkError.self)
.flatMap { result -> AnyPublisher<WalletInfoPollResponse.ResponseType, NetworkError> in
switch result {
case .success(let type):
return .just(type)
case .failure(let error):
return .failure(
NetworkError(
request: request.urlRequest,
type: .payloadError(.badData(rawPayload: error.localizedDescription))
)
)
}
}
.eraseToAnyPublisher()
}
func decodePayload(
responseType: WalletInfoPollResponse.ResponseType,
response: RawServerResponse
) -> AnyPublisher<WalletInfoPollResultResponse, NetworkError> {
switch responseType {
case .walletInfo:
return Just(Result { try Data(response.data.utf8).decode(to: WalletInfo.self) })
.setFailureType(to: NetworkError.self)
.flatMap { result -> AnyPublisher<WalletInfoPollResultResponse, NetworkError> in
switch result {
case .success(let walletInfo):
return .just(.walletInfo(walletInfo))
case .failure(let error):
return .failure(
NetworkError(
request: request.urlRequest,
type: .payloadError(.badData(rawPayload: error.localizedDescription))
)
)
}
}
.eraseToAnyPublisher()
case .continuePolling:
return .just(.continuePolling)
case .requestDenied:
return .just(.requestDenied)
}
}
return networkAdapter.perform(request: request)
.flatMap { response -> AnyPublisher<WalletInfoPollResultResponse, NetworkError> in
decodeType(response: response)
.flatMap { type -> AnyPublisher<WalletInfoPollResultResponse, NetworkError> in
decodePayload(responseType: type, response: response)
}
.eraseToAnyPublisher()
}
.eraseToAnyPublisher()
}
func authorizeVerifyDevice(
from sessionToken: String,
payload: String,
confirmDevice: Bool?
) -> AnyPublisher<Void, NetworkError> {
var parameters = [
URLQueryItem(
name: Parameters.AuthorizeVerifyDevice.method,
value: "authorize-verify-device"
),
URLQueryItem(
name: Parameters.AuthorizeVerifyDevice.fromSessionId,
value: sessionToken
),
URLQueryItem(
name: Parameters.AuthorizeVerifyDevice.payload,
value: payload
)
]
if let confirm = confirmDevice {
parameters.append(
URLQueryItem(
name: Parameters.AuthorizeVerifyDevice.confirmDevice,
value: String(confirm)
)
)
}
let data = RequestBuilder.body(from: parameters)
let request = walletRequestBuilder.post(
path: Path.wallet,
body: data,
contentType: .formUrlEncoded
)!
return networkAdapter.perform(request: request)
.mapToVoid()
.eraseToAnyPublisher()
}
}
| lgpl-3.0 | e990b8c3c39b61d382a0ec2fceed69a0 | 34.130631 | 110 | 0.554174 | 5.850713 | false | false | false | false |
gouyz/GYZBaking | baking/Pods/SKPhotoBrowser/SKPhotoBrowser/SKPhotoBrowserOptions.swift | 4 | 1628 | //
// SKPhotoBrowserOptions.swift
// SKPhotoBrowser
//
// Created by 鈴木 啓司 on 2016/08/18.
// Copyright © 2016年 suzuki_keishi. All rights reserved.
//
import UIKit
public struct SKPhotoBrowserOptions {
public static var displayStatusbar: Bool = false
public static var displayAction: Bool = true
public static var shareExtraCaption: String? = nil
public static var actionButtonTitles: [String]?
public static var displayToolbar: Bool = true
public static var displayCounterLabel: Bool = true
public static var displayBackAndForwardButton: Bool = true
public static var disableVerticalSwipe: Bool = false
public static var displayCloseButton: Bool = true
public static var displayDeleteButton: Bool = false
public static var displayHorizontalScrollIndicator: Bool = true
public static var displayVerticalScrollIndicator: Bool = true
public static var bounceAnimation: Bool = false
public static var enableZoomBlackArea: Bool = true
public static var enableSingleTapDismiss: Bool = false
public static var backgroundColor: UIColor = .black
}
public struct SKCaptionOptions {
public static var textColor: UIColor = .white
public static var textAlignment: NSTextAlignment = .center
public static var numberOfLine: Int = 3
public static var lineBreakMode: NSLineBreakMode = .byTruncatingTail
public static var font: UIFont = .systemFont(ofSize: 17.0)
}
public struct SKToolbarOptions {
public static var textColor: UIColor = .white
public static var font: UIFont = .systemFont(ofSize: 17.0)
}
| mit | b1a5ef85e1f662481f927feb09b295c2 | 33.404255 | 72 | 0.739023 | 4.870482 | false | false | false | false |
colemancda/HTTP-Server | Representor/HTTP/Adapters/HTTPSirenAdapter.swift | 1 | 5549 | //
//
//
//
//
//
//private func sirenFieldToAttribute(builder: HTTPTransitionBuilder)(field: [String: Any]) {
//
// if let name = field["name"] as? String {
//
// let title = field["title"] as? String
// let value: Any? = field["value"]
//
// builder.addAttribute(name, title: title, value: value, defaultValue: nil)
//
// }
//
//}
//
//private func sirenActionToTransition(action:[String: Any]) -> (name: String, transition: HTTPTransition)? {
//
// if let name = action["name"] as? String,
// href = action["href"] as? String {
//
// let transition = HTTPTransition(uri: href) { builder in
//
// if let method = action["method"] as? String {
//
// builder.method = method
//
// }
//
// if let contentType = action["type"] as? String {
//
// builder.suggestedContentTypes = [contentType]
//
// }
//
// if let fields = action["fields"] as? [[String: Any]] {
//
// fields.forEach(sirenFieldToAttribute(builder))
//
// }
//
// }
//
// return (name, transition)
//
// }
//
// return nil
//
//}
//
//private func inputPropertyToSirenField(name: String, inputProperty: InputProperty<Any>) -> [String: Any] {
//
// var field: [String: Any] = [
// "name": name
// ]
//
// if let value: Any = inputProperty.value {
//
// field["value"] = "\(value)"
//
// }
//
// if let title = inputProperty.title {
//
// field["title"] = title
//
// }
//
// return field
//
//}
//
//private func transitionToSirenAction(relation: String, transition: HTTPTransition) -> [String: Any] {
//
// var action:[String: Any] = [
// "href": transition.uri,
// "name": relation,
// "method": transition.method
// ]
//
// if let contentType = transition.suggestedContentTypes.first {
//
// action["type"] = contentType
//
// }
//
// if transition.attributes.count > 0 {
//
// action["fields"] = transition.attributes.map(inputPropertyToSirenField)
//
// }
//
// return action
//
//}
//
//public func deserializeSiren(siren: JSON) -> Representor<HTTPTransition> {
//
// var representors: [String: [Representor<HTTPTransition>]] = [:]
// var transitions: [String: HTTPTransition] = [:]
// var attributes: [String: Any] = [:]
//
// if let sirenLinks = siren["links"] as? [[String: Any]] {
//
// for link in sirenLinks {
//
// if let href = link["href"] as? String,
// relations = link["rel"] as? [String] {
//
// for relation in relations {
//
// transitions[relation] = HTTPTransition(uri: href)
//
// }
//
// }
//
// }
//
// }
//
// if let entities = siren["entities"] as? [[String: Any]] {
//
// for entity in entities {
//
// let representor = deserializeSiren(entity)
//
// if let relations = entity["rel"] as? [String] {
//
// for relation in relations {
//
// if var reps = representors[relation] {
//
// reps.append(representor)
// representors[relation] = reps
//
// } else {
//
// representors[relation] = [representor]
//
// }
//
// }
//
// }
//
// }
//
// }
//
// if let actions = siren["actions"] as? [[String: Any]] {
//
// for action in actions {
//
// if let (name, transition) = sirenActionToTransition(action) {
//
// transitions[name] = transition
//
// }
//
// }
//
// }
//
// if let properties = siren["properties"] as? [String: Any] {
//
// attributes = properties
//
// }
//
// return Representor<HTTPTransition>(transitions: transitions, representors: representors, attributes: attributes, metadata: [:])
//
//}
//
//public func serializeSiren(representor: Representor<HTTPTransition>) -> [String: Any] {
//
// var representation: [String: Any] = [:]
//
// if representor.representors.count > 0 {
//
// var entities: [[String: Any]] = [[:]]
//
// for (relation, representorSet) in representor.representors {
//
// for representor in representorSet {
//
// var representation = serializeSiren(representor)
// representation["rel"] = [relation]
// entities.append(representation)
//
// }
//
// }
//
// representation["entities"] = entities
//
// }
//
// if representor.attributes.count > 0 {
//
// representation["properties"] = representor.attributes
//
// }
//
// let links = representor.transitions.filter { $1.method == "GET" }
// let actions = representor.transitions.filter { $1.method != "GET" }
//
// if links.count > 0 {
//
// var linkRepresentations: [[String: Any]] = [[:]]
//
// for link in links {
//
// let linkRepresentation: [String: Any] = [
// "rel": [link.0],
// "href": link.1.uri
// ]
//
// linkRepresentations.append(linkRepresentation)
//
// }
//
// representation["links"] = linkRepresentations
//
// }
//
// if actions.count > 0 {
//
// representation["actions"] = actions.map(transitionToSirenAction)
//
// }
//
// return representation
//
//}
| mit | cb0ff730e6bf62cc77dec61ee0e042f0 | 22.217573 | 133 | 0.506398 | 3.584625 | false | false | false | false |
kalvish21/AndroidMessenger | AndroidMessengerMacDesktopClient/AndroidMessenger/Classes/MessageHandler.swift | 1 | 12990 | //
// MessageHandler.swift
// AndroidMessenger
//
// Created by Kalyan Vishnubhatla on 3/27/16.
// Copyright © 2016 Kalyan Vishnubhatla. All rights reserved.
//
import Cocoa
import SwiftyJSON
import libPhoneNumber_iOS
class MessageHandler {
lazy var contactsHandler: ContactsHandler = {
return ContactsHandler()
}()
func setMessageDetailsFromDictionary(sms: Message, dictionary: Dictionary<String, AnyObject>, is_pending: Bool) -> Message {
NSLog("%@", dictionary)
sms.id = Int((dictionary["id"] as! NSString).intValue)
sms.thread_id = Int((dictionary["thread_id"] as! NSString).intValue)
sms.address = String(dictionary["address"] as! NSString)
sms.msg = String(dictionary["msg"] as! NSString)
sms.number = String(dictionary["number"] as! NSString)
sms.read = Bool(dictionary["read"] as! Bool)
sms.received = Bool(dictionary["received"] as! Bool)
sms.time = NSDate.dateFromMilliseconds(Double(dictionary["time"] as! String)!)
sms.sms = String(dictionary["type"] as! NSString) == "sms"
sms.pending = is_pending
sms.error = dictionary["failed"] as! Bool
return sms
}
func setMessageDetailsFromDictionaryForMms(moc: NSManagedObjectContext, sms: Message, dictionary: Dictionary<String, AnyObject>, is_pending: Bool) -> Message {
NSLog("%@", dictionary)
sms.id = Int((dictionary["id"] as! NSString).intValue)
sms.thread_id = Int((dictionary["thread_id"] as! NSString).intValue)
sms.address = String(dictionary["address"] as! NSString)
sms.number = String(dictionary["address"] as! NSString)
sms.read = Bool(dictionary["read"] as! Bool)
sms.msg = ""
sms.received = Bool(dictionary["received"] as! Bool)
sms.time = NSDate.dateFromSeconds(Double(dictionary["time"] as! String)!)
sms.sms = String(dictionary["type"] as! NSString) == "sms"
sms.pending = is_pending
let parts: Array<Dictionary<String, AnyObject>> = dictionary["parts"] as! Array<Dictionary<String, AnyObject>>
if sms.messageparts == nil {
sms.messageparts = NSMutableOrderedSet()
}
for part in 0...parts.count-1{
let dict = parts[part]
switch(dict["type"] as! String) {
case "text/plain":
let mmspart = NSEntityDescription.insertNewObjectForEntityForName("MessagePart", inManagedObjectContext: moc) as! MessagePart
mmspart.content_type = dict["type"] as! String
mmspart.id = Int(dict["part_id"] as! String)!
mmspart.message_id = Int(dict["mid"] as! String)!
sms.msg = dict["msg"] as! String
(sms.messageparts as! NSMutableOrderedSet).addObject(mmspart)
break
case "image/jpeg", "image/jpg", "image/png", "image/gif", "image/bmp":
let mmspart = NSEntityDescription.insertNewObjectForEntityForName("MessagePart", inManagedObjectContext: moc) as! MessagePart
mmspart.content_type = dict["type"] as! String
mmspart.id = Int(dict["part_id"] as! String)!
mmspart.message_id = Int(dict["mid"] as! String)!
(sms.messageparts as! NSMutableOrderedSet).addObject(mmspart)
break
default:
break
}
}
return sms
}
func setMessageDetailsFromJsonObject(sms: Message, object: JSON, is_pending: Bool) -> Message {
sms.id = Int((object["id"].stringValue))
sms.thread_id = Int((object["thread_id"].stringValue))
sms.address = String(object["address"].stringValue)
sms.msg = String(object["msg"].stringValue)
sms.number = String(object["number"].stringValue)
sms.read = Bool(object["read"].boolValue)
sms.received = Bool(object["received"].boolValue)
sms.time = NSDate.dateFromMilliseconds(Double(object["time"].stringValue)!)
sms.sms = object["type"].stringValue == "sms"
sms.pending = is_pending
sms.error = object["failed"].boolValue
return sms
}
func setMessageDetailsFromJsonObjectForMms(moc: NSManagedObjectContext, sms: Message, dictionary: JSON, is_pending: Bool) -> Message {
sms.id = Int((dictionary["id"].stringValue))
sms.thread_id = Int((dictionary["thread_id"].stringValue))
sms.address = String(dictionary["address"].stringValue)
sms.number = String(dictionary["address"].stringValue)
sms.read = Bool(dictionary["read"].boolValue)
sms.msg = ""
sms.received = Bool(dictionary["received"].boolValue)
sms.time = NSDate.dateFromSeconds(Double(dictionary["time"].stringValue)!)
sms.sms = String(dictionary["type"].stringValue) == "sms"
sms.pending = is_pending
let parts: [JSON] = dictionary["parts"].array!
if sms.messageparts == nil {
sms.messageparts = NSMutableOrderedSet()
}
for part in 0...parts.count-1{
let dict = parts[part]
switch(dict["type"].stringValue) {
case "text/plain":
let mmspart = NSEntityDescription.insertNewObjectForEntityForName("MessagePart", inManagedObjectContext: moc) as! MessagePart
mmspart.content_type = dict["type"].stringValue
mmspart.id = Int(dict["part_id"].stringValue)!
mmspart.message_id = Int(dict["mid"].stringValue)!
sms.msg = dict["msg"].stringValue
(sms.messageparts as! NSMutableOrderedSet).addObject(mmspart)
break
case "image/jpeg", "image/jpg", "image/png", "image/gif", "image/bmp":
let mmspart = NSEntityDescription.insertNewObjectForEntityForName("MessagePart", inManagedObjectContext: moc) as! MessagePart
mmspart.content_type = dict["type"].stringValue
mmspart.id = Int(dict["part_id"].stringValue)!
mmspart.message_id = Int(dict["mid"].stringValue)!
(sms.messageparts as! NSMutableOrderedSet).addObject(mmspart)
break
default:
break
}
}
return sms
}
func getLeftMessagePaneWithLatestMessages(moc: NSManagedObjectContext!) -> Array<AnyObject> {
var request = NSFetchRequest(entityName: "Message")
request.resultType = .DictionaryResultType
// max for id
let maxExpression = NSExpression(forFunction: "max:", arguments: [NSExpression(forKeyPath: "id")])
let expressionDescription = NSExpressionDescription()
expressionDescription.name = "id"
expressionDescription.expression = maxExpression
expressionDescription.expressionResultType = .Integer64AttributeType
request.propertiesToGroupBy = ["thread_id"]
request.propertiesToFetch = [expressionDescription, "thread_id"]
var objs = []
do {
try objs = moc.executeFetchRequest(request)
} catch let error as NSError {
NSLog("Unresolved error: %@, %@", error, error.userInfo)
}
let values = objs as! [Dictionary<String, AnyObject>]
request = NSFetchRequest(entityName: "Message")
request.sortDescriptors = [NSSortDescriptor(key: "time", ascending: false)]
request.resultType = NSFetchRequestResultType.DictionaryResultType
request.propertiesToFetch = ["msg", "number", "address", "id", "thread_id", "read"]
request.returnsDistinctResults = true
// Filter down based on ID's
var idArray = Array<Int>()
for dict in values {
let id = dict["id"] as! Int
idArray.append(id)
}
let predicate = NSPredicate(format: "id in %@", idArray)
request.predicate = predicate
var results: Array<AnyObject>? = nil
do {
try results = moc.executeFetchRequest(request)
} catch let error as NSError {
NSLog("Unresolved error: %@, %@", error, error.userInfo)
}
if (results != nil && results?.count > 0) {
let delegate = NSApplication.sharedApplication().delegate as! AppDelegate
let context = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
context.parentContext = delegate.coreDataHandler.managedObjectContext
for i in 0...results!.count-1 {
var result = results![i] as! Dictionary<String, AnyObject>
let number = result["number"] as! String
var phoneNumber: PhoneNumberData? = self.contactsHandler.getPhoneNumberIfContactExists(context, number: number)
// If we got a number, then send it
var fmt_number: String? = nil
if phoneNumber != nil {
fmt_number = phoneNumber!.contact.name!
}
if fmt_number == nil {
fmt_number = number
if phoneNumber != nil && phoneNumber?.formatted_number != nil {
fmt_number = phoneNumber?.formatted_number
} else {
let fmt = NBPhoneNumberUtil()
do {
var nb_number: NBPhoneNumber? = nil
try nb_number = fmt.parse(number, defaultRegion: "US")
try fmt_number = fmt.format(nb_number!, numberFormat: .INTERNATIONAL)
} catch let error as NSError {
NSLog("Unresolved error: %@, %@, %@", error, error.userInfo, number)
fmt_number = number
}
phoneNumber = self.contactsHandler.getPhoneNumberIfContactExists(context, number: fmt_number)
if phoneNumber != nil {
fmt_number = phoneNumber!.contact.name!
}
}
}
result.updateValue(fmt_number!, forKey: "row_title")
results![i] = result
}
return results!
}
return []
}
func checkIfMessageExists(moc: NSManagedObjectContext!, idValue: Int!) -> Bool {
return checkIfMessageExists(moc, idValue: idValue, type: "sms")
}
func checkIfMessageExists(moc: NSManagedObjectContext!, idValue: Int!, type: String!) -> Bool {
let request = NSFetchRequest(entityName: "Message")
request.predicate = NSPredicate(format: "id = %i AND sms == %@", idValue, type == "sms")
var objs: [Message]?
do {
try objs = moc.executeFetchRequest(request) as? [Message]
} catch let error as NSError {
NSLog("Unresolved error: %@, %@", error, error.userInfo)
}
return objs != nil && objs!.count > 0
}
func getMaxDate(moc: NSManagedObjectContext) -> String {
let request = NSFetchRequest(entityName: "Message")
request.resultType = .DictionaryResultType
// max for id
let maxExpression = NSExpression(forFunction: "max:", arguments: [NSExpression(forKeyPath: "time")])
let expressionDescription = NSExpressionDescription()
expressionDescription.name = "time"
expressionDescription.expression = maxExpression
expressionDescription.expressionResultType = .DateAttributeType
request.propertiesToFetch = [expressionDescription]
request.predicate = NSPredicate(format: "pending = %@", false)
var objs = [Dictionary<String, AnyObject>]()
do {
try objs = moc.executeFetchRequest(request) as! [Dictionary<String, AnyObject>]
if (objs.count > 0 && objs[0]["time"] != nil) {
var maxDateString = String((objs[0]["time"] as! NSDate).dateToMilliseonds())
if (maxDateString.rangeOfString(".") != nil) {
maxDateString = maxDateString.substringToIndex(maxDateString.rangeOfString(".")!.startIndex)
}
return maxDateString
}
} catch let error as NSError {
NSLog("Unresolved error: %@, %@", error, error.userInfo)
}
return ""
}
func setBadgeCount() {
let count = NSUserDefaults.standardUserDefaults().objectForKey(badgeCountSoFar) as? String
NSApplication.sharedApplication().dockTile.badgeLabel = count
}
}
| mit | 44863337226f6a5c6dbce7a44c4d8631 | 43.789655 | 163 | 0.577797 | 4.953852 | false | false | false | false |
apple/swift | test/decl/protocol/special/coding/struct_codable_simple.swift | 4 | 2256 | // RUN: %target-typecheck-verify-swift -verify-ignore-unknown
// Simple structs with all Codable properties should get derived conformance to
// Codable.
struct SimpleStruct : Codable {
var x: Int
var y: Double
static var z: String = "foo"
// These lines have to be within the SimpleStruct type because CodingKeys
// should be private.
func foo() {
// They should receive a synthesized CodingKeys enum.
let _ = SimpleStruct.CodingKeys.self
// The enum should have a case for each of the vars.
let _ = SimpleStruct.CodingKeys.x
let _ = SimpleStruct.CodingKeys.y
// Static vars should not be part of the CodingKeys enum.
let _ = SimpleStruct.CodingKeys.z // expected-error {{type 'SimpleStruct.CodingKeys' has no member 'z'}}
}
}
// They should receive synthesized init(from:) and an encode(to:).
let _ = SimpleStruct.init(from:)
let _ = SimpleStruct.encode(to:)
// The synthesized CodingKeys type should not be accessible from outside the
// struct.
let _ = SimpleStruct.CodingKeys.self // expected-error {{'CodingKeys' is inaccessible due to 'private' protection level}}
// rdar://problem/59655704
// https://github.com/apple/swift/issues/54675
struct S1_54675: Codable { // expected-error {{type 'S1_54675' does not conform to protocol 'Encodable'}} expected-error {{type 'S1_54675' does not conform to protocol 'Decodable'}}
var x: Int // expected-note {{'x' previously declared here}}
var x: Int // expected-error {{invalid redeclaration of 'x'}}
// expected-note@-1 {{cannot automatically synthesize 'Encodable' because 'Int' does not conform to 'Encodable'}}
// expected-note@-2 {{cannot automatically synthesize 'Encodable' because 'Int' does not conform to 'Encodable'}}
}
struct S2_54675: Decodable { // expected-error {{type 'S2_54675' does not conform to protocol 'Decodable'}}
var x: Int // expected-note {{'x' previously declared here}}
var x: Int // expected-error {{invalid redeclaration of 'x'}}
}
struct S3_54675: Encodable { // expected-error {{type 'S3_54675' does not conform to protocol 'Encodable'}}
var x: Int // expected-note {{'x' previously declared here}}
var x: Int // expected-error {{invalid redeclaration of 'x'}}
}
| apache-2.0 | fc182e1903916a555b76c3b91fc3a0fb | 43.235294 | 181 | 0.699025 | 4.057554 | false | false | false | false |
rotohun/multiples | multiples/ViewController.swift | 1 | 2154 | //
// ViewController.swift
// multiples
//
// Created by ronald hunter on 2/5/16.
// Copyright © 2016 ronald hunter. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
//Global variables
var multiple = 0
var counter = -1
var sum = 0
//Home Screen
//Variables
@IBOutlet weak var appTitle: UIImageView!
@IBOutlet weak var multipleInsert: UITextField!
@IBOutlet weak var playButton: UIButton!
//Add Screen
//Variables
@IBOutlet weak var mathLnl: UILabel!
@IBOutlet weak var addButton: UIButton!
@IBOutlet weak var resetButton: UIButton!
@IBAction func resetButton(sender: AnyObject) {
shouldBehidden(false)
counter = -1
}
@IBAction func playButton(sender: AnyObject) {
if multipleInsert.text != nil && multipleInsert.text != ""{
shouldBehidden(true)
}
}
@IBAction func addButton(sender: AnyObject) {
multiple = Int(multipleInsert.text!)!
counter++
var n1 = counter * multiple
sum = multiple + n1
mathLnl.text = "\(n1) + \(multiple) = \(sum)"
}
// Functions
func textFieldShouldReturn(textField: UITextField) -> Bool {
view.endEditing(true)
return false
}
func shouldBehidden(check:Bool){
if check == true{
playButton.hidden = true
multipleInsert.hidden = true
appTitle.hidden = true
mathLnl.hidden = false
addButton.hidden = false
resetButton.hidden = false
}else{
playButton.hidden = false
multipleInsert.hidden = false
appTitle.hidden = false
mathLnl.hidden = true
addButton.hidden = true
resetButton.hidden = true
}
}
}
| mit | 8c08aaa3881ea8255b246b07197791bb | 19.504762 | 71 | 0.50627 | 5.39599 | false | false | false | false |
ErusaevAP/DStack | Sources/DSExtensions/UIView+DStack.swift | 1 | 9135 | //
// UIView+DStack.swift
// MG
//
// Created by Andrei Erusaev on 6/21/17.
//
public
extension UIView {
@discardableResult
func setHeight(fromView: UIView? = nil) -> Self {
let fromView = fromView ?? superview
guard let view = fromView else { return self }
heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 1).isActive = true
return self
}
@discardableResult
func setWidth(fromView: UIView? = nil) -> Self {
let fromView = fromView ?? superview
guard let view = fromView else { return self }
widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 1).isActive = true
return self
}
@discardableResult
func setSize(fromView: UIView? = nil) -> Self {
let fromView = fromView ?? superview
return self
.setHeight(fromView: fromView)
.setWidth(fromView: fromView)
}
@discardableResult
func setSize(size: CGSize) -> Self {
setSize(width: size.width, height: size.height)
}
@discardableResult
func setSize(width: CGFloat? = nil, height: CGFloat? = nil) -> Self {
if let width = width {
widthAnchor.constraint(equalToConstant: width).isActive = true
}
if let height = height {
heightAnchor.constraint(equalToConstant: height).isActive = true
}
return self
}
}
public
extension UIView {
@discardableResult
func setLeftAnchor(equalTo anchor: NSLayoutXAxisAnchor, marge: CGFloat = 0) -> Self {
leftAnchor.constraint(equalTo: anchor, constant: marge).isActive = true
return self
}
@discardableResult
func setRightAnchor(equalTo anchor: NSLayoutXAxisAnchor, marge: CGFloat = 0) -> Self {
rightAnchor.constraint(equalTo: anchor, constant: -marge).isActive = true
return self
}
@discardableResult
func setTopAnchor(equalTo anchor: NSLayoutYAxisAnchor, marge: CGFloat = 0) -> Self {
topAnchor.constraint(equalTo: anchor, constant: marge).isActive = true
return self
}
@discardableResult
func setBottomAnchor(equalTo anchor: NSLayoutYAxisAnchor, marge: CGFloat = 0) -> Self {
bottomAnchor.constraint(equalTo: anchor, constant: -marge).isActive = true
return self
}
@discardableResult
func setHeightAnchor(equalTo anchor: NSLayoutDimension, marge: CGFloat = 0) -> Self {
heightAnchor.constraint(equalTo: anchor, multiplier: 1).isActive = true
return self
}
@discardableResult
func setWidthAnchor(equalTo anchor: NSLayoutDimension, marge: CGFloat = 0) -> Self {
widthAnchor.constraint(equalTo: anchor, multiplier: 1).isActive = true
return self
}
@discardableResult
func setLeadingAnchor(
equalTo anchor: NSLayoutXAxisAnchor,
marge: CGFloat = 0,
priority: UILayoutPriority = .defaultHigh
) -> Self {
let constraint = leadingAnchor.constraint(equalTo: anchor)
constraint.isActive = true
constraint.priority = priority
return self
}
@discardableResult
func setTrailingAnchor(
equalTo anchor: NSLayoutXAxisAnchor,
marge: CGFloat = 0,
priority: UILayoutPriority = .defaultHigh
) -> Self {
let constraint = trailingAnchor.constraint(equalTo: anchor)
constraint.isActive = true
constraint.priority = priority
return self
}
}
public
extension UIView {
@discardableResult
func setLeftAnchor(greaterThanOrEqualTo anchor: NSLayoutXAxisAnchor, marge: CGFloat = 0) -> Self {
leftAnchor.constraint(greaterThanOrEqualTo: anchor, constant: marge).isActive = true
return self
}
@discardableResult
func setRightAnchor(greaterThanOrEqualTo anchor: NSLayoutXAxisAnchor, marge: CGFloat = 0) -> Self {
rightAnchor.constraint(greaterThanOrEqualTo: anchor, constant: -marge).isActive = true
return self
}
@discardableResult
func setTopAnchor(greaterThanOrEqualTo anchor: NSLayoutYAxisAnchor, marge: CGFloat = 0) -> Self {
topAnchor.constraint(greaterThanOrEqualTo: anchor, constant: marge).isActive = true
return self
}
@discardableResult
func setBottomAnchor(greaterThanOrEqualTo anchor: NSLayoutYAxisAnchor, marge: CGFloat = 0) -> Self {
bottomAnchor.constraint(greaterThanOrEqualTo: anchor, constant: -marge).isActive = true
return self
}
@discardableResult
func setHeightAnchor(greaterThanOrEqualTo anchor: NSLayoutDimension, marge: CGFloat = 0) -> Self {
heightAnchor.constraint(greaterThanOrEqualTo: anchor, multiplier: 1).isActive = true
return self
}
@discardableResult
func setWidthAnchor(greaterThanOrEqualTo anchor: NSLayoutDimension, marge: CGFloat = 0) -> Self {
widthAnchor.constraint(greaterThanOrEqualTo: anchor, multiplier: 1).isActive = true
return self
}
@discardableResult
func setLeadingAnchor(
greaterThanOrEqualTo anchor: NSLayoutXAxisAnchor,
marge: CGFloat = 0,
priority: UILayoutPriority = .defaultHigh
) -> Self {
let constraint = leadingAnchor.constraint(greaterThanOrEqualTo: anchor)
constraint.isActive = true
constraint.priority = priority
return self
}
@discardableResult
func setTrailingAnchor(
greaterThanOrEqualTo anchor: NSLayoutXAxisAnchor,
marge: CGFloat = 0,
priority: UILayoutPriority = .defaultHigh
) -> Self {
let constraint = trailingAnchor.constraint(greaterThanOrEqualTo: anchor)
constraint.isActive = true
constraint.priority = priority
return self
}
}
public
extension UIView {
@discardableResult
func fill(viewController: UIViewController, marge: CGFloat = 0) -> Self {
setTopAnchor(equalTo: viewController.view.safeAreaLayoutGuide.topAnchor, marge: marge)
.setRightAnchor(equalTo: viewController.view.rightAnchor, marge: marge)
.setBottomAnchor(equalTo: viewController.view.safeAreaLayoutGuide.bottomAnchor, marge: marge)
.setLeftAnchor(equalTo: viewController.view.leftAnchor, marge: marge)
}
@discardableResult
func fill(fromView: UIView? = nil, marge: CGFloat = 0) -> Self {
let fromView = fromView ?? superview
return self
.setTopAlignment(fromView: fromView, marge: marge)
.setBottomAlignment(fromView: fromView, marge: marge)
.setLeftAlignment(fromView: fromView, marge: marge)
.setRightAlignment(fromView: fromView, marge: marge)
}
@discardableResult
func fill(fromView: UIView? = nil, inset: UIEdgeInsets) -> Self {
let fromView = fromView ?? superview
return self
.setTopAlignment(fromView: fromView, marge: inset.top)
.setBottomAlignment(fromView: fromView, marge: inset.bottom)
.setLeftAlignment(fromView: fromView, marge: inset.left)
.setRightAlignment(fromView: fromView, marge: inset.right)
}
}
public
extension UIView {
@discardableResult
func setTopAlignment(fromView: UIView? = nil, marge: CGFloat = 0) -> Self {
let fromView = fromView ?? superview
guard let view = fromView else { return self }
return setTopAnchor(equalTo: view.topAnchor, marge: marge)
}
@discardableResult
func setBottomAlignment(fromView: UIView? = nil, marge: CGFloat = 0) -> Self {
let fromView = fromView ?? superview
guard let view = fromView else { return self }
return setBottomAnchor(equalTo: view.bottomAnchor, marge: marge)
}
@discardableResult
func setLeftAlignment(fromView: UIView? = nil, marge: CGFloat = 0) -> Self {
let fromView = fromView ?? superview
guard let view = fromView else { return self }
return setLeftAnchor(equalTo: view.leftAnchor, marge: marge)
}
@discardableResult
func setRightAlignment(fromView: UIView? = nil, marge: CGFloat = 0) -> Self {
let fromView = fromView ?? superview
guard let view = fromView else { return self }
return setRightAnchor(equalTo: view.rightAnchor, marge: marge)
}
}
public
extension UIView {
@discardableResult
func setCenterX(fromView: UIView? = nil) -> Self {
let fromView = fromView ?? superview
guard let view = fromView else { return self }
centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
return self
}
@discardableResult
func setCenterY(fromView: UIView? = nil) -> Self {
let fromView = fromView ?? superview
guard let view = fromView else { return self }
centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
return self
}
@discardableResult
func setCenter(fromView: UIView? = nil) -> Self {
let fromView = fromView ?? superview
return self
.setCenterX(fromView: fromView)
.setCenterY(fromView: fromView)
}
}
| mit | d88e40dbee03c55f9c7d1c70137d2d6f | 31.165493 | 105 | 0.664258 | 5.05814 | false | false | false | false |
powerytg/Accented | Accented/Core/API/Requests/SearchUsersRequest.swift | 1 | 1768 | //
// SearchUsersRequest.swift
// Accented
//
// Created by Tiangong You on 5/22/17.
// Copyright © 2017 Tiangong You. All rights reserved.
//
import UIKit
class SearchUsersRequest: APIRequest {
private var keyword : String
private var page : Int
init(keyword : String, page : Int = 1, success : SuccessAction?, failure : FailureAction?) {
self.keyword = keyword
self.page = page
super.init(success: success, failure: failure)
cacheKey = "search_users/\(keyword)/\(page)"
url = "\(APIRequest.baseUrl)users/search"
parameters = [String : String]()
parameters[RequestParameters.term] = keyword
parameters[RequestParameters.page] = String(page)
}
override func handleSuccess(data: Data, response: HTTPURLResponse?) {
super.handleSuccess(data: data, response: response)
let userInfo : [String : Any] = [RequestParameters.page : page,
RequestParameters.response : data,
RequestParameters.term : keyword]
NotificationCenter.default.post(name: APIEvents.userSearchResultDidReturn, object: nil, userInfo: userInfo)
if let success = successAction {
success()
}
}
override func handleFailure(_ error: Error) {
super.handleFailure(error)
let userInfo : [String : String] = [RequestParameters.errorMessage : error.localizedDescription]
NotificationCenter.default.post(name: APIEvents.userSearchResultFailedReturn, object: nil, userInfo: userInfo)
if let failure = failureAction {
failure(error.localizedDescription)
}
}
}
| mit | 70f5433cfe309f04d47385b44055d8fd | 33.647059 | 118 | 0.615733 | 4.963483 | false | false | false | false |
vector-im/vector-ios | Riot/Modules/MatrixKit/Categories/NSString+MatrixKit.swift | 2 | 2738 | //
// Copyright 2020 The Matrix.org Foundation C.I.C
//
// 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
import MatrixSDK.MXLog
public extension NSString {
/// Gets the first URL contained in the string ignoring any links to hosts defined in
/// the `firstURLDetectionIgnoredHosts` property of `MXKAppSettings`.
/// - Returns: A URL if detected, otherwise nil.
@objc func mxk_firstURLDetected() -> NSURL? {
let hosts = MXKAppSettings.standard().firstURLDetectionIgnoredHosts ?? []
return mxk_firstURLDetected(ignoring: hosts)
}
/// Gets the first URL contained in the string ignoring any links to the specified hosts.
/// - Returns: A URL if detected, otherwise nil.
@objc func mxk_firstURLDetected(ignoring ignoredHosts: [String]) -> NSURL? {
guard let linkDetector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) else {
MXLog.debug("[NSString+URLDetector]: Unable to create link detector.")
return nil
}
var detectedURL: NSURL?
// enumerate all urls that were found in the string to ensure
// detection of a valid link if there are invalid links preceding it
linkDetector.enumerateMatches(in: self as String,
options: [],
range: NSRange(location: 0, length: self.length)) { match, flags, stop in
guard let match = match else { return }
// check if the match is a valid url
let urlString = self.substring(with: match.range)
guard let url = NSURL(string: urlString) else { return }
// ensure the match is a web link
guard let scheme = url.scheme?.lowercased(),
scheme == "https" || scheme == "http"
else { return }
// discard any links to ignored hosts
guard let host = url.host?.lowercased(),
!ignoredHosts.contains(host)
else { return }
detectedURL = url
stop.pointee = true
}
return detectedURL
}
}
| apache-2.0 | c7eb6e7d1f380b05bbf6a3342e3c8bf3 | 40.484848 | 115 | 0.61943 | 4.828924 | false | false | false | false |
GuitarPlayer-Ma/Swiftweibo | weibo/weibo/Classes/OAuth/Controller/OAuthViewController.swift | 1 | 3679 | //
// OAuthViewController.swift
// weibo
//
// Created by mada on 15/9/30.
// Copyright © 2015年 MD. All rights reserved.
//
import UIKit
import SVProgressHUD
class OAuthViewController: UIViewController {
let WB_APP_Key: String = "4155480345"
let WB_App_Secret:String = "d24f97bdb3bbb62a40c46e9cc6ba5ea1"
let WB_Redirect_URI = "https://www.baidu.com/"
override func loadView() {
webView.delegate = self
view = webView
}
override func viewDidLoad() {
super.viewDidLoad()
// 初始导航条
navigationItem.title = "新浪微博"
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Done, target: self, action: Selector("close"))
// 加载登录界面
let str = "https://api.weibo.com/oauth2/authorize?client_id=" + WB_APP_Key + "&redirect_uri=" + WB_Redirect_URI
let url = NSURL(string: str)!
let request = NSURLRequest(URL: url)
webView.loadRequest(request)
}
func close() {
dismissViewControllerAnimated(true, completion: nil)
}
private lazy var webView = UIWebView()
}
extension OAuthViewController : UIWebViewDelegate {
// 开始加载时调用
func webViewDidStartLoad(webView: UIWebView) {
SVProgressHUD.showWithStatus("加载中..", maskType: SVProgressHUDMaskType.Black)
}
func webViewDidFinishLoad(webView: UIWebView) {
SVProgressHUD.dismiss()
}
// 每次webView发送请求就会调用,如果返回true代表可以访问, 返回false代表不能访问
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
// 判断是否跳转到微博对应的页面
let urlStr = request.URL!.absoluteString
if !urlStr.hasPrefix(WB_Redirect_URI) {
return true
}
// 是否是授权界面
let codeStr = "code="
if !urlStr.containsString("error") {
JSJLog("已经授权")
JSJLog(request.URL!)
let code = request.URL?.query?.substringFromIndex(codeStr.endIndex)
JSJLog(code)
loadAccessToken(code!)
close()
}else {
JSJLog("取消授权")
close()
}
return false
}
func loadAccessToken(code: String) {
let path = "oauth2/access_token"
let parameters = ["client_id" : WB_APP_Key, "client_secret" : WB_App_Secret, "grant_type" : "authorization_code", "code" : code, "redirect_uri" : WB_Redirect_URI]
NetworkingTools.shareNetworkTools().POST(path, parameters: parameters, success: { (_, dict) -> Void in
JSJLog(dict)
// 将字典转换为模型
let account = UserAccount(dict: dict as! [String : AnyObject])
// 加载用户信息
account.loadUserInfo { (account, error) -> () in
if account != nil {
// 保存用户信息
JSJLog(account)
account?.saveAccount()
// 发送通知
NSNotificationCenter.defaultCenter().postNotificationName(JSJSwitchRootViewController, object: "oauth")
return
}
SVProgressHUD.showErrorWithStatus("获取授权信息失败")
}
}) { (_, error) -> Void in
JSJLog(error)
SVProgressHUD.showErrorWithStatus("获取授权信息失败", maskType: SVProgressHUDMaskType.Black)
}
}
}
| mit | a4244d2dcdf7789b4f3fbb131f111f42 | 31.647619 | 170 | 0.587515 | 4.510526 | false | false | false | false |
wookiee/ssoutliner | outline-image/CGImage+Outlining.swift | 1 | 3383 | import Cocoa
import CoreGraphics
extension CGImage {
func addingOutline(mask: CornerMask, radius: Int, width lineWidth: Int) -> CGImage {
let newSize = (width: self.width + lineWidth * 2,
height: self.height + lineWidth * 2)
let newCGSize = CGSize(width: newSize.width, height: newSize.height)
let ctx: CGContext = CGContext(data: nil,
width: newSize.width,
height: newSize.height,
bitsPerComponent: 8,
bytesPerRow: 0,
space: CGColorSpaceCreateDeviceRGB(),
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!
// Draw the screenshot itself
let rect = CGRect(x: lineWidth, y: lineWidth, width: self.width, height: self.height)
ctx.draw(self, in: rect)
// Each corner radius is 0 (if not in the mask) or the specified radius, less the line width
let bottomLeftRadius = CGFloat((mask.contains(.bottomLeft) ? radius : 0) - lineWidth)
let bottomRightRadius = CGFloat((mask.contains(.bottomRight) ? radius : 0) - lineWidth)
let topRightRadius = CGFloat((mask.contains(.topRight) ? radius : 0) - lineWidth)
let topLeftRadius = CGFloat((mask.contains(.topLeft) ? radius : 0) - lineWidth)
// Define the pseudorounded rect
let path = CGMutablePath()
let inset = CGFloat(lineWidth) / 2.0
path.addArc(center: CGPoint(x: bottomLeftRadius + inset,
y: bottomLeftRadius + inset),
radius: bottomLeftRadius,
startAngle: .pi,
endAngle: .pi * 1.5,
clockwise: false)
path.addArc(center: CGPoint(x: newCGSize.width - bottomRightRadius - inset,
y: bottomRightRadius + inset),
radius: bottomRightRadius,
startAngle: .pi * 1.5,
endAngle: .pi * 2.0,
clockwise: false)
path.addArc(center: CGPoint(x: newCGSize.width - topRightRadius - inset,
y: newCGSize.height - topRightRadius - inset),
radius: topRightRadius,
startAngle: 0,
endAngle: .pi / 2.0,
clockwise: false)
path.addArc(center: CGPoint(x: topLeftRadius + inset,
y: newCGSize.height - topLeftRadius - inset),
radius: topLeftRadius,
startAngle: .pi / 2.0,
endAngle: .pi,
clockwise: false)
path.closeSubpath()
ctx.setLineWidth(CGFloat(lineWidth))
ctx.setStrokeColor(CGColor.black)
ctx.addPath(path)
ctx.strokePath()
let newImage = ctx.makeImage()!
return newImage
}
@discardableResult func write(to destinationURL: URL) -> Bool {
guard let destination = CGImageDestinationCreateWithURL(destinationURL as CFURL, kUTTypePNG, 1, nil) else { return false }
CGImageDestinationAddImage(destination, self, nil)
return CGImageDestinationFinalize(destination)
}
}
| mit | 4f5fd117ad60ad37e8417ddc824cfb8c | 42.371795 | 130 | 0.539462 | 5.302508 | false | false | false | false |
TrustWallet/trust-wallet-ios | Trust/Transfer/ViewModels/MonetaryAmountViewModel.swift | 1 | 997 | // Copyright DApps Platform Inc. All rights reserved.
import Foundation
import BigInt
import TrustCore
struct MonetaryAmountViewModel {
let amount: String
let contract: Address
let session: WalletSession
let formatter: EtherNumberFormatter
init(
amount: String,
contract: Address,
session: WalletSession,
formatter: EtherNumberFormatter = .full
) {
self.amount = amount
self.contract = contract
self.session = session
self.formatter = formatter
}
var amountCurrency: Double? {
guard let price = session.tokensStorage.coinTicker(by: contract)?.price else {
return .none
}
return FeeCalculator.estimate(fee: amount, with: price)
}
var amountText: String? {
guard let amountCurrency = amountCurrency,
let result = FeeCalculator.format(fee: amountCurrency) else {
return .none
}
return "(\(result))"
}
}
| gpl-3.0 | b8ee756f255e259f4400577fc05d9f98 | 24.564103 | 86 | 0.62989 | 4.770335 | false | false | false | false |
fabiomassimo/eidolon | KioskTests/TextFieldTests.swift | 2 | 3242 | import Quick
import Nimble
import Kiosk
import Nimble_Snapshots
class TextFieldTests: QuickSpec {
override func spec() {
pending("TextField") {
var textField: TextField?
beforeEach {
let window = UIWindow(frame:UIScreen.mainScreen().bounds)
let vc = UIViewController()
textField = TextField(frame: CGRectMake(0, 0, 255, 44))
textField!.shouldAnimateStateChange = false
vc.view.addSubview(textField!)
window.rootViewController = vc
window.makeKeyAndVisible()
textField!.becomeFirstResponder()
textField!.text = "Text text"
}
it("looks correct when not in focus") {
textField!.resignFirstResponder()
expect(textField!).to(haveValidSnapshot(named:"not in focus"))
}
it("looks correct when in focus") {
expect(textField!).to(haveValidSnapshot(named:"in focus"))
}
}
pending("SecureTextField") {
var textField: SecureTextField?
beforeEach {
let window = UIWindow(frame:UIScreen.mainScreen().bounds)
let vc = UIViewController()
textField = SecureTextField(frame: CGRectMake(0, 0, 255, 44))
textField!.shouldAnimateStateChange = false
textField!.text = ""
textField!.font = UIFont.serifFontWithSize(textField!.font.pointSize)
vc.view.addSubview(textField!)
window.rootViewController = vc
window.makeKeyAndVisible()
textField!.becomeFirstResponder()
textField!.insertText("Secure")
}
describe("in focus") {
it("looks correct") {
expect(textField!).to(haveValidSnapshot(named:"in focus"))
}
it("stores text") {
expect(textField!.text).to(equal("Secure"))
expect(textField!.actualText).to(equal("Secure"))
}
}
describe("not in focus") {
beforeEach {
textField!.resignFirstResponder()
return
}
it("looks correct") {
expect(textField!).to(haveValidSnapshot(named:"not in focus"))
}
it("stores text") {
expect(textField!.text).to(equal("Secure"))
expect(textField!.actualText).to(equal("Secure"))
}
}
describe("editing a second time") {
beforeEach {
textField!.resignFirstResponder()
textField!.becomeFirstResponder()
}
it("looks correct") {
expect(textField!).to(haveValidSnapshot(named:"second edit"))
}
it("clears stored text") {
expect(textField!.text).to(equal(""))
expect(textField!.actualText).to(equal(""))
}
}
}
}
}
| mit | 4a2a397999fea7271cac69374a74e158 | 33.489362 | 85 | 0.493214 | 6.003704 | false | false | false | false |
RafaelGarciaIII/CoffeeGroup32 | UserViewController.swift | 1 | 3796 | //
// UserViewController.swift
// ParseTutorial
//
// Created by Rafael Garcia on 11/14/15.
// Copyright © 2015 bizzi-body. All rights reserved.
//
import UIKit
class UserViewController: UIViewController {
var manager:OneShotLocationManager?
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var latLabel: UILabel!
@IBOutlet weak var lonLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var tempLabel: UILabel!
@IBOutlet weak var cityLabel: UILabel!
@IBAction func refresh(sender: AnyObject) {
self.viewDidLoad();
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let formatter = NSNumberFormatter();
formatter.minimumFractionDigits = 1;
formatter.maximumFractionDigits = 5;
// ** LOAD USER PROFILE
// Load the users profile so that we can display their brew devices
let userEmail = PFUser.currentUser()!["username"] as? String
let query = PFQuery(className:"UserProfile")
query.whereKey("username", equalTo:(userEmail)!)
//query.findObjectsInBackgroundWithBlock {
query.getFirstObjectInBackgroundWithBlock {
(object, error) -> Void in
if error == nil {
// The find succeeded.
print("Successfully retrieved UserProfile object!")
// Do something with the found objects
if let object = object {
//UPDATE THIS TO PULL LOCATION FROM PARSE INSTEAD OF USING LOCATION MANAGER
// ** END LOAD USER PROFILE
var locationHolder = object["homeLocation"] as! Dictionary<String, Double>
self.latLabel.text = formatter.stringFromNumber(locationHolder["lat"]!)
self.lonLabel.text = formatter.stringFromNumber(locationHolder["lon"]!)
self.setTemp();
//time ?
let date = NSDate()
let formatter = NSDateFormatter()
formatter.timeStyle = .ShortStyle
self.timeLabel.text=formatter.stringFromDate(date)
self.usernameLabel.text = userEmail;
}}}
}
func setTemp()
{
let formatter = NSNumberFormatter();
formatter.minimumFractionDigits = 1;
formatter.maximumFractionDigits = 5;
getTemp({ (result) -> Void in
self.tempLabel.text = formatter.stringFromNumber(result);})
getCity({ (result) -> Void in
self.cityLabel.text = result;
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Sign the user out
@IBAction func signOut(sender: AnyObject) {
PFUser.logOut()
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("SignUpInViewController")
self.presentViewController(vc, animated: true, completion: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 13024603549fa1fb0faa1f92de36cb5e | 31.435897 | 106 | 0.580764 | 5.664179 | false | false | false | false |
IngmarStein/swift | benchmark/single-source/BitCount.swift | 4 | 1203 | //===--- BitCount.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 Swift bit count.
// and mask operator.
// rdar://problem/22151678
import Foundation
import TestsUtils
func countBitSet(_ num: Int) -> Int {
let bits = MemoryLayout<Int>.size * 8
var cnt: Int = 0
var mask: Int = 1
for _ in 0...bits {
if num & mask != 0 {
cnt += 1
}
mask <<= 1
}
return cnt
}
@inline(never)
public func run_BitCount(_ N: Int) {
for _ in 1...100*N {
// Check some results.
CheckResults(countBitSet(1) == 1, "Incorrect results in BitCount.")
CheckResults(countBitSet(2) == 1, "Incorrect results in BitCount.")
CheckResults(countBitSet(2457) == 6, "Incorrect results in BitCount.")
}
}
| apache-2.0 | e76d5de376a21bf2b955a54f555bef2a | 29.075 | 80 | 0.591022 | 4.206294 | false | false | false | false |
xcodeswift/xcproj | Tests/XcodeProjTests/Objects/Project/PBXProjEncoderTests.swift | 1 | 26661 |
import Foundation
import XCTest
@testable import XcodeProj
class PBXProjEncoderTests: XCTestCase {
var proj: PBXProj!
override func setUp() {
super.setUp()
let dic = iosProjectDictionary()
do {
proj = try PBXProj(jsonDictionary: dic.1)
} catch {
XCTFail("Failed to load project from file \(error)")
}
}
// MARK: - Header
func test_writeHeaders() throws {
let lines = self.lines(fromFile: encodeProject())
XCTAssertEqual(583, lines.count)
XCTAssertEqual("// !$*UTF8*$!", lines[0])
}
// MARK: - Internal file lists
func test_buildFiles_in_default_uuid_order() {
let lines = self.lines(fromFile: encodeProject())
var line = lines.validate(line: "/* Begin PBXBuildFile section */")
line = lines.validate(lineContaining: "04D5C09F1F153824008A2F98 /* CoreData.framework in Frameworks */", onLineAfter: line)
line = lines.validate(lineContaining: "04D5C0A31F153924008A2F98 /* Public.h in Headers */", onLineAfter: line)
line = lines.validate(lineContaining: "04D5C0A41F153924008A2F98 /* Protected.h in Headers */", onLineAfter: line)
line = lines.validate(lineContaining: "04D5C0A51F153924008A2F98 /* Private.h in Headers */", onLineAfter: line)
line = lines.validate(lineContaining: "23766C161EAA3484007A9026 /* AppDelegate.swift in Sources */", onLineAfter: line)
line = lines.validate(lineContaining: "23766C181EAA3484007A9026 /* ViewController.swift in Sources */", onLineAfter: line)
line = lines.validate(lineContaining: "23766C1B1EAA3484007A9026 /* Main.storyboard in Resources */", onLineAfter: line)
line = lines.validate(lineContaining: "23766C1D1EAA3484007A9026 /* Assets.xcassets in Resources */", onLineAfter: line)
line = lines.validate(lineContaining: "23766C201EAA3484007A9026 /* LaunchScreen.storyboard in Resources */", onLineAfter: line)
line = lines.validate(lineContaining: "23766C2B1EAA3484007A9026 /* iOSTests.swift in Sources */", onLineAfter: line)
line = lines.validate(lineContaining: "3CD1EADD205763E400DAEECB /* Model.xcdatamodeld in Sources */", onLineAfter: line)
line = lines.validate(lineContaining: "42AA1A1A22AAF48100428760 /* MyLocalPackage in Frameworks */", onLineAfter: line)
line = lines.validate(lineContaining: "42AA1A1C22AAF48100428760 /* RxSwift in Frameworks */", onLineAfter: line)
lines.validate(line: "/* End PBXBuildFile section */", onLineAfter: line)
}
func test_buildFiles_in_filename_order() {
let settings = PBXOutputSettings(projFileListOrder: .byFilename)
let lines = self.lines(fromFile: encodeProject(settings: settings))
var line = lines.validate(line: "/* Begin PBXBuildFile section */")
line = lines.validate(lineContaining: "23766C161EAA3484007A9026 /* AppDelegate.swift in Sources */", onLineAfter: line)
line = lines.validate(lineContaining: "23766C1D1EAA3484007A9026 /* Assets.xcassets in Resources */", onLineAfter: line)
line = lines.validate(lineContaining: "04D5C09F1F153824008A2F98 /* CoreData.framework in Frameworks */", onLineAfter: line)
line = lines.validate(lineContaining: "23766C201EAA3484007A9026 /* LaunchScreen.storyboard in Resources */", onLineAfter: line)
line = lines.validate(lineContaining: "23766C1B1EAA3484007A9026 /* Main.storyboard in Resources */", onLineAfter: line)
line = lines.validate(lineContaining: "3CD1EADD205763E400DAEECB /* Model.xcdatamodeld in Sources */", onLineAfter: line)
line = lines.validate(lineContaining: "04D5C0A51F153924008A2F98 /* Private.h in Headers */", onLineAfter: line)
line = lines.validate(lineContaining: "04D5C0A41F153924008A2F98 /* Protected.h in Headers */", onLineAfter: line)
line = lines.validate(lineContaining: "04D5C0A31F153924008A2F98 /* Public.h in Headers */", onLineAfter: line)
line = lines.validate(lineContaining: "23766C181EAA3484007A9026 /* ViewController.swift in Sources */", onLineAfter: line)
line = lines.validate(lineContaining: "23766C2B1EAA3484007A9026 /* iOSTests.swift in Sources */", onLineAfter: line)
line = lines.validate(lineContaining: "42AA1A1A22AAF48100428760 /* MyLocalPackage in Frameworks */", onLineAfter: line)
line = lines.validate(lineContaining: "42AA1A1C22AAF48100428760 /* RxSwift in Frameworks */", onLineAfter: line)
lines.validate(line: "/* End PBXBuildFile section */", onLineAfter: line)
}
func test_file_references_in_default_uuid_order() {
let lines = self.lines(fromFile: encodeProject())
var line = lines.validate(line: "/* Begin PBXFileReference section */")
line = lines.validate(lineContaining: "04D5C09E1F153824008A2F98 /* CoreData.framework */", onLineAfter: line)
line = lines.validate(lineContaining: "04D5C0A01F153915008A2F98 /* Public.h */", onLineAfter: line)
line = lines.validate(lineContaining: "04D5C0A11F15391B008A2F98 /* Protected.h */", onLineAfter: line)
line = lines.validate(lineContaining: "04D5C0A21F153921008A2F98 /* Private.h */", onLineAfter: line)
line = lines.validate(lineContaining: "23766C121EAA3484007A9026 /* iOS.app */", onLineAfter: line)
line = lines.validate(lineContaining: "23766C151EAA3484007A9026 /* AppDelegate.swift */", onLineAfter: line)
line = lines.validate(lineContaining: "23766C171EAA3484007A9026 /* ViewController.swift */", onLineAfter: line)
line = lines.validate(lineContaining: "23766C1A1EAA3484007A9026 /* Base */", onLineAfter: line)
line = lines.validate(lineContaining: "23766C1C1EAA3484007A9026 /* Assets.xcassets */", onLineAfter: line)
line = lines.validate(lineContaining: "23766C1F1EAA3484007A9026 /* Base */", onLineAfter: line)
line = lines.validate(lineContaining: "23766C211EAA3484007A9026 /* Info.plist */", onLineAfter: line)
line = lines.validate(lineContaining: "23766C261EAA3484007A9026 /* iOSTests.xctest */", onLineAfter: line)
line = lines.validate(lineContaining: "23766C2A1EAA3484007A9026 /* iOSTests.swift */", onLineAfter: line)
line = lines.validate(lineContaining: "23766C2C1EAA3484007A9026 /* Info.plist */", onLineAfter: line)
line = lines.validate(lineContaining: "23C1E0AF23657FB500B8D1EF /* iOS.xctestplan */", onLineAfter: line)
line = lines.validate(lineContaining: "3CD1EADC205763E400DAEECB /* Model.xcdatamodel */", onLineAfter: line)
line = lines.validate(lineContaining: "42AA1A1822AAF41000428760 /* MyLocalPackage */", onLineAfter: line)
lines.validate(line: "/* End PBXFileReference section */", onLineAfter: line)
}
func test_file_references_in_filename_order() {
let settings = PBXOutputSettings(projFileListOrder: .byFilename)
let lines = self.lines(fromFile: encodeProject(settings: settings))
var line = lines.validate(line: "/* Begin PBXFileReference section */")
line = lines.validate(lineContaining: "23766C151EAA3484007A9026 /* AppDelegate.swift */", onLineAfter: line)
line = lines.validate(lineContaining: "23766C1C1EAA3484007A9026 /* Assets.xcassets */", onLineAfter: line)
line = lines.validate(lineContaining: "23766C1A1EAA3484007A9026 /* Base */", onLineAfter: line)
line = lines.validate(lineContaining: "23766C1F1EAA3484007A9026 /* Base */", onLineAfter: line)
line = lines.validate(lineContaining: "04D5C09E1F153824008A2F98 /* CoreData.framework */", onLineAfter: line)
line = lines.validate(lineContaining: "23766C211EAA3484007A9026 /* Info.plist */", onLineAfter: line)
line = lines.validate(lineContaining: "23766C2C1EAA3484007A9026 /* Info.plist */", onLineAfter: line)
line = lines.validate(lineContaining: "3CD1EADC205763E400DAEECB /* Model.xcdatamodel */", onLineAfter: line)
line = lines.validate(lineContaining: "42AA1A1822AAF41000428760 /* MyLocalPackage */", onLineAfter: line)
line = lines.validate(lineContaining: "04D5C0A21F153921008A2F98 /* Private.h */", onLineAfter: line)
line = lines.validate(lineContaining: "04D5C0A11F15391B008A2F98 /* Protected.h */", onLineAfter: line)
line = lines.validate(lineContaining: "04D5C0A01F153915008A2F98 /* Public.h */", onLineAfter: line)
line = lines.validate(lineContaining: "23766C171EAA3484007A9026 /* ViewController.swift */", onLineAfter: line)
line = lines.validate(lineContaining: "23766C121EAA3484007A9026 /* iOS.app */", onLineAfter: line)
line = lines.validate(lineContaining: "23C1E0AF23657FB500B8D1EF /* iOS.xctestplan */", onLineAfter: line)
line = lines.validate(lineContaining: "23766C2A1EAA3484007A9026 /* iOSTests.swift */", onLineAfter: line)
line = lines.validate(lineContaining: "23766C261EAA3484007A9026 /* iOSTests.xctest */", onLineAfter: line)
lines.validate(line: "/* End PBXFileReference section */", onLineAfter: line)
}
// MARK: - Navigator
func test_navigator_groups_in_default_order() {
let lines = self.lines(fromFile: encodeProject())
let beginGroup = lines.findLine("/* Begin PBXGroup section */")
// Root
let rootGroup = lines.findLine("23766C091EAA3484007A9026 = {", after: beginGroup)
let rootChildrenStart = lines.findLine("children = (", after: rootGroup)
let rootChildrenEnd = lines.findLine(");", after: rootChildrenStart)
lines.validate(line: "23766C141EAA3484007A9026 /* iOS */,", betweenLine: rootChildrenStart, andLine: rootChildrenEnd)
lines.validate(line: "23766C291EAA3484007A9026 /* iOSTests */,", betweenLine: rootChildrenStart, andLine: rootChildrenEnd)
lines.validate(line: "23766C131EAA3484007A9026 /* Products */,", betweenLine: rootChildrenStart, andLine: rootChildrenEnd)
lines.validate(line: "04D5C09D1F153824008A2F98 /* Frameworks */,", betweenLine: rootChildrenStart, andLine: rootChildrenEnd)
// iOS
let iosGroup = lines.findLine("23766C141EAA3484007A9026 /* iOS */ = {", after: beginGroup)
let iosChildrenStart = lines.findLine("children = (", after: iosGroup)
let iosChildrenEnd = lines.findLine(");", after: iosChildrenStart)
lines.validate(line: "3CD1EADB205763E400DAEECB /* Model.xcdatamodeld */,", betweenLine: iosChildrenStart, andLine: iosChildrenEnd)
lines.validate(line: "3CD1EAD92057638200DAEECB /* GroupWithoutFolder */,", betweenLine: iosChildrenStart, andLine: iosChildrenEnd)
lines.validate(line: "23766C151EAA3484007A9026 /* AppDelegate.swift */,", betweenLine: iosChildrenStart, andLine: iosChildrenEnd)
lines.validate(line: "23766C171EAA3484007A9026 /* ViewController.swift */,", betweenLine: iosChildrenStart, andLine: iosChildrenEnd)
lines.validate(line: "23766C191EAA3484007A9026 /* Main.storyboard */,", betweenLine: iosChildrenStart, andLine: iosChildrenEnd)
lines.validate(line: "23766C1C1EAA3484007A9026 /* Assets.xcassets */,", betweenLine: iosChildrenStart, andLine: iosChildrenEnd)
lines.validate(line: "23766C1E1EAA3484007A9026 /* LaunchScreen.storyboard */,", betweenLine: iosChildrenStart, andLine: iosChildrenEnd)
lines.validate(line: "23766C211EAA3484007A9026 /* Info.plist */,", betweenLine: iosChildrenStart, andLine: iosChildrenEnd)
lines.validate(line: "04D5C0A01F153915008A2F98 /* Public.h */,", betweenLine: iosChildrenStart, andLine: iosChildrenEnd)
lines.validate(line: "04D5C0A11F15391B008A2F98 /* Protected.h */,", betweenLine: iosChildrenStart, andLine: iosChildrenEnd)
lines.validate(line: "04D5C0A21F153921008A2F98 /* Private.h */,", betweenLine: iosChildrenStart, andLine: iosChildrenEnd)
// iOS Tests
let iosTestsGroup = lines.findLine("23766C291EAA3484007A9026 /* iOSTests */ = {", after: beginGroup)
let iosTestsChildrenStart = lines.findLine("children = (", after: iosTestsGroup)
let iosTestsChildrenEnd = lines.findLine(");", after: iosTestsChildrenStart)
lines.validate(line: "23766C2A1EAA3484007A9026 /* iOSTests.swift */,", betweenLine: iosTestsChildrenStart, andLine: iosTestsChildrenEnd)
lines.validate(line: "23766C2C1EAA3484007A9026 /* Info.plist */,", betweenLine: iosTestsChildrenStart, andLine: iosTestsChildrenEnd)
}
func test_navigator_groups_in_filename_order() {
let settings = PBXOutputSettings(projNavigatorFileOrder: .byFilename)
let lines = self.lines(fromFile: encodeProject(settings: settings))
let beginGroup = lines.findLine("/* Begin PBXGroup section */")
// Root
let rootGroup = lines.findLine("23766C091EAA3484007A9026 = {", after: beginGroup)
var line = lines.findLine("children = (", after: rootGroup)
line = lines.validate(line: "04D5C09D1F153824008A2F98 /* Frameworks */,", after: line)
line = lines.validate(line: "23766C131EAA3484007A9026 /* Products */,", after: line)
line = lines.validate(line: "23766C141EAA3484007A9026 /* iOS */,", after: line)
line = lines.validate(line: "23766C291EAA3484007A9026 /* iOSTests */,", after: line)
lines.validate(line: ");", after: line)
// iOS
let iosGroup = lines.findLine("23766C141EAA3484007A9026 /* iOS */ = {", after: beginGroup)
line = lines.findLine("children = (", after: iosGroup)
line = lines.validate(line: "23766C151EAA3484007A9026 /* AppDelegate.swift */,", after: line)
line = lines.validate(line: "23766C1C1EAA3484007A9026 /* Assets.xcassets */,", after: line)
line = lines.validate(line: "3CD1EAD92057638200DAEECB /* GroupWithoutFolder */,", after: line)
line = lines.validate(line: "23766C211EAA3484007A9026 /* Info.plist */,", after: line)
line = lines.validate(line: "23766C1E1EAA3484007A9026 /* LaunchScreen.storyboard */,", after: line)
line = lines.validate(line: "23766C191EAA3484007A9026 /* Main.storyboard */,", after: line)
line = lines.validate(line: "3CD1EADB205763E400DAEECB /* Model.xcdatamodeld */,", after: line)
line = lines.validate(line: "04D5C0A21F153921008A2F98 /* Private.h */,", after: line)
line = lines.validate(line: "04D5C0A11F15391B008A2F98 /* Protected.h */,", after: line)
line = lines.validate(line: "04D5C0A01F153915008A2F98 /* Public.h */,", after: line)
line = lines.validate(line: "23766C171EAA3484007A9026 /* ViewController.swift */,", after: line)
lines.validate(line: ");", after: line)
// iOS Tests
let iosTestsGroup = lines.findLine("23766C291EAA3484007A9026 /* iOSTests */ = {", after: beginGroup)
line = lines.findLine("children = (", after: iosTestsGroup)
line = lines.validate(line: "23766C2C1EAA3484007A9026 /* Info.plist */,", after: line)
line = lines.validate(line: "23766C2A1EAA3484007A9026 /* iOSTests.swift */,", after: line)
lines.validate(line: ");", after: line)
}
func test_navigator_groups_in_filename_groups_first_order() {
let settings = PBXOutputSettings(projNavigatorFileOrder: .byFilenameGroupsFirst)
let lines = self.lines(fromFile: encodeProject(settings: settings))
let beginGroup = lines.findLine("/* Begin PBXGroup section */")
// Root
let rootGroup = lines.findLine("23766C091EAA3484007A9026 = {", after: beginGroup)
var line = lines.findLine("children = (", after: rootGroup)
line = lines.validate(line: "04D5C09D1F153824008A2F98 /* Frameworks */,", after: line)
line = lines.validate(line: "23766C131EAA3484007A9026 /* Products */,", after: line)
line = lines.validate(line: "23766C141EAA3484007A9026 /* iOS */,", after: line)
line = lines.validate(line: "23766C291EAA3484007A9026 /* iOSTests */,", after: line)
lines.validate(line: ");", after: line)
// iOS
let iosGroup = lines.findLine("23766C141EAA3484007A9026 /* iOS */ = {", after: beginGroup)
line = lines.findLine("children = (", after: iosGroup)
line = lines.validate(line: "3CD1EAD92057638200DAEECB /* GroupWithoutFolder */,", after: line)
line = lines.validate(line: "23766C151EAA3484007A9026 /* AppDelegate.swift */,", after: line)
line = lines.validate(line: "23766C1C1EAA3484007A9026 /* Assets.xcassets */,", after: line)
line = lines.validate(line: "23766C211EAA3484007A9026 /* Info.plist */,", after: line)
line = lines.validate(line: "23766C1E1EAA3484007A9026 /* LaunchScreen.storyboard */,", after: line)
line = lines.validate(line: "23766C191EAA3484007A9026 /* Main.storyboard */,", after: line)
line = lines.validate(line: "3CD1EADB205763E400DAEECB /* Model.xcdatamodeld */,", after: line)
line = lines.validate(line: "04D5C0A21F153921008A2F98 /* Private.h */,", after: line)
line = lines.validate(line: "04D5C0A11F15391B008A2F98 /* Protected.h */,", after: line)
line = lines.validate(line: "04D5C0A01F153915008A2F98 /* Public.h */,", after: line)
line = lines.validate(line: "23766C171EAA3484007A9026 /* ViewController.swift */,", after: line)
lines.validate(line: ");", after: line)
// iOS Tests
let iosTestsGroup = lines.findLine("23766C291EAA3484007A9026 /* iOSTests */ = {", after: beginGroup)
line = lines.findLine("children = (", after: iosTestsGroup)
line = lines.validate(line: "23766C2C1EAA3484007A9026 /* Info.plist */,", after: line)
line = lines.validate(line: "23766C2A1EAA3484007A9026 /* iOSTests.swift */,", after: line)
lines.validate(line: ");", after: line)
}
// MARK: - Build phases
func test_build_phase_sources_unsorted() {
let lines = self.lines(fromFile: encodeProject())
let beginGroup = lines.findLine("/* Begin PBXSourcesBuildPhase section */")
let files = lines.findLine("files = (", after: beginGroup)
let endGroup = lines.findLine("/* End PBXSourcesBuildPhase section */")
lines.validate(line: "23766C181EAA3484007A9026 /* ViewController.swift in Sources */,", betweenLine: files, andLine: endGroup)
lines.validate(line: "23766C161EAA3484007A9026 /* AppDelegate.swift in Sources */,", betweenLine: files, andLine: endGroup)
lines.validate(line: "3CD1EADD205763E400DAEECB /* Model.xcdatamodeld in Sources */,", betweenLine: files, andLine: endGroup)
}
func test_build_phase_sources_sorted() {
let settings = PBXOutputSettings(projBuildPhaseFileOrder: .byFilename)
let lines = self.lines(fromFile: encodeProject(settings: settings))
let beginGroup = lines.findLine("/* Begin PBXSourcesBuildPhase section */")
var line = lines.findLine("files = (", after: beginGroup)
line = lines.validate(line: "23766C161EAA3484007A9026 /* AppDelegate.swift in Sources */,", after: line)
line = lines.validate(line: "3CD1EADD205763E400DAEECB /* Model.xcdatamodeld in Sources */,", after: line)
line = lines.validate(line: "23766C181EAA3484007A9026 /* ViewController.swift in Sources */,", after: line)
line = lines.validate(line: "/* End PBXSourcesBuildPhase section */", after: line)
}
func test_build_phase_headers_unsorted() {
let lines = self.lines(fromFile: encodeProject())
let beginGroup = lines.findLine("/* Begin PBXHeadersBuildPhase section */")
let files = lines.findLine("files = (", after: beginGroup)
let endGroup = lines.findLine("/* End PBXHeadersBuildPhase section */")
lines.validate(line: "04D5C0A41F153924008A2F98 /* Protected.h in Headers */,", betweenLine: files, andLine: endGroup)
lines.validate(line: "04D5C0A51F153924008A2F98 /* Private.h in Headers */,", betweenLine: files, andLine: endGroup)
lines.validate(line: "04D5C0A31F153924008A2F98 /* Public.h in Headers */,", betweenLine: files, andLine: endGroup)
}
func test_build_phase_headers_sorted() {
let settings = PBXOutputSettings(projBuildPhaseFileOrder: .byFilename)
let lines = self.lines(fromFile: encodeProject(settings: settings))
let beginGroup = lines.findLine("/* Begin PBXHeadersBuildPhase section */")
var line = lines.findLine("files = (", after: beginGroup)
line = lines.validate(line: "04D5C0A51F153924008A2F98 /* Private.h in Headers */,", after: line)
line = lines.validate(line: "04D5C0A41F153924008A2F98 /* Protected.h in Headers */,", after: line)
line = lines.validate(line: "04D5C0A31F153924008A2F98 /* Public.h in Headers */,", after: line)
line = lines.validate(line: "/* End PBXHeadersBuildPhase section */", after: line)
}
func test_build_phase_resources_unsorted() {
let lines = self.lines(fromFile: encodeProject())
let beginGroup = lines.findLine("/* Begin PBXResourcesBuildPhase section */")
let files = lines.findLine("files = (", after: beginGroup)
let endGroup = lines.findLine("/* End PBXResourcesBuildPhase section */")
lines.validate(line: "23766C1D1EAA3484007A9026 /* Assets.xcassets in Resources */,", betweenLine: files, andLine: endGroup)
lines.validate(line: "23766C1B1EAA3484007A9026 /* Main.storyboard in Resources */,", betweenLine: files, andLine: endGroup)
lines.validate(line: "23766C201EAA3484007A9026 /* LaunchScreen.storyboard in Resources */,", betweenLine: files, andLine: endGroup)
}
func test_build_phase_resources_sorted() {
let settings = PBXOutputSettings(projBuildPhaseFileOrder: .byFilename)
let lines = self.lines(fromFile: encodeProject(settings: settings))
let beginGroup = lines.findLine("/* Begin PBXResourcesBuildPhase section */")
var line = lines.findLine("files = (", after: beginGroup)
line = lines.validate(line: "23766C1D1EAA3484007A9026 /* Assets.xcassets in Resources */,", after: line)
line = lines.validate(line: "23766C201EAA3484007A9026 /* LaunchScreen.storyboard in Resources */,", after: line)
line = lines.validate(line: "23766C1B1EAA3484007A9026 /* Main.storyboard in Resources */,", after: line)
line = lines.validate(line: "/* End PBXResourcesBuildPhase section */", after: line)
}
// MARK: - Test internals
private func encodeProject(settings: PBXOutputSettings = PBXOutputSettings(), line: UInt = #line) -> String {
do {
return try PBXProjEncoder(outputSettings: settings).encode(proj: proj)
} catch {
XCTFail("Unexpected error encoding project: \(error)", line: line)
return ""
}
}
private func encodeProjectThrows<E>(error expectedError: E, line: UInt = #line) where E: Error {
do {
_ = try PBXProjEncoder(outputSettings: PBXOutputSettings()).encode(proj: proj)
XCTFail("Expected '\(expectedError)' to be thrown", line: line)
} catch {
if type(of: expectedError) != type(of: error) {
XCTFail("Expected '\(expectedError)' to be thrown, but got \(error)", line: line)
}
}
}
private func lines(fromFile file: String) -> [String] {
file.replacingOccurrences(of: "\t", with: "").components(separatedBy: "\n")
}
}
// MARK: - Line validations
private extension Array where Element == String {
@discardableResult func validate(line string: String, betweenLine lineAbove: Int, andLine lineBelow: Int, line: UInt = #line) -> Int {
validate(string, using: { $0 == $1 }, betweenLine: lineAbove, andLine: lineBelow, line: line)
}
@discardableResult func validate(lineContaining string: String, betweenLine lineAbove: Int, andLine lineBelow: Int, line: UInt = #line) -> Int {
validate(string, using: { $0.contains($1) }, betweenLine: lineAbove, andLine: lineBelow, line: line)
}
func validate(_ string: String, using: (String, String) -> Bool, betweenLine lineAbove: Int, andLine lineBelow: Int, line: UInt) -> Int {
let lineNumber = validate(string, using: using, after: lineAbove, line: line)
if lineNumber >= lineBelow {
XCTFail("Expected to find line between lines \(lineAbove) and \(lineBelow), but was found after \(lineBelow).", line: line)
}
return lineNumber
}
@discardableResult func validate(line string: String, onLineAfter: Int, line: UInt = #line) -> Int {
validate(string, using: { $0 == $1 }, onLineAfter: onLineAfter, line: line)
}
@discardableResult func validate(lineContaining string: String, onLineAfter: Int, line: UInt = #line) -> Int {
validate(string, using: { $0.contains($1) }, onLineAfter: onLineAfter, line: line)
}
func validate(_ string: String, using: (String, String) -> Bool, onLineAfter: Int, line: UInt) -> Int {
let lineNumber = validate(string, using: using, after: onLineAfter, line: line)
if lineNumber != onLineAfter + 1 {
XCTFail("Expected to find at line \(onLineAfter + 1), but was found on line \(lineNumber).", line: line)
}
return lineNumber
}
@discardableResult func validate(line string: String, after: Int = 0, line: UInt = #line) -> Int {
validate(string, using: { $0 == $1 }, after: after, line: line)
}
@discardableResult func validate(lineContaining string: String, after: Int = 0, line: UInt = #line) -> Int {
validate(string, using: { $0.contains($1) }, after: after, line: line)
}
func validate(_ string: String, using: (String, String) -> Bool, after: Int, line: UInt) -> Int {
let lineNumber = findLine(string, matcher: using, after: after)
if lineNumber == endIndex {
XCTFail("Line not found after line \(after)", line: line)
}
return lineNumber
}
func findLine(_ string: String, after: Int = 0) -> Int {
findLine(string, matcher: { $0 == $1 }, after: after)
}
func findLine(containing string: String, after: Int = 0) -> Int {
findLine(string, matcher: { $0.contains($1) }, after: after)
}
func findLine(_ string: String, matcher: (String, String) -> Bool, after: Int) -> Int {
for i in after ..< endIndex {
if matcher(self[i], string) {
return i
}
}
return endIndex
}
func log() {
var line: Int = 0
forEach {
let lineStr = "\(line)"
let lineNo = lineStr + String(repeating: " ", count: 5 - lineStr.count)
print(lineNo, "|", $0)
line += 1
}
}
}
| mit | 09ffdcdb000e990c7e32ca2a3578a5e9 | 64.82963 | 148 | 0.681445 | 3.546289 | false | true | false | false |
glaurent/MessagesHistoryBrowser | MessagesHistoryBrowser/RoundImage.swift | 1 | 1216 | //
// RoundImage.swift
// MessagesHistoryBrowser
//
// Created by Guillaume Laurent on 16/01/16.
// Copyright © 2016 Guillaume Laurent. All rights reserved.
//
import Cocoa
// Copied from http://stackoverflow.com/a/27157566/1081361
func roundCorners(_ image: NSImage) -> NSImage
{
let existing = image
let esize = existing.size
let sideLength = min(esize.width, esize.height) // make sure the resulting image is an actual circle - doesn't always look good if original image isn't properly centered
let newSize = NSSize(width:sideLength, height:sideLength)
let composedImage = NSImage(size: newSize)
composedImage.lockFocus()
let ctx = NSGraphicsContext.current
ctx?.imageInterpolation = NSImageInterpolation.high
let imageFrame = NSRect(x: 0, y: 0, width: sideLength, height: sideLength)
let clipPath = NSBezierPath(ovalIn: imageFrame)
clipPath.windingRule = NSBezierPath.WindingRule.evenOdd
clipPath.addClip()
let rect = NSRect(x: 0, y: 0, width: newSize.width, height: newSize.height)
image.draw(at: NSZeroPoint, from: rect, operation: NSCompositingOperation.sourceOver, fraction: 1)
composedImage.unlockFocus()
return composedImage
}
| gpl-3.0 | edb833cf8afe92dbc6d2e7008b6f7333 | 30.973684 | 173 | 0.730864 | 4.132653 | false | false | false | false |
Somnibyte/MLKit | MLKit/Classes/Helper Classes & Extensions/DataManager.swift | 1 | 8270 | //
// DataManager.swift
// MLKit
//
// Created by Guled on 6/30/16.
// Copyright © 2016 Guled. All rights reserved.
//
import Foundation
import Upsurge
open class MLDataManager {
enum MLDataHandelingError: Error {
case noData
case incorrectFraction
case unacceptableInput
var description: String {
switch(self) {
case .noData:
return "No data was provided."
case .incorrectFraction:
return "Your fraction must be between 1.0 and 0.0"
case .unacceptableInput:
return "Input was not accepted."
}
}
}
/**
The mean method calculates the mean of an array of numbers (of any type using the NumericType protocol).
- parameter data: An array of numbers.
- returns: The mean of the array
*/
open static func mean (_ data: Array<Float>) -> Float {
let totalSum = data.reduce(0.0, +)
let totalAmountOfData = Float(data.count)
return totalSum / totalAmountOfData
}
/**
The dataToMatrix method takes an array of features (which contain your data of a specific feature), along with your observations/output
and turns your features into a Matrix of type Float and your output into an array in order to be processed by machine learning algorithms
such as calculating the RSS/cost function for Regression.
- parameter features: An array of your features (which are suppose to be arrays as well).
- parameter output: An array of your observations/output.
- returns: A tuple that consists of a matrix and a array of type ValueArray
*/
open static func dataToMatrix (_ features: [Array<Float>], output: Array<Float>) -> (Matrix<Float>, ValueArray<Float>) {
// Create Output Matrix
let outputMatrix = Matrix<Float>(rows: output.count, columns: 1, elements: output)
// Create "contant/intercept" list
let constantArray = [Float](repeating: 1.0, count: features[0].count)
var matrixAsArray: [[Float]] = []
for (i, _) in constantArray.enumerated() {
var newRow: [Float] = []
newRow.append(constantArray[i])
for featureArray in features {
newRow.append(featureArray[i])
}
matrixAsArray.append(newRow)
}
let featureMatrix = Matrix<Float>(matrixAsArray)
return (featureMatrix, outputMatrix.elements)
}
/**
A method that takes in a string of arrays (if you read your data in from a CSV file) and converts it into an array of Float values.
- parameter data: A string array that contains your feature data.
- returns: An array of type Float.
*/
open static func convertMyDataToFloat(_ data: Array<String>) throws -> Array<Float> {
if data.count == 0 {
throw MLDataHandelingError.noData
}
let floatData: Array<Float> = data.map { Float($0)! }
return floatData
}
/**
The split data method allows you to split your original data into training and testing sets (or training,validation, and testing sets). The method takes in your data
and a fraction and splits your data based on the fraction you specify. So for example if you chose 0.5 (50%), you would get a tuple containing two halves of your data.
- parameter data: An array of your feature data.
- parameter fraction: The amount you want to split the data.
- returns: A tuple that contains your split data. The first entry of your tuple (0) will contain the fraction of data you specified, and the last entry of your tuple (1) will
contain whatever data is left.
*/
open static func splitData(_ data: Array<Float>, fraction: Float) throws -> (Array<Float>, Array<Float>) {
if data.count == 0 {
throw MLDataHandelingError.noData
}
if (fraction == 1.0 || fraction == 0.0 || fraction >= 1.0) {
throw MLDataHandelingError.incorrectFraction
}
let dataCount = Float(data.count)
let split = Int(fraction * dataCount)
let firstPortion = data[0 ..< split]
let secondPortion = data[split ..< data.count]
let firstPortionAsArray = Array(firstPortion)
let secondPortionAsArray = Array(secondPortion)
return (firstPortionAsArray, secondPortionAsArray)
}
/**
The randomlySplitData method allows you to split your original data into training and testing sets (or training,validation, and testing sets). The method takes in your data
(shuffles it in order to make it completely random) and a fraction and splits your data based on the fraction you specify. So for example if you chose 0.5 (50%), you would get a tuple containing two halves of your data (that have been randomly shuffled).
- parameter data: An array of your feature data.
- parameter fraction: The amount you want to split the data.
- returns: A tuple that contains your split data. The first entry of your tuple (0) will contain the fraction of data you specified, and the last entry of your tuple (1) will
contain whatever data is left.
*/
open static func randomlySplitData(_ data: Array<Float>, fraction: Float) throws -> (Array<Float>, Array<Float>) {
if data.count == 0 {
throw MLDataHandelingError.noData
}
if (fraction == 1.0 || fraction == 0.0 || fraction >= 1.0) {
print("Your fraction must be between 1.0 and 0.0")
throw MLDataHandelingError.incorrectFraction
}
// Shuffle the users input
var shuffledData = data.shuffle()
let dataCount = Float(data.count)
let split = Int(fraction * dataCount)
let firstPortion = shuffledData[0 ..< split]
let secondPortion = shuffledData[split ..< data.count]
let firstPortionAsArray = Array(firstPortion)
let secondPortionAsArray = Array(secondPortion)
return (firstPortionAsArray, secondPortionAsArray)
}
/**
The convertDataToPolynomialOfDegree function takes your array of data from 1 feature and allows you to create complex models
by raising your data up to the power of the degree parameter. For example if you pass in 1 feature (ex: [1,2,3]), and a degree of 3, the method
will return 3 arrays as follows: [ [1,2,3], [1,4,9], [1, 8, 27] ].
- parameter data: An array of your feature data.
- returns: An array of your features. The first will be your original data that was passed in since all the data within your feature was already raised to the
first power. Subsequent arrays will consist of your data being raised up to a certain degree.
*/
open static func convertDataToPolynomialOfDegree(_ data: Array<Float>, degree: Int) throws -> [Array<Float>] {
if data.count == 0 {
throw MLDataHandelingError.noData
}
if degree < 1 {
throw MLDataHandelingError.unacceptableInput
}
// Array of features
var features: [Array<Float>] = []
// Set the feature passed in as the first entry of the array since this is considered as "power_1" or "to the power of 1"
features.append(data)
if degree > 1 {
// Loop over remaining degrees
// range usually starts at 0 and stops at the endpoint-1. We want it to start at 2 and stop at degree
for power in 2..<(degree + 1) {
let newFeature = data.map { powf($0, Float(power)) }
features.append(newFeature)
}
}
return features
}
/**
The normalizeFeatures method calculates the l2 norm of your feature and output vectors.
- parameter features: Your feature vector.
- parameter output: Your output vector.
- returns: A matrix of your normalized data.
*/
open static func normalizeFeatures(_ features: [Array<Float>], output: Array<Float>) -> Matrix<Float> {
let featureMatrixAndOutput = dataToMatrix(features, output: output)
let normalizedFeatures = transpose(normalize(featureMatrixAndOutput.0))
return normalizedFeatures
}
}
| mit | b6f8a476adafe09b7dda1018283052ac | 37.282407 | 259 | 0.649293 | 4.474567 | false | false | false | false |
katfang/swift-overview | 02-arrays-and-dictionaries.playground/section-1.swift | 1 | 1215 | // --- Arrays and Dictionaries
// * typed
// * couple of ways of instantiating empty array
var emptyArray2 = [String]()
var emptyArray1: [String] = []
var emptyArray3 = Array<String>()
var supported = ["javascript"] // type Array<String> or [String]
supported += ["java", "objective-c"]
supported += ["swift"]
// supported += 3.0 // Errors because it's not a string
var emptyDictionary1 = [String: String]()
var emptyDictionary2 = Dictionary<String, String>()
var emptyDictionary3: [String:String] = [:]
var airports = ["SFO": "San Francisco", "BOS": "Logan"] // type [String:String]
airports["BER"] = "Berlin"
// -- Constant
let supportedImmutable = ["javascript"]
// supportedImmutable += ["swift"] // Errors because its immutable
// supportedImmutable[0] = "swift" // Errors because its immutable
let airportsImmutable = airports
// airportsImmutable["DUB"] = "Chicago" // errors
// -- Printing values in arrays and dictionaries
println("The first language supported is \(supported[0])")
// println("The SFO airport is named \(airport["SFO"])") // Errors because bad syntax
let sfo = airports["SFO"]
println("The SFO airport is named \(sfo!)") // Hey wait? What's that "!" doing? Find out in 04-optionals. | mit | 29094d12109dc8a049b2ab78830fc998 | 35.848485 | 105 | 0.693004 | 3.869427 | false | false | false | false |
gusrsilva/Picture-Perfect-iOS | PicturePerfect/MaterialButton.swift | 1 | 2675 | //
// CameraButton.swift
// PicturePerfect
//
// Created by Gus Silva on 4/15/17.
// Copyright © 2017 Gus Silva. All rights reserved.
//
import UIKit
class MaterialButton: UIButton {
var shadowLayer: CAShapeLayer!
var rippleLayer: CAShapeLayer!
override func layoutSubviews() {
super.layoutSubviews()
layer.cornerRadius = 0.5 * bounds.size.width
if shadowLayer == nil {
shadowLayer = CAShapeLayer()
shadowLayer.path = UIBezierPath(roundedRect: bounds, cornerRadius: 0.5*bounds.size.width).cgPath
shadowLayer.fillColor = backgroundColor?.cgColor
shadowLayer.shadowColor = UIColor.black.cgColor
shadowLayer.shadowPath = shadowLayer.path
shadowLayer.shadowOffset = CGSize(width: 5.0, height: 5.0)
shadowLayer.shadowOpacity = 0.25
shadowLayer.shadowRadius = 5
layer.insertSublayer(shadowLayer, at: 0)
}
if rippleLayer == nil {
rippleLayer = CAShapeLayer()
rippleLayer.path = UIBezierPath(roundedRect: bounds, cornerRadius: 0.5*bounds.size.width).cgPath
rippleLayer.bounds = bounds
rippleLayer.frame = bounds
rippleLayer.fillColor = tintColor.cgColor
rippleLayer.transform = CATransform3DMakeScale(0.0, 0.0, 1.0)
layer.insertSublayer(rippleLayer, at: 1)
}
}
func animatePress(onComplete: ((Void) -> Swift.Void)? = nil) {
ripple()
shrinkAndGrow(onComplete: onComplete)
}
func ripple() {
// Create a blank animation using the keyPath "cornerRadius", the property we want to animate
let animation = CABasicAnimation(keyPath: "transform")
animation.fromValue = CATransform3DMakeScale(0.2, 0.2, 1.0)
animation.toValue = CATransform3DMakeScale(1.0, 1.0, 1.0)
animation.repeatCount = 1
animation.duration = 0.3
rippleLayer.add(animation, forKey: "transform")
}
func shrinkAndGrow(onComplete: ((Void) -> Swift.Void)? = nil) {
UIView.animate(withDuration: 0.1,
animations: {
self.transform = CGAffineTransform(scaleX: 0.9, y: 0.9)
},
completion: { _ in
UIView.animate(withDuration: 0.1) {
self.transform = CGAffineTransform.identity
if let onComplete = onComplete {
onComplete()
}
}
})
}
}
| apache-2.0 | 66d60a427d522d759812f43782d0808e | 34.653333 | 108 | 0.567315 | 5.045283 | false | false | false | false |
jacobjiggler/FoodMate | src/iOS/FoodMate/FoodMate/HomeViewController.swift | 1 | 4598 | //
// HomeViewController.swift
// FoodMate
//
// Created by Jordan Horwich on 9/13/14.
// Copyright (c) 2014 FoodMate. All rights reserved.
//
import UIKit
class HomeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
//currently hardcoded, needs to be global app variables:
var my_name = "jordan"
var my_objectID = "LYHZxx4KrL"
@IBOutlet weak var tableView: UITableView!
var foodData:[AnyObject]! = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
var query : PFQuery = PFQuery(className: "Food_item")
query.findObjectsInBackgroundWithBlock({(objects:[AnyObject]!, NSError error) in
if (error != nil) {
NSLog("error " + error.localizedDescription)
}
else {
self.foodData = objects
self.tableView.reloadData()
}
})
}
/*
// 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.
}
*/
//////////////
// Table Stuff
//////////////
func numberOfSectionsInTableView(tableView: UITableView) ->Int
{
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) ->Int
{
//make sure you use the relevant array sizes
return foodData.count
}
func answered(code: String) -> Bool
{
return code.rangeOfString(my_objectID) != nil
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let objId = foodData[indexPath.row].objectId
var query = PFQuery(className:"Food_item")
var cell : HomeTableViewCell! = tableView.dequeueReusableCellWithIdentifier("GreenCell") as HomeTableViewCell
query.getObjectInBackgroundWithId(objId) {
(item: PFObject!, error: NSError!) -> Void in
if error == nil {
if item["response_code"] as? String != nil && self.answered(item["response_code"] as String){
// var response = item["response_code"] as String
// if self.answered(response) {
cell.backgroundColor = UIColor(red: 191/255, green: 255/255, blue: 168/255, alpha: 1.0)
// }
}
else if item["inStock"] as Bool! != nil && item["inStock"] as Bool {
cell.backgroundColor = UIColor.whiteColor() //(red: 255, green: 160, blue: 255, alpha: 1.0)
}
else
{
cell.backgroundColor = UIColor(red: 254/255, green: 255/255, blue: 160/255, alpha: 1.0)
}
cell.foodLabel.text = item["name"] as? String
cell.priceLabel.text = ("$" + String(format: "%.2f", item["price"].floatValue))
}
}
//var cell : HomeTableViewCell! = tableView.dequeueReusableCellWithIdentifier("GreenCell") as HomeTableViewCell
if(cell == nil) {
// cell = NSBundle.mainBundle().loadNibNamed("Cell", owner: self, options: nil)[0] as UITableViewCell;
cell = HomeTableViewCell()
}
return cell
}
/////////////////
// New Item Stuff
/////////////////
@IBAction func manualAddButtonClicked(sender: AnyObject) {
let storyboard = UIStoryboard(name: "Main", bundle: nil);
let vc = storyboard.instantiateViewControllerWithIdentifier("manualItem") as ManualItemViewController;
self.presentViewController(vc, animated: true, completion: nil);
}
@IBAction func cameraAddButtonClicked(sender: UIBarButtonItem) {
let storyboard = UIStoryboard(name: "Main", bundle: nil);
let vc = storyboard.instantiateViewControllerWithIdentifier("scanItem") as ScanItemViewController;
self.presentViewController(vc, animated: true, completion: nil);
}
} | mit | c1f7085d092f8a3a5da100f974f98290 | 33.320896 | 119 | 0.596999 | 5.058306 | false | false | false | false |
dduan/swift | validation-test/compiler_crashers_fixed/02138-swift-modulefile-maybereadpattern.swift | 11 | 642 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
protocol a {
protocol a {
typealias b = B)?
typealias B : b() {
}
}
}
func d: b<T) -> Any) {
var d : a {
}
class func b> {
for (self.E == Swift.d == i: NSObject {
}
protocol b {
class B, y: T? {
protocol A {
switch x }
}
}
}
}
var d = b(Any) + seq
l
| apache-2.0 | c08ca3cffb74af095845fcd844815573 | 19.709677 | 78 | 0.666667 | 3.07177 | false | false | false | false |
firebase/friendlyeats-ios | FriendlyEats/StarsView.swift | 2 | 9855 | //
// Copyright (c) 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
class RatingView: UIControl {
var highlightedColor: CGColor = Constants.highlightedColorOrange
var rating: Int? {
didSet {
if let value = rating {
setHighlighted(index: value - 1)
} else {
clearAll()
}
// highlight the appropriate amount of stars.
sendActions(for: .valueChanged)
}
}
private let starLayers: [CAShapeLayer]
override init(frame: CGRect) {
starLayers = (0 ..< 5).map {
let layer = RatingView.starLayer()
layer.frame = CGRect(x: $0 * 55, y: 0, width: 25, height: 25)
return layer
}
super.init(frame: frame)
starLayers.forEach {
layer.addSublayer($0)
}
}
private var starWidth: CGFloat {
return intrinsicContentSize.width / 5
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
guard let touch = touches.first else { return }
let point = touch.location(in: self)
let index = clamp(Int(point.x / starWidth))
setHighlighted(index: index)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesMoved(touches, with: event)
guard let touch = touches.first else { return }
let point = touch.location(in: self)
let index = clamp(Int(point.x / starWidth))
setHighlighted(index: index)
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
guard let touch = touches.first else { return }
let point = touch.location(in: self)
let index = clamp(Int(point.x / starWidth))
rating = index + 1 // Ratings are 1-indexed; things can be between 1-5 stars.
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesCancelled(touches, with: event)
guard touches.first != nil else { return }
// Cancelled touches should preserve the value before the interaction.
if let oldRating = rating {
let oldIndex = oldRating - 1
setHighlighted(index: oldIndex)
} else {
clearAll()
}
}
/// This is an awful func name. Index must be within 0 ..< 4, or crash.
private func setHighlighted(index: Int) {
// Highlight everything up to and including the star at the index.
(0 ... index).forEach {
let star = starLayers[$0]
star.strokeColor = highlightedColor
star.fillColor = highlightedColor
}
// Unhighlight everything after the index, if applicable.
guard index < 4 else { return }
((index + 1) ..< 5).forEach {
let star = starLayers[$0]
star.strokeColor = highlightedColor
star.fillColor = nil
}
}
/// Unhighlights every star.
private func clearAll() {
(0 ..< 5).forEach {
let star = starLayers[$0]
star.strokeColor = highlightedColor
star.fillColor = nil
}
}
private func clamp(_ index: Int) -> Int {
if index < 0 { return 0 }
if index > 4 { return 4 }
return index
}
override var intrinsicContentSize: CGSize {
return CGSize(width: 270, height: 50)
}
override var isMultipleTouchEnabled: Bool {
get { return false }
set {}
}
private static func starLayer() -> CAShapeLayer {
let layer = CAShapeLayer()
let mutablePath = CGMutablePath()
let outerRadius: CGFloat = 18
let outerPoints = stride(from: CGFloat.pi / -5, to: .pi * 2, by: 2 * .pi / 5).map {
return CGPoint(x: outerRadius * sin($0) + 25,
y: outerRadius * cos($0) + 25)
}
let innerRadius: CGFloat = 6
let innerPoints = stride(from: 0, to: .pi * 2, by: 2 * .pi / 5).map {
return CGPoint(x: innerRadius * sin($0) + 25,
y: innerRadius * cos($0) + 25)
}
let points = zip(outerPoints, innerPoints).reduce([CGPoint]()) { (aggregate, pair) -> [CGPoint] in
return aggregate + [pair.0, pair.1]
}
mutablePath.move(to: points[0])
points.forEach {
mutablePath.addLine(to: $0)
}
mutablePath.closeSubpath()
layer.path = mutablePath.copy()
layer.strokeColor = UIColor.gray.cgColor
layer.lineWidth = 1
layer.fillColor = nil
return layer
}
@available(*, unavailable)
required convenience init?(coder aDecoder: NSCoder) {
// coder is ignored.
self.init(frame: CGRect(x: 0, y: 0, width: 270, height: 50))
self.translatesAutoresizingMaskIntoConstraints = false
}
private enum Constants {
static let unhighlightedColor = UIColor.gray.cgColor
static let highlightedColorOrange = UIColor(red: 255 / 255, green: 179 / 255, blue: 0 / 255, alpha: 1).cgColor
}
// MARK: Rating View Accessibility
override var isAccessibilityElement: Bool {
get { return true }
set {}
}
override var accessibilityValue: String? {
get {
if let rating = rating {
return NSLocalizedString("\(rating) out of 5", comment: "Format string for indicating a variable amount of stars out of five")
}
return NSLocalizedString("No rating", comment: "Read by VoiceOver to vision-impaired users indicating a rating that hasn't been filled out yet")
}
set {}
}
override var accessibilityTraits: UIAccessibilityTraits {
get { return UIAccessibilityTraits.adjustable }
set {}
}
override func accessibilityIncrement() {
let currentRatingIndex = (rating ?? 0) - 1
let highlightedIndex = clamp(currentRatingIndex + 1)
rating = highlightedIndex + 1
}
override func accessibilityDecrement() {
guard let rating = rating else { return } // Doesn't make sense to decrement no rating and get 1.
let currentRatingIndex = rating - 1
let highlightedIndex = clamp(currentRatingIndex - 1)
self.rating = highlightedIndex + 1
}
}
// This class is absolutely not immutable, but it's also not user-interactive.
class ImmutableStarsView: UIView {
override var intrinsicContentSize: CGSize {
get { return CGSize(width: 100, height: 20) }
set {}
}
var highlightedColor: CGColor = Constants.highlightedColorOrange
var rating: Int? {
didSet {
if let value = rating {
setHighlighted(index: value - 1)
} else {
clearAll()
}
}
}
private let starLayers: [CAShapeLayer]
override init(frame: CGRect) {
starLayers = (0 ..< 5).map {
let layer = ImmutableStarsView.starLayer()
layer.frame = CGRect(x: $0 * 20, y: 0, width: 20, height: 20)
return layer
}
super.init(frame: frame)
starLayers.forEach {
layer.addSublayer($0)
}
}
private var starWidth: CGFloat {
return intrinsicContentSize.width / 5
}
/// This is an awful func name. Index must be within 0 ..< 4, or crash.
private func setHighlighted(index anyIndex: Int) {
if anyIndex < 0 {
clearAll()
return
}
let index = self.clamp(anyIndex)
// Highlight everything up to and including the star at the index.
(0 ... index).forEach {
let star = starLayers[$0]
star.strokeColor = highlightedColor
star.fillColor = highlightedColor
}
// Unhighlight everything after the index, if applicable.
guard index < 4 else { return }
((index + 1) ..< 5).forEach {
let star = starLayers[$0]
star.strokeColor = Constants.unhighlightedColor
star.fillColor = nil
}
}
/// Unhighlights every star.
private func clearAll() {
(0 ..< 5).forEach {
let star = starLayers[$0]
star.strokeColor = Constants.unhighlightedColor
star.fillColor = nil
}
}
private func clamp(_ index: Int) -> Int {
if index < 0 { return 0 }
if index >= 5 { return 4 }
return index
}
override var isUserInteractionEnabled: Bool {
get { return false }
set {}
}
private static func starLayer() -> CAShapeLayer {
let layer = CAShapeLayer()
let mutablePath = CGMutablePath()
let outerRadius: CGFloat = 9
let outerPoints = stride(from: CGFloat.pi / -5, to: .pi * 2, by: 2 * .pi / 5).map {
return CGPoint(x: outerRadius * sin($0) + 9,
y: outerRadius * cos($0) + 9)
}
let innerRadius: CGFloat = 4
let innerPoints = stride(from: 0, to: .pi * 2, by: 2 * .pi / 5).map {
return CGPoint(x: innerRadius * sin($0) + 9,
y: innerRadius * cos($0) + 9)
}
let points = zip(outerPoints, innerPoints).reduce([CGPoint]()) { (aggregate, pair) -> [CGPoint] in
return aggregate + [pair.0, pair.1]
}
mutablePath.move(to: points[0])
points.forEach {
mutablePath.addLine(to: $0)
}
mutablePath.closeSubpath()
layer.path = mutablePath.copy()
layer.strokeColor = UIColor.gray.cgColor
layer.lineWidth = 1
layer.fillColor = nil
return layer
}
@available(*, unavailable)
required convenience init?(coder aDecoder: NSCoder) {
// coder is ignored.
self.init(frame: CGRect(x: 0, y: 0, width: 270, height: 50))
self.translatesAutoresizingMaskIntoConstraints = false
}
private enum Constants {
static let unhighlightedColor = UIColor.gray.cgColor
static let highlightedColorOrange = UIColor(red: 255 / 255, green: 179 / 255, blue: 0 / 255, alpha: 1).cgColor
}
}
| apache-2.0 | c5c8907cadf7d194ac89f8bd6d8402c1 | 27.400576 | 150 | 0.641603 | 4.113105 | false | false | false | false |
radioboo/Scraper | Sources/swiftkiq-service/main.swift | 1 | 1410 | import Foundation
import Swiftkiq
class SKRouter: Routable {
func dispatch(processorId: Int, work: UnitOfWork) throws {
switch work.workerClass {
case "BlogCrawlingWorker":
try invokeWorker(processorId: processorId, workerClass: BlogCrawlingWorker.self, work: work)
case "ScrapingWorker":
try invokeWorker(processorId: processorId, workerClass: ScrapingWorker.self, work: work)
default:
break
}
}
func invokeWorker<W: Worker>(processorId: Int, workerClass: W.Type, work: UnitOfWork) throws {
let worker = workerClass.init()
let argument = workerClass.Args.from(work.args)
worker.processorId = processorId
worker.jid = work.jid
worker.retry = work.retry
worker.queue = work.queue
print("[INFO]: \(work.workerClass) start")
let start = Date()
try worker.perform(argument)
let interval = Date().timeIntervalSince(start)
print(String(format: "[INFO]: jid=%@ %@ done - %.4f msec", work.jid, work.workerClass, interval))
}
}
let router = SKRouter()
let options = LaunchOptions(
concurrency: 100,
queues: [Queue(rawValue: "default"), Queue(rawValue: "crawling"), Queue(rawValue: "scraping")],
router: router,
daemonize: false
)
let launcher = Launcher(options: options)
launcher.run()
while true {
sleep(1)
}
| mit | 719403cf1c4680065485e4fe26102ac5 | 31.790698 | 105 | 0.648227 | 3.916667 | false | false | false | false |
Epaus/SimpleParseTimelineAndMenu | LoginViewController.swift | 1 | 1448 | //
// LoginViewController.swift
// creators
//
// Created by Natasja Nielsen on 7/31/14.
// Copyright (c) 2014 Creators Co-op. All rights reserved.
//
import UIKit
import Foundation
import ParseUI
class LoginViewController: UIViewController, PFLogInViewControllerDelegate {
var login: PFLogInViewController = PFLogInViewController()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController!.navigationBar.hidden = true
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if (PFUser.currentUser() == nil ) {
var storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
var login : PFLogInView = PFLogInView()
// var loginFields : PFLoginFields = PFLoginFields();
// login.fields = loginFields
self.login.delegate = self
self.presentViewController(self.login, animated: false, completion: nil)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func logInViewController(logInController: PFLogInViewController!, didLogInUser user: PFUser!) {
self.dismissViewControllerAnimated(false, completion: nil)
//self.presentViewController(self.login, animated: false, completion: nil)
}
}
| gpl-3.0 | 79171a54c512292f6d771a4b003df57a | 30.478261 | 99 | 0.660221 | 5.080702 | false | false | false | false |
tonystone/geofeatures2 | Sources/GeoFeatures/WKTWriter.swift | 1 | 12831 | ///
/// WKTWriter.swift
///
/// Copyright (c) 2016 Tony Stone
///
/// 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.
///
/// Created by Tony Stone on 3/8/2016.
///
import Swift
extension WKTWriter {
public enum Axis {
case z, m
}
public enum Errors: Error {
case invalidNumberOfCoordinates(String)
}
/// Translated from BNF
private enum WKT: String {
case SINGLE_SPACE = " "
case NEW_LINE = "\\n"
case COMMA = ","
case LEFT_PAREN = "("
case RIGHT_PAREN = ")"
case LEFT_BRACKET = "["
case RIGHT_BRACKET = "]"
case THREEDIMENSIONAL = "Z"
case MEASURED = "M"
case EMPTY = "EMPTY"
case POINT = "POINT"
case LINESTRING = "LINESTRING"
case LINEARRING = "LINEARRING"
case POLYGON = "POLYGON"
case MULTIPOINT = "MULTIPOINT"
case MULTILINESTRING = "MULTILINESTRING"
case MULTIPOLYGON = "MULTIPOLYGON"
case GEOMETRYCOLLECTION = "GEOMETRYCOLLECTION"
case NAN = "NaN"
}
}
///
/// WKTWriter generates a WKT – Well-known Text – representation of a `Geometry` object.
///
/// - Remarks: GeoFeatures follows the OGC specification of WKT found here [OpenGIS Implementation Standard for Geographic information - Simple feature access - Part 1: Common architecture](http://portal.opengeospatial.org/files/?artifact_id=25355)
///
public class WKTWriter {
///
/// Initialize this writer
///
public init(axes: [Axis] = []) {
self.output = (axes.contains(.z), axes.contains(.m))
}
///
/// Based on the geometry passed in, converts it into a string representation as specified by
/// the OGC WKT standard.
///
/// - Parameter geometry: A geometry type to be converted to WKT
///
/// - Returns: WKT string for supported types. If unsupported, an empty string is returned.
///
/// - Note: This method does not check the validity of the geometry.
///
public func write(_ geometry: Geometry) throws -> String {
/// BNF: <geometry tagged text> ::= <point tagged text>
/// | <linestring tagged text>
/// | <polygon tagged text>
/// | <triangle tagged text>
/// | <polyhedralsurface tagged text>
/// | <tin tagged text>
/// | <multipoint tagged text>
/// | <multilinestring tagged text>
/// | <multipolygon tagged text>
/// | <geometrycollection tagged text>
///
switch geometry {
case let point as Point:
return try self.pointTaggedText(point)
case let lineString as LineString:
return try self.lineStringTaggedText(lineString)
case let linearRing as LinearRing:
return try self.linearRingTaggedText(linearRing)
case let polygon as Polygon:
return try self.polygonTaggedText(polygon)
case let multiPoint as MultiPoint:
return try self.multiPointTaggedText(multiPoint)
case let multiPolygon as MultiPolygon:
return try self.multiPolygonTaggedText(multiPolygon)
case let multiLineString as MultiLineString:
return try self.multiLineStringTaggedText(multiLineString)
case let geometryCollection as GeometryCollection:
return try self.geometryCollectionTaggedText(geometryCollection)
default: return ""
}
}
private let output: (z: Bool, m: Bool)
}
private extension WKTWriter {
/// BNF: <point tagged text> ::= point <point text>
private func pointTaggedText(_ point: Point) throws -> String {
return WKT.POINT.rawValue + WKT.SINGLE_SPACE.rawValue + zmText() + (try pointText(point))
}
/// BNF: <point text> ::= <empty set> | <left paren> <point> <right paren>
private func pointText(_ point: Point) throws -> String {
return WKT.LEFT_PAREN.rawValue + (try self.coordinateText(point.coordinate)) + WKT.RIGHT_PAREN.rawValue
}
/// BNF: <linestring tagged text> ::= linestring <linestring text>
private func lineStringTaggedText(_ lineString: LineString) throws -> String {
return WKT.LINESTRING.rawValue + WKT.SINGLE_SPACE.rawValue + zmText() + (try lineStringText(lineString))
}
/// BNF: <linestring text> ::= <empty set> | <left paren> <point> {<comma> <point>}* <right paren>
private func lineStringText(_ lineString: LineString) throws -> String {
if lineString.isEmpty() {
return WKT.EMPTY.rawValue
}
var lineStringText = WKT.LEFT_PAREN.rawValue
for index in 0..<lineString.count {
if index > 0 {
lineStringText += WKT.COMMA.rawValue + WKT.SINGLE_SPACE.rawValue
}
lineStringText += try self.coordinateText(lineString[index])
}
lineStringText += WKT.RIGHT_PAREN.rawValue
return lineStringText
}
/// BNF: None defined by OGC
private func linearRingTaggedText(_ linearRing: LinearRing) throws -> String {
return WKT.LINEARRING.rawValue + WKT.SINGLE_SPACE.rawValue + zmText() + (try linearRingText(linearRing))
}
/// BNF: None defined by OGC
private func linearRingText(_ linearRing: LinearRing) throws -> String {
if linearRing.isEmpty() {
return WKT.EMPTY.rawValue
}
var linearRingText = WKT.LEFT_PAREN.rawValue
for index in 0..<linearRing.count {
if index > 0 {
linearRingText += WKT.COMMA.rawValue + WKT.SINGLE_SPACE.rawValue
}
linearRingText += try self.coordinateText(linearRing[index])
}
linearRingText += WKT.RIGHT_PAREN.rawValue
return linearRingText
}
/// BNF: <polygon tagged text> ::= polygon <polygon text>
private func polygonTaggedText(_ polygon: Polygon) throws -> String {
return WKT.POLYGON.rawValue + WKT.SINGLE_SPACE.rawValue + zmText() + (try polygonText(polygon))
}
/// BNF: <polygon text> ::= <empty set> | <left paren> <linestring text> {<comma> <linestring text>}* <right paren>
private func polygonText(_ polygon: Polygon ) throws -> String {
if polygon.isEmpty() {
return WKT.EMPTY.rawValue
}
var polygonText = WKT.LEFT_PAREN.rawValue + (try linearRingText(polygon.outerRing))
for index in 0..<polygon.innerRings.count {
if index < polygon.innerRings.count {
polygonText += WKT.COMMA.rawValue + WKT.SINGLE_SPACE.rawValue
}
polygonText += try linearRingText(polygon.innerRings[index])
}
polygonText += WKT.RIGHT_PAREN.rawValue
return polygonText
}
/// BNF: <multipoint tagged text> ::= multipoint <multipoint text>
private func multiPointTaggedText(_ multiPoint: MultiPoint) throws -> String {
return WKT.MULTIPOINT.rawValue + WKT.SINGLE_SPACE.rawValue + zmText() + (try multiPointText(multiPoint))
}
/// BNF: <multipoint text> ::= <empty set> | <left paren> <point text> {<comma> <point text>}* <right paren>
private func multiPointText(_ multiPoint: MultiPoint) throws -> String {
if multiPoint.isEmpty() {
return WKT.EMPTY.rawValue
}
var multiPointText = WKT.LEFT_PAREN.rawValue
for index in 0..<multiPoint.count {
if index > 0 {
multiPointText += WKT.COMMA.rawValue + WKT.SINGLE_SPACE.rawValue
}
multiPointText += try pointText(multiPoint[index])
}
return multiPointText + WKT.RIGHT_PAREN.rawValue
}
/// BNF: <multilinestring tagged text> ::= multilinestring <multilinestring text>
private func multiLineStringTaggedText(_ multiLineString: MultiLineString) throws -> String {
return WKT.MULTILINESTRING.rawValue + WKT.SINGLE_SPACE.rawValue + zmText() + (try multiLineStringText(multiLineString))
}
/// BNF: <multilinestring text> ::= <empty set> | <left paren> <linestring text> {<comma> <linestring text>}* <right paren>
private func multiLineStringText(_ multiLineString: MultiLineString) throws -> String {
if multiLineString.isEmpty() {
return WKT.EMPTY.rawValue
}
var multiLineStringText = WKT.LEFT_PAREN.rawValue
for index in 0..<multiLineString.count {
if index > 0 {
multiLineStringText += WKT.COMMA.rawValue + WKT.SINGLE_SPACE.rawValue
}
multiLineStringText += try lineStringText(multiLineString[index])
}
return multiLineStringText + WKT.RIGHT_PAREN.rawValue
}
/// BNF: <multipolygon tagged text> ::= multipolygon <multipolygon text>
private func multiPolygonTaggedText(_ multiPolygon: MultiPolygon) throws -> String {
return WKT.MULTIPOLYGON.rawValue + WKT.SINGLE_SPACE.rawValue + zmText() + (try multiPolygonText(multiPolygon))
}
/// BNF: <multipolygon text> ::= <empty set> | <left paren> <polygon text> {<comma> <polygon text>}* <right paren>
private func multiPolygonText(_ multiPolygon: MultiPolygon ) throws -> String {
if multiPolygon.isEmpty() {
return WKT.EMPTY.rawValue
}
var multiPolygonText = WKT.LEFT_PAREN.rawValue
for index in 0..<multiPolygon.count {
if index > 0 {
multiPolygonText += WKT.COMMA.rawValue + WKT.SINGLE_SPACE.rawValue
}
multiPolygonText += try polygonText(multiPolygon[index])
}
return multiPolygonText + WKT.RIGHT_PAREN.rawValue
}
/// BNF: <geometrycollection tagged text> ::= geometrycollection <geometrycollection text>
private func geometryCollectionTaggedText(_ geometryCollection: GeometryCollection) throws -> String {
return WKT.GEOMETRYCOLLECTION.rawValue + WKT.SINGLE_SPACE.rawValue + zmText() + (try geometryCollectionText(geometryCollection))
}
/// BNF: <geometrycollection text> ::= <empty set> | <left paren> <geometry tagged text> {<comma> <geometry tagged text>}* <right paren>
private func geometryCollectionText(_ geometryCollection: GeometryCollection) throws -> String {
var geometryCollectionText = WKT.LEFT_PAREN.rawValue
for index in 0..<geometryCollection.count {
if index > 0 {
geometryCollectionText += WKT.COMMA.rawValue + WKT.SINGLE_SPACE.rawValue
}
geometryCollectionText += try write(geometryCollection[index])
}
return geometryCollectionText + WKT.RIGHT_PAREN.rawValue
}
/// BNF: <point> ::= <x> <y>
/// BNF: <point z> ::= <x> <y> <z>
/// BNF: <point m> ::= <x> <y> <m>
/// BNF: <point zm> ::= <x> <y> <z> <m>
private func coordinateText(_ coordinate: Coordinate) throws -> String {
var text = "\(coordinate.x) \(coordinate.y)"
if output.z {
guard let z = coordinate.z
else { throw Errors.invalidNumberOfCoordinates("Coordinate \(coordinate) is missing the Z axis.") }
text += " \(z)"
}
if output.m {
guard let m = coordinate.m
else { throw Errors.invalidNumberOfCoordinates("Coordinate \(coordinate) is missing the M axis.") }
text += " \(m)"
}
return text
}
private func zmText() -> String {
var zmText = ""
if output.z {
zmText += WKT.THREEDIMENSIONAL.rawValue
}
if output.m {
zmText += WKT.MEASURED.rawValue
}
if zmText != "" {
zmText += WKT.SINGLE_SPACE.rawValue
}
return zmText
}
}
| apache-2.0 | 03ebf83585d04876fa02dd3f39a61d92 | 34.829609 | 248 | 0.593358 | 4.34519 | false | false | false | false |
baottran/nSURE | nSURE/ESDayDropOffViewController.swift | 1 | 3255 | //
// ASDayDropOffViewController.swift
// nSURE
//
// Created by Bao Tran on 7/20/15.
// Copyright (c) 2015 Sprout Designs. All rights reserved.
//
import UIKit
class ESDayDropOffViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
@IBOutlet weak var dayLabel: UILabel!
@IBOutlet weak var timeSlotCollectionView: UICollectionView!
var repairObj: PFObject!
var repairArray: Array<PFObject>?
var currentDate: NSDate!
var timeSlotTaken = [false, false, false, false, false, false, false , false, false, false]
override func viewDidLoad() {
super.viewDidLoad()
// if let date
dayLabel.text = currentDate?.toLongDateString()
self.view.addSubview(timeSlotCollectionView)
timeSlotCollectionView.delegate = self
timeSlotCollectionView.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("TimeSlot", forIndexPath: indexPath) as! DayTimeSlotCollectionViewCell
if indexPath.row < 4 {
cell.dayTimeSlotLabel.text = "\(indexPath.row + 8):00 AM"
} else if indexPath.row == 4 {
cell.dayTimeSlotLabel.text = "12:00 PM"
} else {
cell.dayTimeSlotLabel.text = "\(indexPath.row - 4):00 PM"
}
let hour = indexPath.row + 8
let timeSlot = currentDate + hour.hours
if let repairs = repairArray {
for repair in repairs {
if let dropOffTime = repair["dropOffDate"] as? NSDate {
if (dropOffTime >= timeSlot) && (dropOffTime < (timeSlot + 1.hour)){
cell.dayTimeSlotLabel.text = "Taken"
self.timeSlotTaken[indexPath.row] = true
cell.backgroundColor = UIColor.grayColor()
}
}
}
}
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
if timeSlotTaken[indexPath.row] == false {
let chosenDate = currentDate.beginningOfDay + (indexPath.row + 8).hours
self.performSegueWithIdentifier("Review Assessment", sender: chosenDate)
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "Review Assessment" {
let reviewController = segue.destinationViewController as! ESReviewDropOffViewController
reviewController.chosenDate = sender as? NSDate
reviewController.assessmentObj = repairObj
}
}
}
| mit | d3953c9c4a5ef648f71cc2bc393be456 | 34.769231 | 143 | 0.631029 | 5.318627 | false | false | false | false |
kickstarter/ios-ksapi | KsApi/models/PushEnvelope.swift | 1 | 3390 | import Argo
import Curry
import Runes
public struct PushEnvelope {
public let activity: Activity?
public let aps: ApsEnvelope
public let forCreator: Bool?
public let liveStream: LiveStream?
public let message: Message?
public let project: Project?
public let survey: Survey?
public let update: Update?
public struct Activity {
public let category: KsApi.Activity.Category
public let commentId: Int?
public let id: Int
public let projectId: Int?
public let projectPhoto: String?
public let updateId: Int?
public let userPhoto: String?
}
public struct ApsEnvelope {
public let alert: String
}
public struct LiveStream {
public let id: Int
}
public struct Message {
public let messageThreadId: Int
public let projectId: Int
}
public struct Project {
public let id: Int
public let photo: String?
}
public struct Survey {
public let id: Int
public let projectId: Int
}
public struct Update {
public let id: Int
public let projectId: Int
}
}
extension PushEnvelope: Decodable {
public static func decode(_ json: JSON) -> Decoded<PushEnvelope> {
let create = curry(PushEnvelope.init)
let update: Decoded<Update> = json <| "update" <|> json <| "post"
let optionalUpdate: Decoded<Update?> = update.map(Optional.some) <|> .success(nil)
let tmp = create
<^> json <|? "activity"
<*> json <| "aps"
<*> json <|? "for_creator"
<*> json <|? "live_stream"
return tmp
<*> json <|? "message"
<*> json <|? "project"
<*> json <|? "survey"
<*> optionalUpdate
}
}
extension PushEnvelope.Activity: Decodable {
public static func decode(_ json: JSON) -> Decoded<PushEnvelope.Activity> {
let create = curry(PushEnvelope.Activity.init)
let tmp = create
<^> json <| "category"
<*> json <|? "comment_id"
<*> json <| "id"
<*> json <|? "project_id"
return tmp
<*> json <|? "project_photo"
<*> json <|? "update_id"
<*> json <|? "user_photo"
}
}
extension PushEnvelope.ApsEnvelope: Decodable {
public static func decode(_ json: JSON) -> Decoded<PushEnvelope.ApsEnvelope> {
return curry(PushEnvelope.ApsEnvelope.init)
<^> json <| "alert"
}
}
extension PushEnvelope.LiveStream: Decodable {
public static func decode(_ json: JSON) -> Decoded<PushEnvelope.LiveStream> {
return curry(PushEnvelope.LiveStream.init)
<^> json <| "id"
}
}
extension PushEnvelope.Message: Decodable {
public static func decode(_ json: JSON) -> Decoded<PushEnvelope.Message> {
return curry(PushEnvelope.Message.init)
<^> json <| "message_thread_id"
<*> json <| "project_id"
}
}
extension PushEnvelope.Project: Decodable {
public static func decode(_ json: JSON) -> Decoded<PushEnvelope.Project> {
return curry(PushEnvelope.Project.init)
<^> json <| "id"
<*> json <|? "photo"
}
}
extension PushEnvelope.Survey: Decodable {
public static func decode(_ json: JSON) -> Decoded<PushEnvelope.Survey> {
return curry(PushEnvelope.Survey.init)
<^> json <| "id"
<*> json <| "project_id"
}
}
extension PushEnvelope.Update: Decodable {
public static func decode(_ json: JSON) -> Decoded<PushEnvelope.Update> {
return curry(PushEnvelope.Update.init)
<^> json <| "id"
<*> json <| "project_id"
}
}
| apache-2.0 | 11ee00df5d1150892caf2e8c22a6cac1 | 24.488722 | 86 | 0.641298 | 3.96028 | false | false | false | false |
ACChe/eidolon | Kiosk/Bid Fulfillment/ConfirmYourBidPINViewController.swift | 1 | 5423 | import UIKit
import Moya
import ReactiveCocoa
class ConfirmYourBidPINViewController: UIViewController {
dynamic var pin = ""
@IBOutlet var keypadContainer: KeypadContainerView!
@IBOutlet var pinTextField: TextField!
@IBOutlet var confirmButton: Button!
@IBOutlet var bidDetailsPreviewView: BidDetailsPreviewView!
lazy var pinSignal: RACSignal = { self.keypadContainer.stringValueSignal }()
lazy var provider: ReactiveCocoaMoyaProvider<ArtsyAPI> = Provider.sharedProvider
class func instantiateFromStoryboard(storyboard: UIStoryboard) -> ConfirmYourBidPINViewController {
return storyboard.viewControllerWithID(.ConfirmYourBidPIN) as! ConfirmYourBidPINViewController
}
override func viewDidLoad() {
super.viewDidLoad()
RAC(self, "pin") <~ pinSignal
RAC(pinTextField, "text") <~ pinSignal
RAC(fulfillmentNav().bidDetails, "bidderPIN") <~ pinSignal
let pinExistsSignal = pinSignal.map { ($0 as! String).isNotEmpty }
bidDetailsPreviewView.bidDetails = fulfillmentNav().bidDetails
/// verify if we can connect with number & pin
confirmButton.rac_command = RACCommand(enabled: pinExistsSignal) { [weak self] _ in
guard let strongSelf = self else { return RACSignal.empty() }
let phone = strongSelf.fulfillmentNav().bidDetails.newUser.phoneNumber ?? ""
let endpoint: ArtsyAPI = ArtsyAPI.Me
let loggedInProvider = strongSelf.providerForPIN(strongSelf.pin, number: phone)
return loggedInProvider.request(endpoint).filterSuccessfulStatusCodes().doNext { _ in
// If the request to ArtsyAPI.Me succeeds, we have logged in and can use this provider.
self?.fulfillmentNav().loggedInProvider = loggedInProvider
}.andThen {
// We want to put the data we've collected up to the server.
self?.fulfillmentNav().updateUserCredentials()
}.andThen {
// This looks for credit cards on the users account, and sends them on the signal
self?.checkForCreditCard()
}.doNext { (cards) in
// If the cards list doesn't exist, or its empty, then perform the segue to collect one.
// Otherwise, proceed directly to the loading view controller to place the bid.
if (cards as? [Card]).isNilOrEmpty {
self?.performSegue(.ArtsyUserviaPINHasNotRegisteredCard)
} else {
self?.performSegue(.PINConfirmedhasCard)
}
}.doError({ [weak self] (error) -> Void in
if let response = error.userInfo["data"] as? MoyaResponse {
let responseBody = NSString(data: response.data, encoding: NSUTF8StringEncoding)
print("Error authenticating(\(response.statusCode)): \(responseBody)")
}
self?.showAuthenticationError()
return
})
}
}
@IBAction func forgotPINTapped(sender: AnyObject) {
let auctionID = fulfillmentNav().auctionID
let number = fulfillmentNav().bidDetails.newUser.phoneNumber ?? ""
let endpoint: ArtsyAPI = ArtsyAPI.BidderDetailsNotification(auctionID: auctionID, identifier: number)
let alertController = UIAlertController(title: "Forgot PIN", message: "We have sent your bidder details to your device.", preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "Back", style: .Cancel) { (_) in }
alertController.addAction(cancelAction)
self.presentViewController(alertController, animated: true) {}
XAppRequest(endpoint, provider: Provider.sharedProvider).filterSuccessfulStatusCodes().subscribeNext { (_) -> Void in
// Necessary to subscribe to the actual signal. This should be in a RACCommand of the button, instead.
logger.log("Sent forgot PIN request")
}
}
func providerForPIN(pin: String, number: String) -> ReactiveCocoaMoyaProvider<ArtsyAPI> {
let newEndpointsClosure = { (target: ArtsyAPI) -> Endpoint<ArtsyAPI> in
// Grab existing endpoint to piggy-back off of any existing configurations being used by the sharedprovider.
let endpoint = Provider.sharedProvider.endpointClosure(target)
let auctionID = self.fulfillmentNav().auctionID
return endpoint.endpointByAddingParameters(["auction_pin": pin, "number": number, "sale_id": auctionID])
}
return ReactiveCocoaMoyaProvider(endpointClosure: newEndpointsClosure, requestClosure: endpointResolver(), stubClosure: Provider.APIKeysBasedStubBehaviour, plugins: Provider.plugins)
}
func showAuthenticationError() {
confirmButton.flashError("Wrong PIN")
pinTextField.flashForError()
keypadContainer.resetCommand.execute(nil)
}
func checkForCreditCard() -> RACSignal {
let endpoint: ArtsyAPI = ArtsyAPI.MyCreditCards
let authProvider = self.fulfillmentNav().loggedInProvider!
return authProvider.request(endpoint).filterSuccessfulStatusCodes().mapJSON().mapToObjectArray(Card.self)
}
}
private extension ConfirmYourBidPINViewController {
@IBAction func dev_loggedInTapped(sender: AnyObject) {
self.performSegue(.PINConfirmedhasCard)
}
} | mit | fc9a6c8de8a6076c97139ab935542914 | 44.2 | 190 | 0.66974 | 5.461229 | false | false | false | false |
exchangegroup/swift-badge | BadgeSwift/BadgeSwift.swift | 2 | 5046 | import UIKit
/**
Badge view control for iOS and tvOS.
Project home: https://github.com/evgenyneu/swift-badge
*/
@IBDesignable open class BadgeSwift: UILabel {
/// Background color of the badge
@IBInspectable open var badgeColor: UIColor = UIColor.red {
didSet {
setNeedsDisplay()
}
}
/// Width of the badge border
@IBInspectable open var borderWidth: CGFloat = 0 {
didSet {
invalidateIntrinsicContentSize()
}
}
/// Color of the bardge border
@IBInspectable open var borderColor: UIColor = UIColor.white {
didSet {
invalidateIntrinsicContentSize()
}
}
/// Badge insets that describe the margin between text and the edge of the badge.
@IBInspectable open var insets: CGSize = CGSize(width: 5, height: 2) {
didSet {
invalidateIntrinsicContentSize()
}
}
// MARK: Badge shadow
// --------------------------
/// Opacity of the badge shadow
@IBInspectable open var shadowOpacityBadge: CGFloat = 0.5 {
didSet {
layer.shadowOpacity = Float(shadowOpacityBadge)
setNeedsDisplay()
}
}
/// Size of the badge shadow
@IBInspectable open var shadowRadiusBadge: CGFloat = 0.5 {
didSet {
layer.shadowRadius = shadowRadiusBadge
setNeedsDisplay()
}
}
/// Color of the badge shadow
@IBInspectable open var shadowColorBadge: UIColor = UIColor.black {
didSet {
layer.shadowColor = shadowColorBadge.cgColor
setNeedsDisplay()
}
}
/// Offset of the badge shadow
@IBInspectable open var shadowOffsetBadge: CGSize = CGSize(width: 0, height: 0) {
didSet {
layer.shadowOffset = shadowOffsetBadge
setNeedsDisplay()
}
}
/// Corner radius of the badge. -1 if unspecified. When unspecified, the corner is fully rounded. Default: -1.
@IBInspectable open var cornerRadius: CGFloat = -1 {
didSet {
setNeedsDisplay()
}
}
/// Initialize the badge view
convenience public init() {
self.init(frame: CGRect())
}
/// Initialize the badge view
override public init(frame: CGRect) {
super.init(frame: frame)
setup()
}
/// Initialize the badge view
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
/// Add custom insets around the text
override open func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
let rect = super.textRect(forBounds: bounds, limitedToNumberOfLines: numberOfLines)
var insetsWithBorder = actualInsetsWithBorder()
let rectWithDefaultInsets = rect.insetBy(dx: -insetsWithBorder.width, dy: -insetsWithBorder.height)
// If width is less than height
// Adjust the width insets to make it look round
if rectWithDefaultInsets.width < rectWithDefaultInsets.height {
insetsWithBorder.width = (rectWithDefaultInsets.height - rect.width) / 2
}
let result = rect.insetBy(dx: -insetsWithBorder.width, dy: -insetsWithBorder.height)
return result
}
/// Draws the label with insets
override open func drawText(in rect: CGRect) {
if cornerRadius >= 0 {
layer.cornerRadius = cornerRadius
}else {
// Use fully rounded corner if radius is not specified
layer.cornerRadius = rect.height / 2
}
let insetsWithBorder = actualInsetsWithBorder()
let insets = UIEdgeInsets(
top: insetsWithBorder.height,
left: insetsWithBorder.width,
bottom: insetsWithBorder.height,
right: insetsWithBorder.width)
let rectWithoutInsets = rect.inset(by: insets)
super.drawText(in: rectWithoutInsets)
}
/// Draw the background of the badge
override open func draw(_ rect: CGRect) {
let rectInset = rect.insetBy(dx: borderWidth/2, dy: borderWidth/2)
let actualCornerRadius = cornerRadius >= 0 ? cornerRadius : rect.height/2
var path: UIBezierPath?
if actualCornerRadius == 0 {
// Use rectangular path when corner radius is zero as a workaround
// a glith in the left top corner with UIBezierPath(roundedRect).
path = UIBezierPath(rect: rectInset)
} else {
path = UIBezierPath(roundedRect: rectInset, cornerRadius: actualCornerRadius)
}
badgeColor.setFill()
path?.fill()
if borderWidth > 0 {
borderColor.setStroke()
path?.lineWidth = borderWidth
path?.stroke()
}
super.draw(rect)
}
private func setup() {
textAlignment = NSTextAlignment.center
clipsToBounds = false // Allows shadow to spread beyond the bounds of the badge
}
/// Size of the insets plus the border
private func actualInsetsWithBorder() -> CGSize {
return CGSize(
width: insets.width + borderWidth,
height: insets.height + borderWidth
)
}
/// Draw the stars in interface builder
@available(iOS 8.0, *)
override open func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
setup()
setNeedsDisplay()
}
}
| mit | 61c045e311ffa01d5dd1e256f97d0a91 | 25.840426 | 112 | 0.664487 | 4.663586 | false | false | false | false |
lishengbing/XJDomainLive | XJDomainLive/XJDomainLive/Classes/Home/View/Live/LiveTopCollectionView.swift | 1 | 1531 | //
// LiveTopCollectionView.swift
// XJDomainLive
//
// Created by 李胜兵 on 2016/12/10.
// Copyright © 2016年 付公司. All rights reserved.
//
import UIKit
private let KCellIdentifier = "KCellIdentifier"
class LiveTopCollectionView: UICollectionView {
override func awakeFromNib() {
super.awakeFromNib()
setupUI()
}
override func layoutSubviews() {
super.layoutSubviews()
let layout = collectionViewLayout as! UICollectionViewFlowLayout
let itemW : CGFloat = self.bounds.size.height
layout.itemSize = CGSize(width: itemW, height: itemW)
layout.minimumLineSpacing = 10
layout.minimumInteritemSpacing = 0
layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0)
}
}
extension LiveTopCollectionView {
fileprivate func setupUI() {
dataSource = self
delegate = self
register(UINib(nibName: "LiveTopCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: KCellIdentifier)
}
}
extension LiveTopCollectionView : UICollectionViewDataSource, UICollectionViewDelegate{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 200
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: KCellIdentifier, for: indexPath) as! LiveTopCollectionViewCell
return cell
}
}
| apache-2.0 | 38dcd07dea4040cb5d937872250d194e | 29.938776 | 137 | 0.708443 | 5.209622 | false | false | false | false |
tonyarnold/Bond | Sources/Bond/Observable Collections/ChangesetContainer.swift | 1 | 5485 | //
// The MIT License (MIT)
//
// Copyright (c) 2018 DeclarativeHub/Bond
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import ReactiveKit
/// A type that contains or wraps a changeset.
public protocol ChangesetContainerProtocol: class {
associatedtype Changeset: ChangesetProtocol
/// Contained changeset.
var changeset: Changeset { get }
}
public protocol MutableChangesetContainerProtocol: ChangesetContainerProtocol {
var changeset: Changeset { get set }
}
extension ChangesetContainerProtocol {
public typealias Collection = Changeset.Collection
public typealias Operation = Changeset.Operation
public typealias Diff = Changeset.Diff
/// Collection contained in the changeset (`changeset.collection`).
public var collection: Collection {
return changeset.collection
}
}
extension MutableChangesetContainerProtocol {
/// Update the collection and provide a description of changes as patch.
public func descriptiveUpdate(_ update: (inout Collection) -> [Operation]) {
var collection = changeset.collection
let patch = update(&collection)
changeset = Changeset(collection: collection, patch: patch)
}
/// Update the collection and provide a description of changes as diff.
public func descriptiveUpdate(_ update: (inout Collection) -> Diff) {
var collection = changeset.collection
let diff = update(&collection)
changeset = Changeset(collection: collection, diff: diff)
}
/// Update the collection and provide a description of changes as patch.
public func descriptiveUpdate<T>(_ update: (inout Collection) -> ([Operation], T)) -> T {
var collection = changeset.collection
let (patch, returnValue) = update(&collection)
changeset = Changeset(collection: collection, patch: patch)
return returnValue
}
/// Replace the underlying collection with the given collection.
public func replace(with newCollection: Collection) {
descriptiveUpdate { (collection) -> [Changeset.Operation] in
collection = newCollection
return []
}
}
/// Replace the underlying collection with the given collection. Setting `performDiff: true` will make the framework
/// calculate the diff between the existing and new collection and emit an event with the calculated diff.
public func replace(with newCollection: Collection, performDiff: Bool, generateDiff: (Collection, Collection) -> Diff) {
if performDiff {
descriptiveUpdate { (collection) -> Diff in
let diff = generateDiff(collection, newCollection)
collection = newCollection
return diff
}
} else {
replace(with: newCollection)
}
}
}
extension ChangesetContainerProtocol where Changeset.Collection: Swift.Collection {
/// Returns `true` if underlying collection is empty, `false` otherwise.
public var isEmpty: Bool {
return collection.isEmpty
}
/// Number of elements in the underlying collection.
public var count: Int {
return collection.count
}
/// Access the collection element at `index`.
public subscript(index: Collection.Index) -> Collection.Element {
get {
return collection[index]
}
}
}
extension ChangesetContainerProtocol where Changeset.Collection: Swift.Collection, Changeset.Collection.Index == Int {
/// Underlying array.
public var array: Collection {
return collection
}
}
extension ChangesetContainerProtocol where Changeset.Collection: TreeProtocol {
/// Underlying tree.
public var tree: Collection {
return collection
}
/// Access the element at `index`.
public subscript(childAt indexPath: IndexPath) -> Collection.Children.Element {
get {
return collection[childAt: indexPath]
}
}
}
extension SignalProtocol where Error == NoError {
/// Bind the collection signal to the given changeset container like MutableObervableArray.
@discardableResult
public func bind<C: ChangesetContainerProtocol>(to changesetContainer: C) -> Disposable where C: BindableProtocol, C.Element == C.Changeset, C.Changeset.Collection == Element {
return map { C.Changeset(collection: $0, diff: .init()) }.bind(to: changesetContainer)
}
}
| mit | f9c7908c8441fa78835bd50d54b58b5b | 35.324503 | 180 | 0.699362 | 5.022894 | false | false | false | false |
mercadopago/px-ios | MercadoPagoSDK/MercadoPagoSDK/UI/PXResult/New UI/PXNewResultUtil.swift | 1 | 10688 | import Foundation
import MLBusinessComponents
import AndesUI
class PXNewResultUtil {
// TRACKING
class func trackScreenAndConversion(viewModel: PXViewModelTrackingDataProtocol) {
let path = viewModel.getTrackingPath()
if let path = path {
MPXTracker.sharedInstance.trackScreen(event: path)
let behaviourProtocol = PXConfiguratorManager.flowBehaviourProtocol
behaviourProtocol.trackConversion(result: viewModel.getFlowBehaviourResult())
}
}
// RECEIPT DATA
class func getDataForReceiptView(paymentId: String?) -> PXNewCustomViewData? {
guard let paymentId = paymentId else {
return nil
}
let attributedTitle = NSAttributedString(string: ("Operación #{0}".localized as NSString).replacingOccurrences(of: "{0}", with: "\(paymentId)"), attributes: PXNewCustomView.titleAttributes)
let date = Date()
let attributedSubtitle = NSAttributedString(string: Utils.getFormatedStringDate(date, addTime: true), attributes: PXNewCustomView.subtitleAttributes)
let icon = ResourceManager.shared.getImage("receipt_icon")
let data = PXNewCustomViewData(firstString: attributedTitle, secondString: attributedSubtitle, thirdString: nil, fourthString: nil, bottomString: nil, icon: icon, iconURL: nil, action: nil, color: nil)
return data
}
// POINTS DATA
class func getDataForPointsView(points: PXPoints?) -> MLBusinessLoyaltyRingData? {
guard let points = points else {
return nil
}
let data = PXRingViewData(points: points)
return data
}
// DISCOUNTS DATA
class func getDataForDiscountsView(discounts: PXDiscounts?) -> MLBusinessDiscountBoxData? {
guard let discounts = discounts else {
return nil
}
let data = PXDiscountsBoxData(discounts: discounts)
return data
}
class func getDataForTouchpointsView(discounts: PXDiscounts?) -> MLBusinessTouchpointsData? {
guard let touchpoint = discounts?.touchpoint else {
return nil
}
let data = PXDiscountsTouchpointsData(touchpoint: touchpoint)
return data
}
// DISCOUNTS ACCESSORY VIEW
class func getDataForDiscountsAccessoryViewData(discounts: PXDiscounts?) -> ResultViewData? {
guard let discounts = discounts else {
return nil
}
let dataService = MLBusinessAppDataService()
if dataService.isMpAlreadyInstalled() {
let button = AndesButton(text: discounts.discountsAction.label, hierarchy: .quiet, size: .large)
button.add(for: .touchUpInside) {
// open deep link
PXDeepLinkManager.open(discounts.discountsAction.target)
MPXTracker.sharedInstance.trackEvent(event: PXResultTrackingEvents.didTapOnAllDiscounts)
}
return ResultViewData(view: button, verticalMargin: PXLayout.M_MARGIN, horizontalMargin: PXLayout.L_MARGIN)
} else {
let downloadAppDelegate = PXDownloadAppData(discounts: discounts)
let downloadAppView = MLBusinessDownloadAppView(downloadAppDelegate)
downloadAppView.addTapAction { deepLink in
// open deep link
PXDeepLinkManager.open(deepLink)
MPXTracker.sharedInstance.trackEvent(event: PXResultTrackingEvents.didtapOnDownload)
}
return ResultViewData(view: downloadAppView, verticalMargin: PXLayout.M_MARGIN, horizontalMargin: PXLayout.L_MARGIN)
}
}
// EXPENSE SPLIT DATA
class func getDataForExpenseSplitView(expenseSplit: PXExpenseSplit) -> MLBusinessActionCardViewData {
return PXExpenseSplitData(expenseSplitData: expenseSplit)
}
// CROSS SELLING VIEW
class func getDataForCrossSellingView(crossSellingItems: [PXCrossSellingItem]?) -> [MLBusinessCrossSellingBoxData]? {
guard let crossSellingItems = crossSellingItems else {
return nil
}
var data = [MLBusinessCrossSellingBoxData]()
for item in crossSellingItems {
data.append(PXCrossSellingItemData(item: item))
}
return data
}
// URL logic
enum PXAutoReturnTypes: String {
case APPROVED = "approved"
case ALL = "all"
}
class func openURL(url: URL, success: @escaping (Bool) -> Void) {
if UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url, options: [:], completionHandler: { result in
sleep(1)
success(result)
})
} else {
success(false)
}
}
}
// MARK: Payment Method Logic
extension PXNewResultUtil {
// ATTRIBUTES FOR DISPLAYING PAYMENT METHOD
static let totalAmountAttributes: [NSAttributedString.Key: Any] = [
NSAttributedString.Key.font: Utils.getSemiBoldFont(size: PXLayout.XS_FONT),
NSAttributedString.Key.foregroundColor: UIColor.black.withAlphaComponent(0.45)
]
static let interestRateAttributes: [NSAttributedString.Key: Any] = [
NSAttributedString.Key.font: Utils.getSemiBoldFont(size: PXLayout.XS_FONT),
NSAttributedString.Key.foregroundColor: ThemeManager.shared.noTaxAndDiscountLabelTintColor()
]
static let discountAmountAttributes: [NSAttributedString.Key: Any] = [
NSAttributedString.Key.font: Utils.getSemiBoldFont(size: PXLayout.XS_FONT),
NSAttributedString.Key.foregroundColor: UIColor.black.withAlphaComponent(0.45),
NSAttributedString.Key.strikethroughStyle: NSUnderlineStyle.single.rawValue
]
// PAYMENT METHOD ICON URL
class func getPaymentMethodIconURL(for paymentMethodId: String, using paymentMethodsImageURLs: [String: String]) -> String? {
guard paymentMethodsImageURLs.keys.contains(paymentMethodId), let iconURLString = paymentMethodsImageURLs[paymentMethodId] else {
return nil
}
return iconURLString
}
class func formatPaymentMethodFirstString(paymentInfo: PXCongratsPaymentInfo) -> NSAttributedString {
var firstString: NSMutableAttributedString = NSMutableAttributedString()
if paymentInfo.hasInstallments { // Pago en cuotas
if let installmentsAmount = paymentInfo.installmentsAmount, let installmentsTotalAmount = paymentInfo.installmentsTotalAmount {
firstString = textForInstallmentsPayment(installmentsCount: paymentInfo.installmentsCount, installmentsRate: paymentInfo.installmentsRate, installmentsAmount: installmentsAmount, installmentsTotalAmount: installmentsTotalAmount)
}
} else { // Caso account money
firstString.append(textForNonInstallmentPayment(paidAmount: paymentInfo.paidAmount))
}
if paymentInfo.hasDiscount {
if let discountName = paymentInfo.discountName, let rawAmount = paymentInfo.rawAmount {
let message = discountMessage(discountName, transactionAmount: rawAmount)
firstString.append(message)
}
}
return firstString
}
class func textForInstallmentsPayment(installmentsCount: Int, installmentsRate: Double, installmentsAmount: String, installmentsTotalAmount: String) -> NSMutableAttributedString {
guard installmentsCount > 1 else {
return NSMutableAttributedString(string: installmentsTotalAmount, attributes: PXNewCustomView.titleAttributes)
}
let finalString: NSMutableAttributedString = NSMutableAttributedString()
let titleString = String(format: "%dx %@", installmentsCount, installmentsAmount)
let attributedTitle = NSAttributedString(string: titleString, attributes: PXNewCustomView.titleAttributes)
finalString.append(attributedTitle)
// Installment Rate
if installmentsRate == 0.0 {
let interestRateString = String(format: " %@", "Sin interés".localized.lowercased())
let attributedInsterest = NSAttributedString(string: interestRateString, attributes: interestRateAttributes)
finalString.appendWithSpace(attributedInsterest)
}
// Total Amount
let totalString = Utils.addParenthesis(installmentsTotalAmount)
let attributedTotal = NSAttributedString(string: totalString, attributes: totalAmountAttributes)
finalString.appendWithSpace(attributedTotal)
return finalString
}
class func textForNonInstallmentPayment(paidAmount: String) -> NSAttributedString {
return NSAttributedString(string: paidAmount, attributes: PXNewCustomView.titleAttributes)
}
class func discountMessage(_ text: String, transactionAmount: String) -> NSMutableAttributedString {
let discountString = NSMutableAttributedString()
let attributedAmount = NSAttributedString(string: transactionAmount, attributes: discountAmountAttributes)
discountString.appendWithSpace(attributedAmount)
let attributedMessage = NSAttributedString(string: text, attributes: interestRateAttributes)
discountString.appendWithSpace(attributedMessage)
return discountString
}
// PM Second String
class func formatPaymentMethodSecondString(paymentMethodName: String?, paymentMethodLastFourDigits lastFourDigits: String?, paymentType: PXPaymentTypes) -> NSAttributedString? {
guard let description = assembleSecondString(paymentMethodName: paymentMethodName ?? "", paymentMethodLastFourDigits: lastFourDigits, paymentType: paymentType) else { return nil }
return secondaryStringAttributed(description)
}
class func formatBankTransferSecondaryString(_ message: String?) -> NSAttributedString? {
guard let msg = message else { return nil }
return secondaryStringAttributed(msg)
}
class func assembleSecondString(paymentMethodName: String, paymentMethodLastFourDigits lastFourDigits: String?, paymentType: PXPaymentTypes) -> String? {
var pmDescription: String = ""
if paymentType.isCard() {
if let lastFourDigits = lastFourDigits {
pmDescription = paymentMethodName.capitalized + " " + "terminada en".localized + " " + lastFourDigits
}
} else if paymentType == PXPaymentTypes.DIGITAL_CURRENCY {
pmDescription = paymentMethodName
} else {
return nil
}
return pmDescription
}
class func secondaryStringAttributed(_ string: String) -> NSAttributedString {
return NSMutableAttributedString(string: string, attributes: PXNewCustomView.subtitleAttributes)
}
}
| mit | 9fc2908d1a8279319db3f26a125b94b4 | 43.89916 | 244 | 0.701291 | 5.177326 | false | false | false | false |
fienlute/programmeerproject | GOals/LoginViewController.swift | 1 | 4521 | //
// LoginViewController.swift
// GOals
//
// De gebruiker kan op deze viewcontroller inloggen met een bestaand account of een nieuw account aanmaken.
//
// Created by Fien Lute on 10-01-17.
// Copyright © 2017 Fien Lute. All rights reserved.
//
import UIKit
import Firebase
import FirebaseAuth
class LoginViewController: UIViewController {
// MARK: Properties
var ref: FIRDatabaseReference!
// MARK: Outlets
@IBOutlet weak var textFieldLoginEmail: UITextField!
@IBOutlet weak var textFieldLoginPassword: UITextField!
// MARK: View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
ref = FIRDatabase.database().reference(withPath: "Users")
textFieldLoginPassword.isSecureTextEntry = true
self.view.backgroundColor = UIColor(patternImage: UIImage(named: "mountainbackgroundgoals.png")!)
FIRAuth.auth()!.addStateDidChangeListener() { auth, user in
if user != nil {
print("USER: \(user)")
self.performSegue(withIdentifier: "LoginToList", sender: nil)
}
}
}
// MARK: Actions
@IBAction func loginDidTouch(_ sender: Any) {
FIRAuth.auth()!.signIn(withEmail: textFieldLoginEmail.text!,
password: textFieldLoginPassword.text!) {
(user, error) in
if error != nil {
self.errorAlert(title: "Error with loggig in", alertCase: "Enter a valid email and password.")
}
}
}
@IBAction func signupDidTouch(_ sender: AnyObject) {
let alert = UIAlertController(title: "Register",
message: "Register",
preferredStyle: .alert)
let saveAction = UIAlertAction(title: "Save",
style: .default) { action in
let emailField = alert.textFields![0]
let passwordField = alert.textFields![1]
let groupField = alert.textFields![2]
FIRAuth.auth()!.createUser(withEmail: emailField.text!,
password: passwordField.text!) { user, error in
if error == nil {
let user = User(uid: (user?.uid)!, email: emailField.text!, group: groupField.text!, points: 0)
FIRAuth.auth()!.signIn(withEmail: self.textFieldLoginEmail.text!,
password: self.textFieldLoginPassword.text!)
let userRef = self.ref.child((user.uid))
userRef.setValue(user.toAnyObject())
} else {
self.errorAlert(title: "Signup failed", alertCase: "Make sure all the fields are filled in. The password must be at least 6 characters.")
}
}
}
let cancelAction = UIAlertAction(title: "Cancel",
style: .default)
alert.addTextField { textEmail in
textEmail.placeholder = "Enter your email"
}
alert.addTextField { textPassword in
textPassword.isSecureTextEntry = true
textPassword.placeholder = "Enter your password"
}
alert.addTextField { textGroup in
textGroup.placeholder = "Add a group/Join a group"
}
alert.addAction(saveAction)
alert.addAction(cancelAction)
present(alert, animated: true, completion: nil)
}
// MARK: Functions
func errorAlert(title: String, alertCase: String) {
let alert = UIAlertController(title: title, message: alertCase , preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok!", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
extension LoginViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == textFieldLoginEmail {
textFieldLoginPassword.becomeFirstResponder()
}
if textField == textFieldLoginPassword {
textField.resignFirstResponder()
}
return true
}
}
| mit | c9d89979c98e197eec4fa2a653f12351 | 33.769231 | 157 | 0.556195 | 5.393795 | false | false | false | false |
ben-ng/swift | stdlib/public/core/StringHashable.swift | 1 | 3612 | //===----------------------------------------------------------------------===//
//
// 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 https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
#if _runtime(_ObjC)
@_silgen_name("swift_stdlib_NSStringHashValue")
func _stdlib_NSStringHashValue(_ str: AnyObject, _ isASCII: Bool) -> Int
@_silgen_name("swift_stdlib_NSStringHashValuePointer")
func _stdlib_NSStringHashValuePointer(_ str: OpaquePointer, _ isASCII: Bool) -> Int
#endif
extension _Unicode {
internal static func hashASCII(
_ string: UnsafeBufferPointer<UInt8>
) -> Int {
let collationTable = _swift_stdlib_unicode_getASCIICollationTable()
var hasher = _SipHash13Context(key: _Hashing.secretKey)
for c in string {
_precondition(c <= 127)
let element = collationTable[Int(c)]
// Ignore zero valued collation elements. They don't participate in the
// ordering relation.
if element != 0 {
hasher.append(element)
}
}
return hasher._finalizeAndReturnIntHash()
}
internal static func hashUTF16(
_ string: UnsafeBufferPointer<UInt16>
) -> Int {
let collationIterator = _swift_stdlib_unicodeCollationIterator_create(
string.baseAddress!,
UInt32(string.count))
defer { _swift_stdlib_unicodeCollationIterator_delete(collationIterator) }
var hasher = _SipHash13Context(key: _Hashing.secretKey)
while true {
var hitEnd = false
let element =
_swift_stdlib_unicodeCollationIterator_next(collationIterator, &hitEnd)
if hitEnd {
break
}
// Ignore zero valued collation elements. They don't participate in the
// ordering relation.
if element != 0 {
hasher.append(element)
}
}
return hasher._finalizeAndReturnIntHash()
}
}
extension String : Hashable {
/// The string's 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 {
#if _runtime(_ObjC)
// Mix random bits into NSString's hash so that clients don't rely on
// Swift.String.hashValue and NSString.hash being the same.
#if arch(i386) || arch(arm)
let hashOffset = Int(bitPattern: 0x88dd_cc21)
#else
let hashOffset = Int(bitPattern: 0x429b_1266_88dd_cc21)
#endif
// If we have a contiguous string then we can use the stack optimization.
let core = self._core
let isASCII = core.isASCII
if core.hasContiguousStorage {
let stackAllocated = _NSContiguousString(core)
return hashOffset ^ stackAllocated._unsafeWithNotEscapedSelfPointer {
return _stdlib_NSStringHashValuePointer($0, isASCII)
}
} else {
let cocoaString = unsafeBitCast(
self._bridgeToObjectiveCImpl(), to: _NSStringCore.self)
return hashOffset ^ _stdlib_NSStringHashValue(cocoaString, isASCII)
}
#else
if let asciiBuffer = self._core.asciiBuffer {
return _Unicode.hashASCII(UnsafeBufferPointer(
start: asciiBuffer.baseAddress!,
count: asciiBuffer.count))
} else {
return _Unicode.hashUTF16(
UnsafeBufferPointer(start: _core.startUTF16, count: _core.count))
}
#endif
}
}
| apache-2.0 | 0535aad3750ee7f29857d21164c3b464 | 33.075472 | 83 | 0.660853 | 4.388821 | false | false | false | false |
335g/TwitterAPIKit | Sources/APIs/FollowersAPI.swift | 1 | 2632 | //
// Followers.swift
// TwitterAPIKit
//
// Created by Yoshiki Kudo on 2015/07/05.
// Copyright © 2015年 Yoshiki Kudo. All rights reserved.
//
import Foundation
import APIKit
// MARK: - Request
public protocol FollowersRequestType: TwitterAPIRequestType {}
public protocol FollowersGetRequestType: FollowersRequestType {}
public extension FollowersRequestType {
public var baseURL: NSURL {
return NSURL(string: "https://api.twitter.com/1.1/followers")!
}
}
public extension FollowersGetRequestType {
public var method: APIKit.HTTPMethod {
return .GET
}
}
// MARK: - API
public enum TwitterFollowers {
///
/// https://dev.twitter.com/rest/reference/get/followers/ids
///
public struct Ids: FollowersGetRequestType {
public let client: OAuthAPIClient
public var path: String {
return "/ids.json"
}
private let _parameters: [String: AnyObject?]
public var parameters: AnyObject? {
return queryStringsFromParameters(_parameters)
}
public init(
_ client: OAuthAPIClient,
user: User,
count: Int = 5000,
cursorStr: String = "-1",
stringifyIds: Bool = true){
self.client = client
self._parameters = [
user.key: user.obj,
"cursor": cursorStr,
"stringify_ids": stringifyIds,
"count": count
]
}
public func responseFromObject(object: AnyObject, URLResponse: NSHTTPURLResponse) throws -> UserIDs {
guard let
dictionary = object as? [String: AnyObject],
ids = UserIDs(dictionary: dictionary) else {
throw DecodeError.Fail
}
return ids
}
}
///
/// https://dev.twitter.com/rest/reference/get/friends/list
///
public struct List: FollowersGetRequestType {
public let client: OAuthAPIClient
public var path: String {
return "/list.json"
}
private let _parameters: [String: AnyObject?]
public var parameters: AnyObject? {
return queryStringsFromParameters(_parameters)
}
public init(
_ client: OAuthAPIClient,
user: User,
count: Int = 50,
cursorStr: String = "-1",
skipStatus: Bool = true,
includeUserEntities: Bool = false){
self.client = client
self._parameters = [
user.key: user.obj,
"cursor": cursorStr,
"count": count,
"skip_status": skipStatus,
"include_user_entities": includeUserEntities
]
}
public func responseFromObject(object: AnyObject, URLResponse: NSHTTPURLResponse) throws -> UsersList {
guard let
dictionary = object as? [String: AnyObject],
list = UsersList(dictionary: dictionary) else {
throw DecodeError.Fail
}
return list
}
}
}
| mit | 84da457db081e7028a0cb7c09ed43d96 | 21.092437 | 105 | 0.670217 | 3.702817 | false | false | false | false |
ChaosCoder/Fluency | Fluency/Process.swift | 1 | 1165 | import Foundation
class Process : NSObject
{
var rootTask : Task!
var successClosure : ((Any?) -> ())!
var failureClosure : ((NSError?) -> ())!
var successTask : Task {
return ClosureTask(title: "SUCCESS", voidClosure: { (result : Any?) -> () in
self.successClosure(result)
})
}
var failureTask : Task {
return ClosureTask(title: "FAILURE", voidClosure: { (result : Any?) -> () in
self.failureClosure(result as? NSError)
})
}
convenience init(task : Task)
{
self.init()
self.rootTask = task
}
func execute()
{
execute(nil)
}
func execute(input : Any?)
{
let context = Context(process: self, task: nil, result: input)
rootTask.start(context)
}
func className() -> String
{
let classString : String = NSStringFromClass(self.classForCoder)
return classString.componentsSeparatedByString(".").last!
}
func unhandledFailure(task : Task, error : NSError, context : Context)
{
failureTask.start(context)
}
func plantUML() -> String
{
var code = "@startuml\n"
code += "title \(self.className())\n"
code += "(*) --> " + rootTask.plantUML([])
code += "@enduml\n"
return code
}
} | mit | 206d3993a7aea4f8e896c13f08f17dca | 17.806452 | 78 | 0.634335 | 3.218232 | false | false | false | false |
avito-tech/Paparazzo | Paparazzo/Core/VIPER/ImageCropping/Interactor/ImageCroppingParameters.swift | 1 | 1320 | import CoreGraphics
import ImageSource
struct ImageCroppingParameters: Equatable {
let transform: CGAffineTransform
let sourceSize: CGSize
let sourceOrientation: ExifOrientation
let outputWidth: CGFloat
let cropSize: CGSize
let imageViewSize: CGSize
let contentOffsetCenter: CGPoint
let turnAngle: CGFloat
let tiltAngle: CGFloat
let zoomScale: CGFloat
let manuallyZoomed: Bool
static func ==(parameters1: ImageCroppingParameters, parameters2: ImageCroppingParameters) -> Bool {
return parameters1.transform == parameters2.transform &&
parameters1.sourceSize == parameters2.sourceSize &&
parameters1.sourceOrientation == parameters2.sourceOrientation &&
parameters1.outputWidth == parameters2.outputWidth &&
parameters1.cropSize == parameters2.cropSize &&
parameters1.imageViewSize == parameters2.imageViewSize &&
parameters1.contentOffsetCenter == parameters2.contentOffsetCenter &&
parameters1.turnAngle == parameters2.turnAngle &&
parameters1.tiltAngle == parameters2.tiltAngle &&
parameters1.zoomScale == parameters2.zoomScale &&
parameters1.manuallyZoomed == parameters2.manuallyZoomed
}
}
| mit | 74927aa0f27bf89cb42b37adb729579d | 40.25 | 104 | 0.688636 | 5.59322 | false | false | false | false |
tmandry/Swindler | SwindlerTests/support/ExpectationHelpers.swift | 1 | 2821 | import Foundation
import Quick
import Nimble
import PromiseKit
func waitUntil(_ expression: @autoclosure @escaping () throws -> Bool,
file: FileString = #file,
line: UInt = #line) {
expect(try expression(), file: file, line: line).toEventually(beTrue())
}
func waitFor<T>(_ expression: @autoclosure @escaping () throws -> T?,
file: FileString = #file,
line: UInt = #line) -> T? {
expect(try expression(), file: file, line: line).toEventuallyNot(beNil())
do {
let result = try expression()
return result!
} catch {
fail("Error thrown while retrieving value: \(error)")
return nil
}
}
func it<T>(_ desc: String,
timeout: TimeInterval = 1.0,
failOnError: Bool = true,
file: FileString = #file,
line: UInt = #line,
closure: @escaping () -> Promise<T>) {
it(desc, file: file, line: line, closure: {
let promise = closure()
waitUntil(timeout: timeout, file: file, line: line) { done in
promise.done { _ in
done()
}.catch { error in
if failOnError {
fail("Promise failed with error \(error)", file: file, line: line)
}
done()
}
}
} as () -> Void)
}
func expectToSucceed<T>(_ promise: Promise<T>, file: FileString = #file, line: UInt = #line)
-> Promise<Void> {
return promise.asVoid().recover { (error: Error) -> Void in
fail("Expected promise to succeed, but failed with \(error)", file: file, line: line)
}
}
func expectToFail<T>(_ promise: Promise<T>, file: FileString = #file, line: UInt = #line)
-> Promise<Void> {
return promise.asVoid().done {
fail("Expected promise to fail, but succeeded", file: file, line: line)
}.recover { (error: Error) -> Promise<Void> in
expect(file, line: line, expression: { throw error }).to(throwError())
return Promise.value(())
}
}
func expectToFail<T, E: Error>(_ promise: Promise<T>,
with expectedError: E,
file: FileString = #file,
line: UInt = #line) -> Promise<Void> {
return promise.asVoid().done {
fail("Expected promise to fail with error \(expectedError), but succeeded",
file: file, line: line)
}.recover { (error: Error) -> Void in
expect(file, line: line, expression: { throw error }).to(throwError(expectedError))
}
}
/// Convenience struct for when errors need to be thrown from tests to abort execution (e.g. during
/// a promise chain).
struct TestError: Error {
let description: String
init(_ description: String) { self.description = description }
}
| mit | d9cfc2397ce94040bd0ed9648a872288 | 34.2625 | 99 | 0.56682 | 4.248494 | false | false | false | false |
daniel-hall/Stylish | StylishExample/StylishExample/Aqua.swift | 1 | 5748 | //
// Aqua.swift
// StylishExample
//
// Copyright (c) 2016 Daniel Hall
// Twitter: @_danielhall
// GitHub: https://github.com/daniel-hall
// Website: http://danielhall.io
//
// 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 Stylish
import UIKit
// 1. To define a Stylesheet, create a new type that conforms to the Stylesheet protocol
class Aqua : Stylesheet {
// 2. The protocol requires that you create a styles dictionary that defines a mapping of style names to style instances
let styles: [String : Style] = [
"PrimaryBackgroundColor": PrimaryBackgroundColor(),
"SecondaryBackgroundColor": SecondaryBackgroundColor(),
"HeaderText": HeaderText(),
"BodyText": BodyText(),
"ThemeDescription": ThemeDescription(),
"DefaultProgressBar": DefaultProgressBar(),
"DefaultButton": DefaultButton(),
"StylesheetTitle": StylesheetTitle(),
"ThemeImage": ThemeImage(),
"Rounded": RoundedStyle(), // This style is defined in a separate file (SharedStyles.swift) for easy reuse in multiple stylesheets
"HighlightedText": HighlightedTextStyle() // This style is defined in a separate file (SharedStyles.swift) for easy reuse in multiple stylesheets
]
// 3. Here are the specific, nested Style types defined for this Stylesheet. They can be made private, or left internal as below, to allow other Stylesheets to resuse them with their full type identifiers, e.g. 'Aqua.PrimaryBackgroundColor'
struct PrimaryBackgroundColor : Style {
var propertyStylers = [backgroundColor.set(value: UIColor(red:0.18, green:0.51, blue:0.72, alpha:1.0))]
}
struct SecondaryBackgroundColor : Style {
var propertyStylers = [backgroundColor.set(value: UIColor(red:0.23, green:0.60, blue:0.85, alpha:1.0))]
}
struct HeaderText : Style {
var propertyStylers = [
font.set(value: UIFont(name: "Futura-Medium", size: 20.0)),
textColor.set(value: .white),
textAlignment.set(value: .center)
]
}
struct BodyText : Style {
var propertyStylers = [
font.set(value: UIFont(name: "Futura-Medium", size: 16.0)),
textColor.set(value: .white),
textAlignment.set(value: .justified)
]
}
struct ThemeDescription : Style {
var propertyStylers = [text.set(value: "This Aqua theme shows off some additional capabilities. There are rounded corners on elements, and the progress bar has a complex pattern color defined in the style. Even this text is part of a style, and not coded into a view controller or model.")]
}
struct DefaultProgressBar : Style {
private static var patternColor: UIColor {
let context = CIContext()
let stripesFilter = CIFilter(name: "CIStripesGenerator", parameters: ["inputColor0" : CIColor(color: UIColor(red:0.25, green:0.80, blue:0.99, alpha:1.0)), "inputColor1" : CIColor(color: UIColor(red:0.60, green:0.89, blue:0.99, alpha:1.0)), "inputWidth" : 4])!
let stripes = context.createCGImage(stripesFilter.outputImage!, from: CGRect(origin: CGPoint.zero, size: CGSize(width: 32.0, height: 32.0)))
let rotateFilter = CIFilter(name: "CIStraightenFilter", parameters: ["inputImage" : CIImage(cgImage: stripes!), "inputAngle" : 2.35])!
let rotated = context.createCGImage(rotateFilter.outputImage!, from: rotateFilter.outputImage!.extent)
return UIColor(patternImage: UIImage(cgImage: rotated!))
}
var propertyStylers = [
progressColor.set(value: patternColor),
progressTrackColor.set(value: .white),
progressCornerRadiusRatio.set(value: 0.55),
cornerRadiusRatio.set(value: 0.55),
borderWidth.set(value: 2.0),
borderColor.set(value: UIColor(red:0.25, green:0.80, blue:0.99, alpha:1.0))
]
}
struct DefaultButton : Style {
var propertyStylers = [
titleColorForNormalState.set(value: .white),
titleColorForHighlightedState.set(value: UIColor(red:0.60, green:0.89, blue:0.99, alpha:1.0)),
cornerRadiusRatio.set(value: 0.5),
borderColor.set(value: UIColor(red:0.60, green:0.89, blue:0.99, alpha:1.0)),
backgroundColor.set(value: UIColor(red:0.25, green:0.80, blue:0.99, alpha:1.0))
]
}
struct StylesheetTitle : Style {
var propertyStylers = [text.set(value: "Aqua")]
}
struct ThemeImage : Style {
var propertyStylers = [image.set(value: UIImage(named: "water", in: Bundle(for: ProgressBar.self), compatibleWith: nil))]
}
}
| mit | 5ba16f599eba8cd4bd6a6555be21bd6c | 46.9 | 298 | 0.674669 | 4.186453 | false | false | false | false |
tkremenek/swift | benchmark/single-source/ArraySetElement.swift | 20 | 1244 | //===--- ArraySetElement.swift ---------------------------------------------===//
//
// 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 TestsUtils
// 33% isUniquelyReferenced
// 15% swift_rt_swift_isUniquelyReferencedOrPinned_nonNull_native
// 18% swift_isUniquelyReferencedOrPinned_nonNull_native
public let ArraySetElement = BenchmarkInfo(
name: "ArraySetElement",
runFunction: run_ArraySetElement,
tags: [.runtime, .cpubench]
)
// This is an effort to defeat isUniquelyReferenced optimization. Ideally
// microbenchmarks list this should be written in C.
@inline(never)
func storeArrayElement(_ array: inout [Int], _ i: Int) {
array[i] = i
}
public func run_ArraySetElement(_ N: Int) {
var array = [Int](repeating: 0, count: 10000)
for _ in 0..<10*N {
for i in 0..<array.count {
storeArrayElement(&array, i)
}
}
}
| apache-2.0 | 404910bcc5634d95d37b8bd74951fcde | 31.736842 | 81 | 0.643891 | 4.319444 | false | false | false | false |
pjcau/LocalNotifications_Over_iOS10 | Pods/SwiftDate/Sources/SwiftDate/Commons.swift | 2 | 8783 | // SwiftDate
// Manage Date/Time & Timezone in Swift
//
// Created by: Daniele Margutti
// Email: <[email protected]>
// Web: <http://www.danielemargutti.com>
//
// Licensed under MIT License.
import Foundation
internal extension Calendar.Component {
/// Return the localized identifier of a calendar component
///
/// - parameter unit: unit
/// - parameter value: value
///
/// - returns: return the plural or singular form of the time unit used to compose a valid identifier for search a localized
/// string in resource bundle
internal func localizedKey(forValue value: Int) -> String {
let locKey = self.localizedKey
let absValue = abs(value)
switch absValue {
case 0: // zero difference for this unit
return "0\(locKey)"
case 1: // one unit of difference
return locKey
default: // more than 1 unit of difference
return "\(locKey)\(locKey)"
}
}
internal var localizedKey: String {
switch self {
case .year: return "y"
case .month: return "m"
case .weekOfYear: return "w"
case .day: return "d"
case .hour: return "h"
case .minute: return "M"
case .second: return "s"
default:
return ""
}
}
}
/// Time interval reference
///
/// - start: start of the specified component
/// - end: end of the specified component
/// - auto: value is the result of the operation
public enum TimeReference {
case start
case end
case auto
}
/// Rounding mode of the interval
///
/// - round: round
/// - ceil: ceil
/// - floor: floor
public enum IntervalRoundingType {
case round
case ceil
case floor
}
public enum IntervalType {
case seconds(_: Int)
case minutes(_: Int)
internal var seconds: TimeInterval {
switch self {
case .seconds(let secs): return TimeInterval(secs)
case .minutes(let mins): return TimeInterval(mins * 60)
}
}
}
/// This define the weekdays
///
/// - sunday: sunday
/// - monday: monday
/// - tuesday: tuesday
/// - wednesday: wednesday
/// - thursday: thursday
/// - friday: friday
/// - saturday: saturday
public enum WeekDay: Int {
case sunday = 1
case monday = 2
case tuesday = 3
case wednesday = 4
case thursday = 5
case friday = 6
case saturday = 7
}
/// Provide a mechanism to create and return local-thread object you can share.
///
/// Basically you assign a key to the object and return the initializated instance in `create`
/// block. Again this code is used internally to provide a common way to create local-thread date
/// formatter as like `NSDateFormatter` (which is expensive to create) or
/// `NSDateComponentsFormatter`.
/// Instance is saved automatically into current thread own dictionary.
///
/// - parameter key: identification string of the object
/// - parameter create: creation block. At the end of the block you need to provide the instance you
/// want to save.
///
/// - returns: the instance you have created into the current thread
internal func localThreadSingleton<T: AnyObject>(key: String, create: () -> T) -> T {
if let cachedObj = Thread.current.threadDictionary[key] as? T {
return cachedObj
} else {
let newObject = create()
Thread.current .threadDictionary[key] = newObject
return newObject
}
}
/// This is the list of all possible errors you can get from the library
///
/// - FailedToParse: Failed to parse a specific date using provided format
/// - FailedToCalculate: Failed to calculate new date from passed parameters
/// - MissingCalTzOrLoc: Provided components does not include a valid TimeZone or Locale
/// - DifferentCalendar: Provided dates are expressed in different calendars and cannot be compared
/// - MissingRsrcBundle: Missing SwiftDate resource bundle
/// - FailedToSetComponent: Failed to set a calendar com
public enum DateError: Error {
case FailedToParse
case FailedToCalculate
case MissingCalTzOrLoc
case DifferentCalendar
case MissingRsrcBundle
case FailedToSetComponent(Calendar.Component)
case InvalidLocalizationFile
}
/// Available date formats used to parse strings and format date into string
///
/// - custom: custom format expressed in Unicode tr35-31 (see http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns and Apple's Date Formatting Guide). Formatter uses heuristics to guess the date if it's invalid.
/// This may end in a wrong parsed date. Use `strict` to disable heuristics parsing.
/// - strict: strict format is like custom but does not apply heuristics to guess at the date which is intended by the string.
/// So, if you pass an invalid date (like 1999-02-31) formatter fails instead of returning guessing date (in our case
/// 1999-03-03).
/// - iso8601: ISO8601 date format (see https://en.wikipedia.org/wiki/ISO_8601).
/// - iso8601Auto: ISO8601 date format. You should use it to parse a date (parsers evaluate automatically the format of
/// the ISO8601 string). Passed as options to transform a date to string it's equal to [.withInternetDateTime] options.
/// - extended: extended date format ("eee dd-MMM-yyyy GG HH:mm:ss.SSS zzz")
/// - rss: RSS and AltRSS date format
/// - dotNET: .NET date format
public enum DateFormat {
case custom(String)
case strict(String)
case iso8601(options: ISO8601DateTimeFormatter.Options)
case iso8601Auto
case extended
case rss(alt: Bool)
case dotNET
}
/// This struct group the options you can choose to output a string which represent
/// the interval between two dates.
public struct ComponentsFormatterOptions {
/// The default formatting behavior. When using positional units, this behavior drops leading zeroes but pads middle and trailing values with zeros as needed. For example, with hours, minutes, and seconds displayed, the value for one hour and 10 seconds is “1:00:10”. For all other unit styles, this behavior drops all units whose values are 0. For example, when days, hours, minutes, and seconds are allowed, the abbreviated version of one hour and 10 seconds is displayed as “1h 10s”.*
public var zeroBehavior: DateComponentsFormatter.ZeroFormattingBehavior = .pad
// The maximum number of time units to include in the output string.
// By default is nil, which does not cause the elimination of any units.
public var maxUnitCount: Int? = nil
// Configures the strings to use (if any) for unit names such as days, hours, minutes, and seconds.
// By default is `positional`.
public var style: DateComponentsFormatter.UnitsStyle = .positional
// Setting this property to true results in output strings like “30 minutes remaining”. The default value of this property is false.
public var includeTimeRemaining: Bool = false
/// The bitmask of calendrical units such as day and month to include in the output string
/// Allowed components are: `year,month,weekOfMonth,day,hour,minute,second`.
/// By default it's set as nil which means set automatically based upon the interval.
public var allowedUnits: NSCalendar.Unit? = nil
/// The locale to use to format the string.
/// If `ComponentsFormatterOptions` is used from a `TimeInterval` object the default value
/// value is set to the current device's locale.
/// If `ComponentsFormatterOptions` is used from a `DateInRegion` object the default value
/// is set the `DateInRegion`'s locale.
public var locale: Locale = LocaleName.current.locale
/// Initialize a new ComponentsFormatterOptions struct
/// - parameter allowedUnits: allowed units or nil if you want to keep the default value
/// - parameter style: units style or nil if you want to keep the default value
/// - parameter zero: zero behavior or nil if you want to keep the default value
public init(allowedUnits: NSCalendar.Unit? = nil, style: DateComponentsFormatter.UnitsStyle? = nil, zero: DateComponentsFormatter.ZeroFormattingBehavior? = nil) {
if allowedUnits != nil { self.allowedUnits = allowedUnits! }
if style != nil { self.style = style! }
if zero != nil { self.zeroBehavior = zero! }
}
/// Evaluate the best allowed units to workaround NSException of the DateComponentsFormatter
internal func bestAllowedUnits(forInterval interval: TimeInterval) -> NSCalendar.Unit {
switch interval {
case 0...(SECONDS_IN_MINUTE-1):
return [.second]
case SECONDS_IN_MINUTE...(SECONDS_IN_HOUR-1):
return [.minute,.second]
case SECONDS_IN_HOUR...(SECONDS_IN_DAY-1):
return [.hour,.minute,.second]
case SECONDS_IN_DAY...(SECONDS_IN_WEEK-1):
return [.day,.hour,.minute,.second]
default:
return [.year,.month,.weekOfMonth,.day,.hour,.minute,.second]
}
}
}
internal let SECONDS_IN_MINUTE: TimeInterval = 60
internal let SECONDS_IN_HOUR: TimeInterval = SECONDS_IN_MINUTE * 60
internal let SECONDS_IN_DAY: TimeInterval = SECONDS_IN_HOUR * 24
internal let SECONDS_IN_WEEK: TimeInterval = SECONDS_IN_DAY * 7
| mit | 765db8d1bed4b379f0455a0bea16e85e | 36.969697 | 488 | 0.728651 | 3.89649 | false | false | false | false |
joerocca/GitHawk | Classes/Models/RepositoryLabel.swift | 1 | 713 | //
// Label.swift
// Freetime
//
// Created by Ryan Nystrom on 6/2/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import Foundation
import IGListKit
final class RepositoryLabel: ListDiffable {
let color: String
let name: String
init(color: String, name: String) {
self.color = color
self.name = name
}
// MARK: ListDiffable
func diffIdentifier() -> NSObjectProtocol {
return name as NSObjectProtocol
}
func isEqual(toDiffableObject object: ListDiffable?) -> Bool {
if self === object { return true }
guard let object = object as? RepositoryLabel else { return false }
return color == object.color
}
}
| mit | 5efc8c2036b3cc201d3cbef7517d0e56 | 19.941176 | 75 | 0.63764 | 4.395062 | false | false | false | false |
Evgeniy-Odesskiy/Bond | Bond/iOS/Bond+UISegmentedControl.swift | 1 | 3352 | //
// Bond+UISegmentedControl.swift
// Bond
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Austin Cooley (@adcooley)
//
// 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
class SegmentedControlDynamicHelper
{
weak var control: UISegmentedControl?
var listener: (UIControlEvents -> Void)?
init(control: UISegmentedControl) {
self.control = control
control.addTarget(self, action: Selector("valueChanged:"), forControlEvents: UIControlEvents.ValueChanged)
}
dynamic func valueChanged(control: UISegmentedControl) {
self.listener?(.ValueChanged)
}
deinit {
control?.removeTarget(self, action: nil, forControlEvents: .AllEvents)
}
}
class SegmentedControlDynamic<T>: InternalDynamic<UIControlEvents>
{
let helper: SegmentedControlDynamicHelper
init(control: UISegmentedControl) {
self.helper = SegmentedControlDynamicHelper(control: control)
super.init()
self.helper.listener = { [unowned self] in
self.value = $0
}
}
}
private var eventDynamicHandleUISegmentedControl: UInt8 = 0;
extension UISegmentedControl /*: Dynamical, Bondable */ {
public var dynEvent: Dynamic<UIControlEvents> {
if let d: AnyObject = objc_getAssociatedObject(self, &eventDynamicHandleUISegmentedControl) {
return (d as? Dynamic<UIControlEvents>)!
} else {
let d = SegmentedControlDynamic<UIControlEvents>(control: self)
objc_setAssociatedObject(self, &eventDynamicHandleUISegmentedControl, d, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return d
}
}
public var designatedDynamic: Dynamic<UIControlEvents> {
return self.dynEvent
}
public var designatedBond: Bond<UIControlEvents> {
return self.dynEvent.valueBond
}
}
public func ->> (left: UISegmentedControl, right: Bond<UIControlEvents>) {
left.designatedDynamic ->> right
}
public func ->> <U: Bondable where U.BondType == UIControlEvents>(left: UISegmentedControl, right: U) {
left.designatedDynamic ->> right.designatedBond
}
public func ->> <T: Dynamical where T.DynamicType == UIControlEvents>(left: T, right: UISegmentedControl) {
left.designatedDynamic ->> right.designatedBond
}
public func ->> (left: Dynamic<UIControlEvents>, right: UISegmentedControl) {
left ->> right.designatedBond
}
| mit | eb768e37ebd6b71258bbc0d0fb1c9c0f | 32.188119 | 136 | 0.73747 | 4.523617 | false | false | false | false |
ptiz/bender | Bender/ObjectRule.swift | 1 | 21324 | //
// ObjectRule.swift
// Bender
//
// Created by Evgenii Kamyshanov on 07.12.16.
// Original work Copyright © 2016 Evgenii Kamyshanov
// Modified work Copyright © 2016 Sviatoslav Bulgakov, Anton Davydov
//
// The MIT License (MIT)
//
// 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
/**
Validator for compound types: classes or structs. Validates JSON struct for particular type T,
which is passed by value of type RefT.
*/
open class ObjectRule<T, RefT>: Rule {
public typealias V = T
fileprivate typealias LateBindClosure = (RefT) -> Void
fileprivate typealias RuleClosure = (Any) throws -> LateBindClosure?
fileprivate typealias OptionalRuleClosure = (Any?) throws -> LateBindClosure?
fileprivate typealias RequirementClosure = (Any) throws -> Bool
fileprivate typealias DumpRuleClosure = (T) throws -> Any
fileprivate typealias DumpOptionalRuleClosure = (T) throws -> Any?
fileprivate var pathRequirements = [(JSONPath, RequirementClosure)]()
fileprivate var pathMandatoryRules = [(JSONPath, RuleClosure)]()
fileprivate var pathOptionalRules = [(JSONPath, OptionalRuleClosure)]()
fileprivate var mandatoryDumpRules = [(JSONPath, DumpRuleClosure)]()
fileprivate var optionalDumpRules = [(JSONPath, DumpOptionalRuleClosure)]()
fileprivate let objectFactory: ()->RefT
/**
Validator initializer
- parameter factory: autoclosure for allocating object, which returns reference to object of generic type T
*/
public init(_ objectFactory: @autoclosure @escaping ()->RefT) {
self.objectFactory = objectFactory
}
/**
Methoid for declaring requirement for input data, which must be met. Did not cause creation of a new bind item.
Throws if the requirement was not met. No binding is possible while checking requirement.
- parameter name: string name if the filed which value is checked
- parameter rule: rule that should validate the value of the field
- parameter requirement: closure, that receives unmutable validated field value to be checked and returns true if requiremet was met and false otherwise.
- returns: returns self for field declaration chaining
*/
open func required<R: Rule>(_ path: JSONPath, _ rule: R, requirement: @escaping (R.V)->Bool) -> Self {
pathRequirements.append((path, { requirement(try rule.validate($0)) }))
return self
}
/**
Method for declaring mandatory field expected in a JSON dictionary. If the field is not found during validation,
an error will be thrown.
- parameter name: string name of the field
- parameter rule: rule that should validate the value of the field
- parameter bind: bind closure, that receives reference to object of generic parameter type as a first argument and validated field value as a second one
- returns: returns self for field declaration chaining
*/
open func expect<R: Rule>(_ path: JSONPath, _ rule: R, _ bind: @escaping (RefT, R.V)->Void) -> Self {
pathMandatoryRules.append((path, storeRule(rule, bind)))
return self
}
/**
Method for declaring mandatory field expected in a JSON dictionary. If the field is not found during validation,
an error will be thrown.
- parameter name: string name of the field
- parameter rule: rule that should validate the value of the field
- parameter bind: optional bind closure, that receives reference to object of generic parameter type as a first argument and validated field value as a second one
- parameter dump: closure used for dump, receives immutable object of type T and may return optional value of validated field type
- returns: returns self for field declaration chaining
*/
open func expect<R: Rule>(_ path: JSONPath, _ rule: R, _ bind: @escaping (RefT, R.V)->Void, dump: @escaping (T)->R.V?) -> Self {
pathMandatoryRules.append((path, storeRule(rule, bind)))
mandatoryDumpRules.append((path, storeDumpRuleForseNull(rule, dump)))
return self
}
/**
Method for declaring mandatory field expected in a JSON dictionary. If the field is not found during validation,
an error will be thrown.
- parameter name: string name of the field
- parameter rule: rule that should validate the value of the field
- parameter bind: optional bind closure, that receives reference to object of generic parameter type as a first argument and validated field value as a second one
- parameter dump: closure used for dump, receives immutable object of type T and should return value of validated field type
- returns: returns self for field declaration chaining
*/
open func expect<R: Rule>(_ path: JSONPath, _ rule: R, _ bind: @escaping (RefT, R.V)->Void, dump: @escaping (T)->R.V) -> Self {
pathMandatoryRules.append((path, storeRule(rule, bind)))
mandatoryDumpRules.append((path, storeDumpRule(rule, dump)))
return self
}
/**
Method for declaring mandatory field expected in a JSON dictionary. If the field is not found during validation,
an error will be thrown.
- parameter name: string name of the field
- parameter rule: rule that should validate the value of the field
- parameter dump: closure used for dump, receives immutable object of type T and may return optional value of validated field type
- returns: returns self for field declaration chaining
*/
open func expect<R: Rule>(_ path: JSONPath, _ rule: R, dump: @escaping (T)->R.V?) -> Self {
mandatoryDumpRules.append((path, storeDumpRuleForseNull(rule, dump)))
return self
}
/**
Method for declaring mandatory field expected in a JSON dictionary. If the field is not found during validation,
an error will be thrown.
- parameter name: string name of the field
- parameter rule: rule that should validate the value of the field
- parameter dump: closure used for dump, receives immutable object of type T and should return value of validated field type
- returns: returns self for field declaration chaining
*/
open func expect<R: Rule>(_ path: JSONPath, _ rule: R, dump: @escaping (T)->R.V) -> Self {
mandatoryDumpRules.append((path, storeDumpRule(rule, dump)))
return self
}
/**
Method for declaring optional field that may be found in a JSON dictionary. If the field is not found during validation,
nothing happens.
- parameter name: string name of the field
- parameter rule: rule that should validate the value of the field
- parameter ifNotFound: optional value of field type, i.e. R.V. It is being returned if provided in case if the
JSON field value is not found or is 'null'.
- parameter bind: optional bind closure, that receives reference to object of generic parameter type as a first argument and validated field value as a second one
- returns: returns self for field declaration chaining
*/
open func optional<R: Rule>(_ path: JSONPath, _ rule: R, ifNotFound: R.V? = nil, _ bind: @escaping (RefT, R.V)->Void) -> Self {
pathOptionalRules.append((path, storeOptionalRule(rule, ifNotFound, bind)))
return self
}
/**
Method for declaring optional field that may be found in a JSON dictionary. If the field is not found during validation,
nothing happens.
- parameter name: string name of the field
- parameter rule: rule that should validate the value of the field
- parameter ifNotFound: optional value of field type, i.e. R.V. It is being returned if provided in case if the
JSON field value is not found or is 'null'.
- parameter bind: optional bind closure, that receives reference to object of generic parameter type as a first argument and validated field value as a second one
- parameter dump: closure used for dump, receives immutable object of type T and should return value of validated field type
- returns: returns self for field declaration chaining
*/
open func optional<R: Rule>(_ path: JSONPath, _ rule: R, ifNotFound: R.V? = nil, _ bind: @escaping (RefT, R.V)->Void, dump: @escaping (T)->R.V?) -> Self {
pathOptionalRules.append((path, storeOptionalRule(rule, ifNotFound, bind)))
optionalDumpRules.append((path, storeDumpRule(rule, dump)))
return self
}
/**
Method for declaring optional field that may be found in a JSON dictionary. If the field is not found during validation,
nothing happens.
- parameter name: string name of the field
- parameter rule: rule that should validate the value of the field
- parameter dump: closure used for dump, receives immutable object of type T and may return optional value of R.V field type
- returns: returns self for field declaration chaining
*/
open func optional<R: Rule>(_ path: JSONPath, _ rule: R, dump: @escaping (T)->R.V?) -> Self {
optionalDumpRules.append((path, storeDumpRule(rule, dump)))
return self
}
/**
Method for declaring optional field that may be found in a JSON dictionary. If value not found in struct, bind will be called with 'nil'.
- parameter name: string name of the field
- parameter rule: rule that should validate the value of the field
- parameter bind: optional bind closure, that receives reference to object of generic parameter type as a first argument and validated field value as a second one
- returns: returns self for field declaration chaining
*/
open func forceOptional<R: Rule>(_ path: JSONPath, _ rule: R, _ bind: @escaping (RefT, R.V?)->Void) -> Self {
pathOptionalRules.append((path, storeForceOptionalRule(rule, bind)))
return self
}
/**
Method for declaring optional field that may be found in a JSON dictionary. If value not found in struct, bind and dump will be called with 'nil'.
- parameter name: string name of the field
- parameter rule: rule that should validate the value of the field
- parameter bind: optional bind closure, that receives reference to object of generic parameter type as a first argument and validated field value as a second one
- parameter dump: closure used for dump, receives immutable object of type T and should return value of validated field type
- returns: returns self for field declaration chaining
*/
open func forceOptional<R: Rule>(_ path: JSONPath, _ rule: R, _ bind: @escaping (RefT, R.V?)->Void, dump: @escaping (T)->R.V?) -> Self {
pathOptionalRules.append((path, storeForceOptionalRule(rule, bind)))
optionalDumpRules.append((path, storeDumpRuleForseNull(rule, dump)))
return self
}
/**
Method for declaring optional field that may be found in a JSON dictionary. If the field is not found during validation,
dump will be called with nil.
- parameter name: string name of the field
- parameter rule: rule that should validate the value of the field
- parameter dump: closure used for dump, receives immutable object of type T and may return optional value of R.V field type
- returns: returns self for field declaration chaining
*/
open func forceOptional<R: Rule>(_ path: JSONPath, _ rule: R, dump: @escaping (T)->R.V?) -> Self {
optionalDumpRules.append((path, storeDumpRuleForseNull(rule, dump)))
return self
}
/**
Validates JSON dictionary and returns T value if succeeded. Validation throws if jsonValue is not a JSON dictionary or if any nested rule throws. Object of type T will not be created if the validation fails.
- parameter jsonValue: JSON dictionary to be validated and converted into T
- throws: throws RuleError
- returns: object of generic parameter argument if validation was successful
*/
open func validate(_ jsonValue: Any) throws -> T {
guard let json = jsonValue as? NSDictionary else {
throw RuleError.invalidJSONType("Value of unexpected type found: \"\(jsonValue)\". Expected dictionary \(T.self).", nil)
}
try validateRequirements(json)
let mandatoryBindings = try validateMandatoryRules(json)
let optionalBindings = try validateOptionalRules(json)
let newStruct = objectFactory()
for binding in mandatoryBindings + optionalBindings {
binding(newStruct)
}
return value(newStruct)
}
/**
Dumps compund object of type T to [String: AnyObject] dictionary. Throws in case if any nested rule does.
- parameter value: compund value of type T
- throws: throws RuleError
- returns: [String: AnyObject] dictionary
*/
open func dump(_ value: T) throws -> Any {
var dictionary = [String: Any]()
try dumpMandatoryRules(value, dictionary: &dictionary)
try dumpOptionalRules(value, dictionary: &dictionary)
return dictionary
}
/**
Functions that unboxes reference to generic parameter and returns object of type T
- parameter newStruct: reference to generic parameter T
- returns: object of generic parameter T
*/
func value(_ newStruct: RefT) -> T {
return newStruct as! T
}
//MARK: - implementation
fileprivate func storeRule<R: Rule>(_ rule: R, _ bind: ((RefT, R.V)->Void)? = nil) -> RuleClosure {
return { (json) in
let v = try rule.validate(json)
if let b = bind {
return { b($0, v) }
}
return nil
}
}
fileprivate func storeForceOptionalRule<R: Rule>(_ rule: R, _ bind: ((RefT, R.V?)->Void)?) -> OptionalRuleClosure {
return { (optionalJson) in
guard let json = optionalJson, !(json is NSNull) else {
if let b = bind {
return { b($0, nil) }
}
return nil
}
let v = try rule.validate(json)
if let b = bind {
return { b($0, v) }
}
return nil
}
}
fileprivate func storeOptionalRule<R: Rule>(_ rule: R, _ ifNotFound: R.V?, _ bind: ((RefT, R.V)->Void)?) -> OptionalRuleClosure {
return { (optionalJson) in
guard let json = optionalJson, !(json is NSNull) else {
if let v = ifNotFound, let b = bind {
return { b($0, v) }
}
return nil
}
let v = try rule.validate(json)
if let b = bind {
return { b($0, v) }
}
return nil
}
}
fileprivate func storeDumpRule<R: Rule>(_ rule: R, _ dump: @escaping (T)->R.V) -> DumpRuleClosure {
return { struc in return try rule.dump(dump(struc)) }
}
fileprivate func storeDumpRuleForseNull<R: Rule>(_ rule: R, _ dump: @escaping (T)->R.V?) -> DumpRuleClosure {
return { struc in
if let v = dump(struc) {
return try rule.dump(v)
}
return NSNull()
}
}
fileprivate func storeDumpRule<R: Rule>(_ rule: R, _ dump: @escaping (T)->R.V?) -> DumpOptionalRuleClosure {
return { struc in
if let v = dump(struc) {
return try rule.dump(v)
}
return nil
}
}
fileprivate func validateRequirements(_ json: NSDictionary) throws {
for (path, rule) in pathRequirements {
try autoreleasepool {
guard let value = getInDictionary(json, atPath: path) else {
throw RuleError.expectedNotFound("Unable to check the requirement, field \"\(path)\" not found in struct.", nil)
}
do {
if !(try rule(value)) {
throw RuleError.unmetRequirement("Requirement was not met for field \"\(path)\" with value \"\(value)\"", nil)
}
} catch let err as RuleError {
switch err {
case .unmetRequirement: throw err
default:
throw RuleError.unmetRequirement("Requirement was not met for field \"\(path)\" with value \"\(value)\"", err)
}
}
}
}
}
fileprivate func validateMandatoryRules(_ json: NSDictionary) throws -> [LateBindClosure] {
var bindings = [LateBindClosure]()
for (path, rule) in pathMandatoryRules {
try autoreleasepool {
guard let value = getInDictionary(json, atPath: path) else {
throw RuleError.expectedNotFound("Unable to validate \"\(json)\" as \(T.self). Mandatory field \"\(path)\" not found in struct.", nil)
}
do {
if let binding = try rule(value) { bindings.append(binding) }
} catch let err as RuleError {
throw RuleError.invalidJSONType("Unable to validate mandatory field \"\(path)\" for \(T.self).", err)
}
}
}
return bindings
}
fileprivate func validateOptionalRules(_ json: NSDictionary) throws -> [LateBindClosure] {
var bindings = [LateBindClosure]()
for (path, rule) in pathOptionalRules {
try autoreleasepool {
let value = getInDictionary(json, atPath: path)
do {
if let binding = try rule(value) { bindings.append(binding) }
} catch let err as RuleError {
throw RuleError.invalidJSONType("Unable to validate optional field \"\(path)\" for \(T.self).", err)
}
}
}
return bindings
}
fileprivate func dumpMandatoryRules(_ value: T, dictionary: inout [String: Any]) throws {
for (path, rule) in mandatoryDumpRules {
try autoreleasepool {
do {
dictionary = try setInDictionary(dictionary, object: try rule(value), atPath: path)
} catch let err as RuleError {
throw RuleError.invalidDump("Unable to dump mandatory field \(path) for \(T.self).", err)
}
}
}
}
fileprivate func dumpOptionalRules(_ value: T, dictionary: inout [String: Any]) throws {
for (path, rule) in optionalDumpRules {
try autoreleasepool {
do {
if let v = try rule(value) {
dictionary = try setInDictionary(dictionary, object: v, atPath: path)
}
} catch let err as RuleError {
throw RuleError.invalidDump("Unable to dump optional field \(path) for \(T.self).", err)
}
}
}
}
}
/**
Validator of compound JSON object with binding to reference type like class T. Reference type is T itself.
*/
open class ClassRule<T>: ObjectRule<T, T> {
public override init( _ factory: @autoclosure @escaping ()->T) {
#if swift(>=5.0)
super.init(factory())
#else
super.init(factory)
#endif
}
open override func value(_ newStruct: T) -> T {
return newStruct
}
}
/**
Validator of compound JSON object with binding to value type like struct T. Reference type is ref<T>.
*/
open class StructRule<T>: ObjectRule<T, ref<T>> {
public override init( _ factory: @autoclosure @escaping ()->ref<T>) {
#if swift(>=5.0)
super.init(factory())
#else
super.init(factory)
#endif
}
open override func value(_ newStruct: ref<T>) -> T {
return newStruct.value
}
}
| mit | bf4a7b7cc089ad77e2f1e255da43dffe | 42.074747 | 212 | 0.629069 | 4.677929 | false | false | false | false |
DominikHorn/TUM-Utility | TUM-Utility/Utility.swift | 1 | 4314 | //
// Utility.swift
// TUM-Utility
//
// Created by Dominik Horn on 13.10.16.
// Copyright © 2016 Dominik Horn. All rights reserved.
//
import Foundation
// Define prefix operator to convert string to regex
prefix operator /
prefix func / (pattern:String) throws -> NSRegularExpression {
return try NSRegularExpression(pattern: pattern, options:
NSRegularExpression.Options.dotMatchesLineSeparators)
}
precedencegroup constPrecedence {
associativity: left
higherThan: AssignmentPrecedence
}
// Define infix operator for regex. This will return true when there are matches
infix operator =~ : constPrecedence
func =~ (string: String, regex: NSRegularExpression) -> Bool {
return regex.numberOfMatches(in: string, options: [], range: NSMakeRange(0, string.characters.count)) > 0
}
// Define infix operator for regex. This will return the actual matches found
infix operator =~~ : constPrecedence
func =~~ (string: String, regex: NSRegularExpression) -> [NSTextCheckingResult] {
return regex.matches(in: string, options: [], range: NSMakeRange(0, string.characters.count))
}
// global synchronized function to make up for the lack theirof in swift O.o
func synchronized(_ lock: AnyObject, _ closure: @escaping () -> ()) {
// lock using object
objc_sync_enter(lock)
// Execute closure
closure()
// Make sure this is executed no matter what
defer { objc_sync_exit(lock) }
}
class Utility: NSObject {
// TODO: lookup naming convention
static let REGEX_NUMBEREDLIST = "^(\\d+)\\."
static let REGEX_LINEENDSWITHPRICE = "\\s([0-9]+)\\.[0-9][0-9]"
class func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
return documentsDirectory
}
class func getAppGroupDocumentsDirectory() -> URL {
return FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.tum")!
}
class func lineIsPartOfNumberedList(string: String) -> Bool {
return try! string =~ /REGEX_NUMBEREDLIST
}
class func lineEndsWithPrice(line: String) -> Bool {
return try! line =~ /REGEX_LINEENDSWITHPRICE
}
/// Checks whether the date exists and is within today
class func isDateInToday(date: Date?) -> Bool {
guard let date = date else {
return false
}
// Return whether date is today or not
return Calendar.autoupdatingCurrent.isDateInToday(date)
}
//// TODO: find better way for everything bellow
private class func min(numbers: Int...) -> Int {
return numbers.reduce(numbers[0], {$0 < $1 ? $0 : $1})
}
class Array2D {
var cols:Int, rows:Int
var matrix: [Int]
init(cols:Int, rows:Int) {
self.cols = cols
self.rows = rows
matrix = Array(repeating:0, count:cols*rows)
}
subscript(col:Int, row:Int) -> Int {
get {
return matrix[cols * row + col]
}
set {
matrix[cols*row+col] = newValue
}
}
func colCount() -> Int {
return self.cols
}
func rowCount() -> Int {
return self.rows
}
}
class func levenshtein(aStr: String, bStr: String) -> Int {
let a = Array(aStr.utf16)
let b = Array(bStr.utf16)
let dist = Array2D(cols: a.count + 1, rows: b.count + 1)
for i in 1...a.count {
dist[i, 0] = i
}
for j in 1...b.count {
dist[0, j] = j
}
for i in 1...a.count {
for j in 1...b.count {
if a[i-1] == b[j-1] {
dist[i, j] = dist[i-1, j-1] // noop
} else {
dist[i, j] = min(
numbers: dist[i-1, j] + 1, // deletion
dist[i, j-1] + 1, // insertion
dist[i-1, j-1] + 1 // substitution
)
}
}
}
return dist[a.count, b.count]
}
}
| gpl-3.0 | 36adb160a1238509bf2eed8835d50dde | 28.744828 | 109 | 0.559703 | 4.236739 | false | false | false | false |
Wallapop/WallaFoundation | Deferred.swift | 1 | 10116 | //
// Deferred.swift
// AsyncNetworkServer
//
// Created by John Gallagher on 7/19/14.
// Copyright (c) 2014 Big Nerd Ranch. All rights reserved.
//
import Foundation
// TODO: Replace this with a class var
private var DeferredDefaultQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
public final class Deferred<T> {
typealias UponBlock = (dispatch_queue_t, T -> ())
private typealias Protected = (protectedValue: T?, uponBlocks: [UponBlock])
private var protected: LockProtected<Protected>
private let defaultQueue: dispatch_queue_t
private init(value: T?, queue: dispatch_queue_t) {
protected = LockProtected(item: (value, []))
self.defaultQueue = queue
}
// Initialize an unfilled Deferred
public convenience init(defaultQueue: dispatch_queue_t = DeferredDefaultQueue) {
self.init(value: nil, queue: defaultQueue)
}
// Initialize a filled Deferred with the given value
public convenience init(value: T, defaultQueue: dispatch_queue_t = DeferredDefaultQueue) {
self.init(value: value, queue: defaultQueue)
}
// Check whether or not the receiver is filled
public var isFilled: Bool {
return protected.withReadLock { $0.protectedValue != nil }
}
private func _fill(value: T, assertIfFilled: Bool) {
let (filledValue, blocks) = protected.withWriteLock { data -> (T, [UponBlock]) in
if assertIfFilled {
precondition(data.protectedValue == nil, "Cannot fill an already-filled Deferred")
data.protectedValue = value
} else if data.protectedValue == nil {
data.protectedValue = value
}
let blocks = data.uponBlocks
data.uponBlocks.removeAll(keepCapacity: false)
return (data.protectedValue!, blocks)
}
for (queue, block) in blocks {
dispatch_async(queue) { block(filledValue) }
}
}
public func fill(value: T) {
_fill(value, assertIfFilled: true)
}
public func fillIfUnfilled(value: T) {
_fill(value, assertIfFilled: false)
}
public func peek() -> T? {
return protected.withReadLock { $0.protectedValue }
}
public func uponQueue(queue: dispatch_queue_t, block: T -> ()) {
let maybeValue: T? = protected.withWriteLock{ data in
if data.protectedValue == nil {
data.uponBlocks.append( (queue, block) )
}
return data.protectedValue
}
if let value = maybeValue {
dispatch_async(queue) { block(value) }
}
}
}
extension Deferred {
public var value: T {
// fast path - return if already filled
if let v = peek() {
return v
}
// slow path - block until filled
let group = dispatch_group_create()
var result: T!
dispatch_group_enter(group)
self.upon { result = $0; dispatch_group_leave(group) }
dispatch_group_wait(group, DISPATCH_TIME_FOREVER)
return result
}
}
extension Deferred {
public func bindQueue<U>(queue: dispatch_queue_t, f: T -> Deferred<U>) -> Deferred<U> {
let d = Deferred<U>()
self.uponQueue(queue) {
f($0).uponQueue(queue) {
d.fill($0)
}
}
return d
}
public func mapQueue<U>(queue: dispatch_queue_t, f: T -> U) -> Deferred<U> {
return bindQueue(queue) { t in Deferred<U>(value: f(t)) }
}
}
extension Deferred {
public func upon(block: T ->()) {
uponQueue(defaultQueue, block: block)
}
public func bind<U>(f: T -> Deferred<U>) -> Deferred<U> {
return bindQueue(defaultQueue, f: f)
}
public func map<U>(f: T -> U) -> Deferred<U> {
return mapQueue(defaultQueue, f: f)
}
}
extension Deferred {
public func both<U>(other: Deferred<U>) -> Deferred<(T,U)> {
return self.bind { t in other.map { u in (t, u) } }
}
}
public func all<T>(deferreds: [Deferred<T>]) -> Deferred<[T]> {
if deferreds.count == 0 {
return Deferred(value: [])
}
let combined = Deferred<[T]>()
var results: [T] = []
results.reserveCapacity(deferreds.count)
var block: (T -> ())!
block = { t in
results.append(t)
if results.count == deferreds.count {
combined.fill(results)
} else {
deferreds[results.count].upon(block)
}
}
deferreds[0].upon(block)
return combined
}
public func any<T>(deferreds: [Deferred<T>]) -> Deferred<Deferred<T>> {
let combined = Deferred<Deferred<T>>()
for d in deferreds {
d.upon { _ in combined.fillIfUnfilled(d) }
}
return combined
}
public final class LockProtected<T> {
private var lock: ReadWriteLock
private var item: T
public convenience init(item: T) {
self.init(item: item, lock: CASSpinLock())
}
public init(item: T, lock: ReadWriteLock) {
self.item = item
self.lock = lock
}
public func withReadLock<U>(block: T -> U) -> U {
return lock.withReadLock { [unowned self] in
return block(self.item)
}
}
public func withWriteLock<U>(block: (inout T) -> U) -> U {
return lock.withWriteLock { [unowned self] in
return block(&self.item)
}
}
}
public protocol ReadWriteLock: class {
func withReadLock<T>(block: () -> T) -> T
func withWriteLock<T>(block: () -> T) -> T
}
public final class GCDReadWriteLock: ReadWriteLock {
private let queue = dispatch_queue_create("GCDReadWriteLock", DISPATCH_QUEUE_CONCURRENT)
public init() {}
public func withReadLock<T>(block: () -> T) -> T {
var result: T!
dispatch_sync(queue) {
result = block()
}
return result
}
public func withWriteLock<T>(block: () -> T) -> T {
var result: T!
dispatch_barrier_sync(queue) {
result = block()
}
return result
}
}
public final class SpinLock: ReadWriteLock {
private var lock: UnsafeMutablePointer<Int32>
public init() {
lock = UnsafeMutablePointer.alloc(1)
lock.memory = OS_SPINLOCK_INIT
}
deinit {
lock.dealloc(1)
}
public func withReadLock<T>(block: () -> T) -> T {
OSSpinLockLock(lock)
let result = block()
OSSpinLockUnlock(lock)
return result
}
public func withWriteLock<T>(block: () -> T) -> T {
OSSpinLockLock(lock)
let result = block()
OSSpinLockUnlock(lock)
return result
}
}
/// Test comment 2
public final class CASSpinLock: ReadWriteLock {
private struct Masks {
static let WRITER_BIT: Int32 = 0x40000000
static let WRITER_WAITING_BIT: Int32 = 0x20000000
static let MASK_WRITER_BITS = WRITER_BIT | WRITER_WAITING_BIT
static let MASK_READER_BITS = ~MASK_WRITER_BITS
}
private var _state: UnsafeMutablePointer<Int32>
public init() {
_state = UnsafeMutablePointer.alloc(1)
_state.memory = 0
}
deinit {
_state.dealloc(1)
}
public func withWriteLock<T>(block: () -> T) -> T {
// spin until we acquire write lock
repeat {
let state = _state.memory
// if there are no readers and no one holds the write lock, try to grab the write lock immediately
if (state == 0 || state == Masks.WRITER_WAITING_BIT) &&
OSAtomicCompareAndSwap32Barrier(state, Masks.WRITER_BIT, _state) {
break
}
// If we get here, someone is reading or writing. Set the WRITER_WAITING_BIT if
// it isn't already to block any new readers, then wait a bit before
// trying again. Ignore CAS failure - we'll just try again next iteration
if state & Masks.WRITER_WAITING_BIT == 0 {
OSAtomicCompareAndSwap32Barrier(state, state | Masks.WRITER_WAITING_BIT, _state)
}
} while true
// write lock acquired - run block
let result = block()
// unlock
repeat {
let state = _state.memory
// clear everything except (possibly) WRITER_WAITING_BIT, which will only be set
// if another writer is already here and waiting (which will keep out readers)
if OSAtomicCompareAndSwap32Barrier(state, state & Masks.WRITER_WAITING_BIT, _state) {
break
}
} while true
return result
}
public func withReadLock<T>(block: () -> T) -> T {
// spin until we acquire read lock
repeat {
let state = _state.memory
// if there is no writer and no writer waiting, try to increment reader count
if (state & Masks.MASK_WRITER_BITS) == 0 &&
OSAtomicCompareAndSwap32Barrier(state, state + 1, _state) {
break
}
} while true
// read lock acquired - run block
let result = block()
// decrement reader count
repeat {
let state = _state.memory
// sanity check that we have a positive reader count before decrementing it
assert((state & Masks.MASK_READER_BITS) > 0, "unlocking read lock - invalid reader count")
// desired new state: 1 fewer reader, preserving whether or not there is a writer waiting
let newState = ((state & Masks.MASK_READER_BITS) - 1) |
(state & Masks.WRITER_WAITING_BIT)
if OSAtomicCompareAndSwap32Barrier(state, newState, _state) {
break
}
} while true
return result
}
}
| mit | 7e68fd3baef4f72bbe492eb98fe4dc9b | 29.197015 | 110 | 0.566034 | 4.262958 | false | false | false | false |
Ge3kXm/MXWB | MXWB/Classes/Home/View/HomeCollectionView.swift | 1 | 5488 | //
// HomeCollectionView.swift
// MXWB
//
// Created by maRk on 2017/5/16.
// Copyright © 2017年 maRk. All rights reserved.
//
import UIKit
import SDWebImage
class HomeCollectionView: UICollectionView, UICollectionViewDelegate, UICollectionViewDataSource{
@IBOutlet weak var colletionLayout: UICollectionViewFlowLayout!
@IBOutlet weak var clvWidthCon: NSLayoutConstraint!
@IBOutlet weak var clvHeightCon: NSLayoutConstraint!
var statusViewMoldel: StatusViewModel? {
didSet {
reloadData()
let (itemSize, clvSize) = calculateSize()
// item不能为zero否则报错
if itemSize != CGSize.zero
{
colletionLayout.itemSize = itemSize
}
clvHeightCon.constant = clvSize.height;
clvWidthCon.constant = clvSize.width
}
}
override func awakeFromNib() {
super.awakeFromNib()
self.delegate = self
self.dataSource = self
}
// MARK: - PrivateFunc
/// 计算item Size和collectionView Size
private func calculateSize() -> (CGSize, CGSize)
{
let count = statusViewMoldel?.thumbnail_urls?.count ?? 0
// 没有配图
if count == 0 {
return (CGSize.zero, CGSize.zero)
}
// 有一张配图时按照图片的大小来设置cell的大小
if count == 1 {
// 从缓存中取出图片,且一定有图
let image = SDWebImageManager.shared().imageCache!.imageFromCache(forKey: statusViewMoldel!.thumbnail_urls!.first!.absoluteString)!
return (image.size, image.size)
}
let imageWidth: CGFloat = 90
let imageHeight: CGFloat = 90
let imageMargin: CGFloat = 10
// 四张配图或以上时固定大小
if count == 4
{
let col = 2
let row = col
let width = imageWidth * CGFloat(col) + CGFloat(col - 1) * imageMargin
let height = imageHeight * CGFloat(row) + CGFloat(row - 1) * imageMargin
return (CGSize(width: imageWidth, height: imageHeight), CGSize(width: width, height: height))
}
// 其他张配图
let col = 3
let row = (count - 1) / 3 + 1
let width = imageWidth * CGFloat(col) + CGFloat(col - 1) * imageMargin
let height = imageHeight * CGFloat(row) + CGFloat(row - 1) * imageMargin
return (CGSize(width: imageWidth, height: imageHeight), CGSize(width: width, height: height))
}
// MARK: - UICollectionViewDataSource
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return self.statusViewMoldel?.thumbnail_urls?.count ?? 0
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HomeColletionViewCell", for: indexPath) as! HomeCollectionViewCell
cell.url = self.statusViewMoldel?.thumbnail_urls?[indexPath.row];
return cell
}
// MARK: - UICollectionViewDelegate
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
MXLog(indexPath.item)
let url = statusViewMoldel!.bmiddle_urls![indexPath.item]
// 取出cell
let cell = collectionView.cellForItem(at: indexPath) as! HomeCollectionViewCell
SDWebImageManager.shared().loadImage(with: url, options: SDWebImageOptions.retryFailed, progress: { (current, total, _) in
cell.imageView.progress = CGFloat(current) / CGFloat(total)
MXLog(cell.imageView.progress)
}) { (_, _, error, _, _, _) in
NotificationCenter.default.post(name: NSNotification.Name(rawValue: MXWB_NOTIFICATION_COLLECTIONVIEWCELL_SELECTED), object: self, userInfo: ["bmiddle_url": self.statusViewMoldel!.bmiddle_urls!, "indexPath": indexPath])
}
}
}
extension HomeCollectionView: MXPicBrowserDelegate
{
func browserPresentionShowImageView(presentationController: MXPicBrowserPC, indexPath: IndexPath) -> UIImageView {
let iv = UIImageView()
let cell = cellForItem(at: indexPath) as! HomeCollectionViewCell
iv.image = cell.imageView.image
iv.sizeToFit()
return iv
}
func browserPresentionFromFrame(presentationController: MXPicBrowserPC, indexPath: IndexPath) -> CGRect {
let cell = cellForItem(at: indexPath) as! HomeCollectionViewCell
let frame = self.convert(cell.frame, to: UIApplication.shared.keyWindow)
return frame
}
func browserPresentionToFrame(presentationController: MXPicBrowserPC, indexPath: IndexPath) -> CGRect {
let width = UIScreen.main.bounds.width
let height = UIScreen.main.bounds.height
let cell = cellForItem(at: indexPath) as! HomeCollectionViewCell
let scale = CGFloat(cell.imageView.image!.size.height) / CGFloat(cell.imageView.image!.size.width)
let imageHeight = width * scale
var offsetY: CGFloat = 0.0
if imageHeight < height {
offsetY = (height - imageHeight) * 0.5
}
return CGRect(x: 0, y: offsetY, width: width, height: imageHeight)
}
}
| apache-2.0 | 80ba96dda5ffbaecc0ea8f9c07f2d5cc | 35.414966 | 230 | 0.632169 | 4.775201 | false | false | false | false |
XLabKC/Badger | Badger/Badger/ProfileControlsCell.swift | 1 | 1569 | import UIKit
class ProfileControlsCell: BorderedCell {
private var hasAwakened = false
private var user: User?
private var authUser: User?
private var observer: FirebaseObserver<User>?
@IBOutlet weak var subscribeButton: ResizedImageButton!
deinit {
if let observer = self.observer {
observer.dispose()
}
}
@IBAction func subscribedPressed(sender: AnyObject) {
if let user = self.user {
if let authUser = self.authUser {
if authUser.followingIds[user.uid] == nil {
// Start following user.
UserStore.followUser(authUser.uid, otherUid: user.uid)
} else {
// Stop following user.
UserStore.unFollowUser(authUser.uid, otherUid: user.uid)
}
}
}
}
override func awakeFromNib() {
self.hasAwakened = true
let authUid = UserStore.sharedInstance().getAuthUid()
self.observer = FirebaseObserver<User>(query: User.createRef(authUid), withBlock: { user in
self.authUser = user
self.updateView()
})
}
func setUser(user: User) {
self.user = user
self.updateView()
}
private func updateView() {
if self.hasAwakened {
if let user = self.user {
if let authUser = self.authUser {
self.subscribeButton.selected = authUser.followingIds[user.uid] != nil
}
}
}
}
} | gpl-2.0 | 92b1422e2049ce4ef0cf870fc23b7e58 | 28.074074 | 99 | 0.550669 | 4.683582 | false | false | false | false |
jubinjacob19/CustomCalendarSwift | SampleCalendar/NoteViewController.swift | 1 | 8482 | //
// NoteViewController.swift
// SampleCalendar
//
// Created by ram on 03/07/15.
// Copyright (c) 2015 XYZ. All rights reserved.
//
import UIKit
enum TagColors{
case Green
case Blue
case Red
case Gray
static let allColors : [TagColors] = [Green,Blue,Red,Gray]
var color : UIColor? {
get {
switch(self){
case .Green : return UIColor.greenColor()
case .Blue : return UIColor.blueColor()
case .Red : return UIColor.redColor()
case .Gray : return UIColor.grayColor()
}
}
}
}
class NoteViewController: UIViewController,UITextFieldDelegate,TagButtonDelegate,UITextViewDelegate {
var date : NSDate?
var selectedTag : TagButton?
private var discardedNote : Bool = false
private var selectedColor : UIColor?
private var selectedNote : Note?
private lazy var titleField : UITextField = {
var textField = UITextField()
textField.placeholder = "Title"
textField.setTranslatesAutoresizingMaskIntoConstraints(false)
textField.textColor = UIColor.brownColor()
textField.font = UIFont(name: "Helvetica-Bold", size: 16)
textField.delegate = self
return textField
}()
private var dateFormatter : NSDateFormatter = {
let dateFmtr = NSDateFormatter()
dateFmtr.dateFormat = "dd MMMM yyyy"
return dateFmtr
}()
private lazy var noteDescription : UITextView = {
var textView = UITextView()
textView.setTranslatesAutoresizingMaskIntoConstraints(false)
textView.textColor = UIColor.lightGrayColor()
textView.font = UIFont(name: "Helvetica", size: 14)
textView.text = "Note"
textView.delegate = self
return textView
}()
convenience init(date : NSDate){
self.init(nibName: nil, bundle: nil)
self.date = date
self.title = self.dateFormatter.stringFromDate(self.date!)
self.selectedNote = CoreDataManager.sharedInstance.getNote(self.date!).note
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nil, bundle: nil)
}
required init(coder aDecoder: NSCoder) {
super.init(coder:aDecoder )
}
override func viewDidLoad() {
super.viewDidLoad()
let trashButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Trash, target: self, action: "discardNote")
self.navigationItem.rightBarButtonItem = trashButton
self.view.backgroundColor = UIColor.whiteColor()
self.addSubviews()
self.setLayoutConstraints()
// Do any additional setup after loading the view.
}
func addSubviews(){
self.view.addSubview(self.titleField)
self.view.addSubview(self.noteDescription)
self.titleField.becomeFirstResponder()
self.addTagOptions()
if(self.selectedNote != nil){
self.titleField.text = self.selectedNote?.title
self.noteDescription.text = self.selectedNote?.noteDescription
}
}
func setLayoutConstraints(){
self.view.addConstraint(NSLayoutConstraint(item: self.titleField, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 160))
self.view.addConstraint(NSLayoutConstraint(item: self.titleField, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 20))
self.view.addConstraint(NSLayoutConstraint(item: self.titleField, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 20))
self.view.addConstraint(NSLayoutConstraint(item: self.noteDescription, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.titleField, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 10))
self.view.addConstraint(NSLayoutConstraint(item: self.noteDescription, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self.titleField, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: -5))
self.view.addConstraint(NSLayoutConstraint(item: self.noteDescription, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: self.noteDescription, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 80))
}
func addTagOptions(){
for (index, value) in enumerate(TagColors.allColors){
var selected : Bool? = false
if(self.selectedNote == nil){
selected = (index == 0)
} else{
let color : UIColor = value.color!
var dbColor : UIColor? = self.selectedNote?.color as! UIColor!
selected = (color == dbColor)
}
let tagView : TagButton = TagButton(radius: 50, color: value.color!, isSelected: selected!, delegate : self)
if(selected == true){
self.selectedTag = tagView
self.selectedColor = value.color
}
self.view.addSubview(tagView)
self.view.addConstraint(NSLayoutConstraint(item: tagView, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: CGFloat(50 * (index+1))))
self.view.addConstraint(NSLayoutConstraint(item: tagView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 80))
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func selectedTagWthColor(color: UIColor, sender: TagButton) {
self.selectedTag?.markUnSelected()
self.selectedTag = sender
self.selectedColor = color
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
return true
}
func textViewShouldBeginEditing(textView: UITextView) -> Bool {
if(true){
textView.textColor = UIColor.blackColor()
textView.text = ""
}
return true
}
func textViewDidEndEditing(textView: UITextView) {
if(textView.text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) == ""){
textView.textColor = UIColor.lightGrayColor()
textView.text = "Note"
}
}
func discardNote(){
self.discardedNote = true
self.navigationController?.popViewControllerAnimated(true)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
if(self.isMovingFromParentViewController()){
if(!self.discardedNote){
if(self.selectedNote != nil){
CoreDataManager.sharedInstance.modifyNote(self.selectedNote!, title : self.titleField.text, noteDescripton: self.noteDescription.text, date: self.date!, color: self.selectedColor!)
}else{
if(!self.titleField.text.isEmpty){
CoreDataManager.sharedInstance.addNote(self.titleField.text, noteDescripton: self.noteDescription.text, date: self.date!, color: self.selectedColor!)
}
}
}else{
if(self.selectedNote != nil){
CoreDataManager.sharedInstance.deleteNote(self.selectedNote!)
}
}
}
}
}
| mit | 542ba8bd47028382a05a27adcb827aa0 | 39.975845 | 250 | 0.647725 | 5.1688 | false | false | false | false |
cotkjaer/SilverbackFramework | SilverbackFramework/Queue.swift | 1 | 3928 | //
// Queue.swift
// SilverbackFramework
//
// Created by Christian Otkjær on 01/06/15.
// Copyright (c) 2015 Christian Otkjær. All rights reserved.
//
import Foundation
// private, as users of Queue never use this directly
private class QueueNode<T>
{
// note, not optional – every node has a value
var value: T
// but the last node doesn't have a next
var next: QueueNode<T>? = nil
init(value: T)
{
self.value = value
}
}
public struct Queue<T>
{
private var firstNode: QueueNode<T>? = nil
private var lastNode: QueueNode<T>? = nil
public init() { }
}
extension Queue
{
mutating public func append(newElement: T)
{
let newNode = QueueNode(value:newElement)
if firstNode == nil
{
firstNode = newNode
}
lastNode?.next = newNode
lastNode = newNode
}
mutating public func enqueue(newElement: T)
{
append(newElement)
}
mutating public func dequeue() -> T?
{
if let _ = firstNode?.value
{
firstNode = firstNode?.next
if firstNode == nil
{
lastNode = nil
}
}
return nil
}
}
public struct QueueIndex<T>: ForwardIndexType
{
private let node: QueueNode<T>?
public func successor() -> QueueIndex<T>
{
return QueueIndex(node: node?.next)
}
}
public func ==<T>(lhs: QueueIndex<T>, rhs: QueueIndex<T>) -> Bool
{
if let lhsNode = lhs.node, let rhsNode = rhs.node
{
return lhsNode === rhsNode
}
return false
}
extension Queue: MutableCollectionType
{
public typealias Index = QueueIndex<T>
public var startIndex: Index
{ return Index(node: firstNode) }
public var endIndex: Index
{ return Index(node: nil) }
public subscript(idx: Index) -> T
{
get
{
if let node = idx.node
{
return node.value
}
else
{
preconditionFailure("Attempt to subscript out of bounds")
}
}
set
{
if let node = idx.node
{
node.value = newValue
}
else
{
preconditionFailure("Attempt to subscript out of bounds")
}
}
}
public typealias Generator = IndexingGenerator<Queue>
public func generate() -> Generator
{
return Generator(self)
}
}
// init() and append() requirements are already covered
extension Queue: RangeReplaceableCollectionType
{
public mutating func replaceRange<C : CollectionType where C.Generator.Element == Generator.Element>(subRange: Range<Queue.Index>, with newElements: C) {
preconditionFailure("TODO: implement")
}
public func reserveCapacity(n: Index.Distance)
{
// do nothing
}
mutating public func extend<S : SequenceType where S.Generator.Element == T>
(newElements: S)
{
for x in newElements
{
append(x)
}
}
}
extension Queue: ArrayLiteralConvertible
{
public init(arrayLiteral elements: T...)
{
self.init()
// conformance to ExtensibleCollectionType makes this easy
self.extend(elements)
}
}
extension Queue: CustomStringConvertible
{
// pretty easy given conformance to CollectionType
public var description: String
{
return String( map { (t) -> String in
if t is CustomStringConvertible
{
return (t as! CustomStringConvertible).description
}
return "."
})
// return "[" + ", ".join(self.map(String.init)) + "]"
}
} | mit | 7baa40bfb1b9000097c7d3255ad497f7 | 20.448087 | 157 | 0.542304 | 4.688172 | false | false | false | false |
stephentyrone/swift | test/IRGen/prespecialized-metadata/struct-extradata-field_offsets-no_trailing_flags.swift | 3 | 2980 | // RUN: %target-swift-frontend -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment
// REQUIRES: OS=macosx || OS=ios || OS=tvos || OS=watchos || OS=linux-gnu
// UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
// CHECK: [[EXTRA_DATA_PATTERN:@[0-9]+]] = internal constant {
// CHECK-SAME: i32
// CHECK-SAME: , i32
// CHECK-SAME: , i32
// : , [4 x i8]
// CHECK-SAME: } {
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 8,
// CHECK-SAME: i32 16
// : , [4 x i8] zeroinitializer
// CHECK-SAME: }, align [[ALIGNMENT]]
// CHECK: @"$s4main4PairVMP" = internal constant <{
// : i32,
// : i32,
// : i32,
// : i32,
// : i32,
// : i16,
// : i16
// : }> <{
// : i32 trunc (
// : i64 sub (
// : i64 ptrtoint (
// : %swift.type* (
// : %swift.type_descriptor*,
// : i8**,
// : i8*
// : )* @"$s4main4PairVMi" to i64
// : ),
// : i64 ptrtoint (
// : <{ i32, i32, i32, i32, i32, i16, i16 }>*
// : @"$s4main4PairVMP" to i64
// : )
// : ) to i32
// : ),
// : i32 0,
// : i32 1073741827,
// : i32 trunc (
// : i64 sub (
// : i64 ptrtoint (
// : %swift.vwtable* @"$s4main4PairVWV" to i64
// : ),
// : i64 ptrtoint (
// : i32* getelementptr inbounds (
// : <{ i32, i32, i32, i32, i32, i16, i16 }>,
// : <{ i32, i32, i32, i32, i32, i16, i16 }>* @"$s4main4PairVMP",
// : i32 0,
// : i32 3
// : ) to i64
// : )
// : ) to i32
// : ),
// : i32 trunc (
// CHECK-SAME: [[INT]] sub (
// CHECK-SAME: [[INT]] ptrtoint (
// CHECK-SAME: { i32
// CHECK-SAME: , i32
// CHECK-SAME: , i32
// : , [4 x i8]
// CHECK-SAME: }* [[EXTRA_DATA_PATTERN]] to [[INT]]
// CHECK-SAME: ),
// CHECK-SAME: [[INT]] ptrtoint (
// CHECK-SAME: i32* getelementptr inbounds (
// CHECK-SAME: <{ i32, i32, i32, i32, i32, i16, i16 }>,
// CHECK-SAME: <{ i32, i32, i32, i32, i32, i16, i16 }>* @"$s4main4PairVMP",
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 4
// CHECK-SAME: ) to [[INT]]
// CHECK-SAME: )
// CHECK-SAME: )
// : ),
// : i16 3,
// : i16 3
// : }>, align 8
struct Pair<First, Second, Third> {
let first: Int64
let second: Int64
let third: Int64
}
| apache-2.0 | b3eb9479b0fe3c373f0c4d08be2d62a8 | 32.483146 | 111 | 0.378188 | 2.956349 | false | false | false | false |
saagarjha/iina | iina/InspectorWindowController.swift | 1 | 11554 | //
// InspectorWindowController.swift
// iina
//
// Created by lhc on 21/12/2016.
// Copyright © 2016 lhc. All rights reserved.
//
import Cocoa
class InspectorWindowController: NSWindowController, NSTableViewDelegate, NSTableViewDataSource {
override var windowNibName: NSNib.Name {
return NSNib.Name("InspectorWindowController")
}
var updateTimer: Timer?
var watchProperties: [String] = []
@IBOutlet weak var tabView: NSTabView!
@IBOutlet weak var trackPopup: NSPopUpButton!
@IBOutlet weak var pathField: NSTextField!
@IBOutlet weak var fileSizeField: NSTextField!
@IBOutlet weak var fileFormatField: NSTextField!
@IBOutlet weak var chaptersField: NSTextField!
@IBOutlet weak var editionsField: NSTextField!
@IBOutlet weak var durationField: NSTextField!
@IBOutlet weak var vformatField: NSTextField!
@IBOutlet weak var vcodecField: NSTextField!
@IBOutlet weak var vdecoderField: NSTextField!
@IBOutlet weak var vcolorspaceField: NSTextField!
@IBOutlet weak var vprimariesField: NSTextField!
@IBOutlet weak var voField: NSTextField!
@IBOutlet weak var vsizeField: NSTextField!
@IBOutlet weak var vbitrateField: NSTextField!
@IBOutlet weak var vfpsField: NSTextField!
@IBOutlet weak var aformatField: NSTextField!
@IBOutlet weak var acodecField: NSTextField!
@IBOutlet weak var aoField: NSTextField!
@IBOutlet weak var achannelsField: NSTextField!
@IBOutlet weak var abitrateField: NSTextField!
@IBOutlet weak var asamplerateField: NSTextField!
@IBOutlet weak var trackIdField: NSTextField!
@IBOutlet weak var trackDefaultField: NSTextField!
@IBOutlet weak var trackForcedField: NSTextField!
@IBOutlet weak var trackSelectedField: NSTextField!
@IBOutlet weak var trackExternalField: NSTextField!
@IBOutlet weak var trackSourceIdField: NSTextField!
@IBOutlet weak var trackTitleField: NSTextField!
@IBOutlet weak var trackLangField: NSTextField!
@IBOutlet weak var trackFilePathField: NSTextField!
@IBOutlet weak var trackCodecField: NSTextField!
@IBOutlet weak var trackDecoderField: NSTextField!
@IBOutlet weak var trackFPSField: NSTextField!
@IBOutlet weak var trackChannelsField: NSTextField!
@IBOutlet weak var trackSampleRateField: NSTextField!
@IBOutlet weak var avsyncField: NSTextField!
@IBOutlet weak var totalAvsyncField: NSTextField!
@IBOutlet weak var droppedFramesField: NSTextField!
@IBOutlet weak var mistimedFramesField: NSTextField!
@IBOutlet weak var displayFPSField: NSTextField!
@IBOutlet weak var voFPSField: NSTextField!
@IBOutlet weak var edispFPSField: NSTextField!
@IBOutlet weak var watchTableView: NSTableView!
@IBOutlet weak var deleteButton: NSButton!
override func windowDidLoad() {
super.windowDidLoad()
watchProperties = Preference.array(for: .watchProperties) as! [String]
watchTableView.delegate = self
watchTableView.dataSource = self
deleteButton.isEnabled = false
if #available(macOS 10.14, *) {} else {
window?.appearance = NSAppearance(named: .vibrantDark)
}
updateInfo()
updateTimer = Timer.scheduledTimer(timeInterval: TimeInterval(1), target: self, selector: #selector(dynamicUpdate), userInfo: nil, repeats: true)
NotificationCenter.default.addObserver(self, selector: #selector(fileLoaded), name: .iinaFileLoaded, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(fileLoaded), name: .iinaMainWindowChanged, object: nil)
}
deinit {
ObjcUtils.silenced {
NotificationCenter.default.removeObserver(self)
}
}
func updateInfo(dynamic: Bool = false) {
let controller = PlayerCore.lastActive.mpv!
let info = PlayerCore.lastActive.info
DispatchQueue.main.async {
if !dynamic {
// string properties
let strProperties: [String: NSTextField] = [
MPVProperty.path: self.pathField,
MPVProperty.fileFormat: self.fileFormatField,
MPVProperty.chapters: self.chaptersField,
MPVProperty.editions: self.editionsField,
MPVProperty.videoFormat: self.vformatField,
MPVProperty.videoCodec: self.vcodecField,
MPVProperty.hwdecCurrent: self.vdecoderField,
MPVProperty.containerFps: self.vfpsField,
MPVProperty.currentVo: self.voField,
MPVProperty.audioCodec: self.acodecField,
MPVProperty.currentAo: self.aoField,
MPVProperty.audioParamsFormat: self.aformatField,
MPVProperty.audioParamsChannels: self.achannelsField,
MPVProperty.audioBitrate: self.abitrateField,
MPVProperty.audioParamsSamplerate: self.asamplerateField
]
for (k, v) in strProperties {
var value = controller.getString(k)
if value == "" { value = nil }
v.stringValue = value ?? "N/A"
self.setLabelColor(v, by: value != nil)
}
// other properties
let duration = controller.getDouble(MPVProperty.duration)
self.durationField.stringValue = VideoTime(duration).stringRepresentation
let vwidth = controller.getInt(MPVProperty.width)
let vheight = controller.getInt(MPVProperty.height)
self.vsizeField.stringValue = "\(vwidth)\u{d7}\(vheight)"
let fileSize = controller.getInt(MPVProperty.fileSize)
self.fileSizeField.stringValue = "\(FloatingPointByteCountFormatter.string(fromByteCount: fileSize))B"
// track list
self.trackPopup.removeAllItems()
var needSeparator = false
for track in info.videoTracks {
self.trackPopup.menu?.addItem(withTitle: "Video" + track.readableTitle,
action: nil, tag: nil, obj: track, stateOn: false)
needSeparator = true
}
if needSeparator && !info.audioTracks.isEmpty {
self.trackPopup.menu?.addItem(NSMenuItem.separator())
}
for track in info.audioTracks {
self.trackPopup.menu?.addItem(withTitle: "Audio" + track.readableTitle,
action: nil, tag: nil, obj: track, stateOn: false)
needSeparator = true
}
if needSeparator && !info.subTracks.isEmpty {
self.trackPopup.menu?.addItem(NSMenuItem.separator())
}
for track in info.subTracks {
self.trackPopup.menu?.addItem(withTitle: "Subtitle" + track.readableTitle,
action: nil, tag: nil, obj: track, stateOn: false)
}
self.trackPopup.selectItem(at: 0)
self.updateTrack()
}
let vbitrate = controller.getInt(MPVProperty.videoBitrate)
self.vbitrateField.stringValue = FloatingPointByteCountFormatter.string(fromByteCount: vbitrate) + "bps"
let abitrate = controller.getInt(MPVProperty.audioBitrate)
self.abitrateField.stringValue = FloatingPointByteCountFormatter.string(fromByteCount: abitrate) + "bps"
let dynamicStrProperties: [String: NSTextField] = [
MPVProperty.avsync: self.avsyncField,
MPVProperty.totalAvsyncChange: self.totalAvsyncField,
MPVProperty.frameDropCount: self.droppedFramesField,
MPVProperty.mistimedFrameCount: self.mistimedFramesField,
MPVProperty.displayFps: self.displayFPSField,
MPVProperty.estimatedVfFps: self.voFPSField,
MPVProperty.estimatedDisplayFps: self.edispFPSField
]
for (k, v) in dynamicStrProperties {
let value = controller.getString(k)
v.stringValue = value ?? "N/A"
self.setLabelColor(v, by: value != nil)
}
let sigPeak = controller.getDouble(MPVProperty.videoParamsSigPeak);
self.vprimariesField.stringValue = sigPeak > 0
? "\(controller.getString(MPVProperty.videoParamsPrimaries) ?? "?") / \(controller.getString(MPVProperty.videoParamsGamma) ?? "?") (\(sigPeak > 1 ? "H" : "S")DR)"
: "N/A";
self.setLabelColor(self.vprimariesField, by: sigPeak > 0)
if PlayerCore.lastActive.mainWindow.loaded && controller.fileLoaded {
let colorspace = PlayerCore.lastActive.mainWindow.videoView.videoLayer.colorspace?.name;
self.vcolorspaceField.stringValue = colorspace == nil ? "Unspecified (SDR)" : String(colorspace!) + " (HDR)"
} else {
self.vcolorspaceField.stringValue = "N/A"
}
self.setLabelColor(self.vcolorspaceField, by: controller.fileLoaded)
}
}
@objc func fileLoaded() {
updateInfo()
}
@objc func dynamicUpdate() {
updateInfo(dynamic: true)
watchTableView.reloadData()
}
func updateTrack() {
guard let track = trackPopup.selectedItem?.representedObject as? MPVTrack else { return }
trackIdField.stringValue = "\(track.id)"
setLabelColor(trackDefaultField, by: track.isDefault)
setLabelColor(trackForcedField, by: track.isForced)
setLabelColor(trackSelectedField, by: track.isSelected)
setLabelColor(trackExternalField, by: track.isExternal)
let strProperties: [(String?, NSTextField)] = [
(track.srcId?.description, trackSourceIdField),
(track.title, trackTitleField),
(track.lang, trackLangField),
(track.externalFilename, trackFilePathField),
(track.codec, trackCodecField),
(track.decoderDesc, trackDecoderField),
(track.demuxFps?.description, trackFPSField),
(track.demuxChannels, trackChannelsField),
(track.demuxSamplerate?.description, trackSampleRateField)
]
for (str, field) in strProperties {
field.stringValue = str ?? "N/A"
setLabelColor(field, by: str != nil)
}
}
// MARK: NSTableView
func numberOfRows(in tableView: NSTableView) -> Int {
return watchProperties.count
}
func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? {
guard let identifier = tableColumn?.identifier else { return nil }
guard let property = watchProperties[at: row] else { return nil }
if identifier == .key {
return property
} else if identifier == .value {
return PlayerCore.active.mpv.getString(property) ?? "<Error>"
}
return ""
}
func tableView(_ tableView: NSTableView, setObjectValue object: Any?, for tableColumn: NSTableColumn?, row: Int) {
guard let value = object as? String,
let identifier = tableColumn?.identifier else { return }
if identifier == .key {
watchProperties[row] = value
}
saveWatchList()
}
func tableViewSelectionDidChange(_ notification: Notification) {
deleteButton.isEnabled = (watchTableView.selectedRow != -1)
}
@IBAction func addWatchAction(_ sender: AnyObject) {
Utility.quickPromptPanel("add_watch", sheetWindow: window) { str in
self.watchProperties.append(str)
self.watchTableView.reloadData()
self.saveWatchList()
}
}
@IBAction func removeWatchAction(_ sender: AnyObject) {
if watchTableView.selectedRow >= 0 {
watchProperties.remove(at: watchTableView.selectedRow)
watchTableView.reloadData()
}
saveWatchList()
}
// MARK: IBActions
@IBAction func tabSwitched(_ sender: NSSegmentedControl) {
tabView.selectTabViewItem(at: sender.selectedSegment)
}
@IBAction func trackSwitched(_ sender: AnyObject) {
updateTrack()
}
// MARK: Utils
private func setLabelColor(_ label: NSTextField, by state: Bool) {
label.textColor = state ? NSColor.textColor : NSColor.disabledControlTextColor
}
private func saveWatchList() {
Preference.set(watchProperties, for: .watchProperties)
}
}
| gpl-3.0 | e0ca625d3c86e85a0b83419c3243d425 | 35.216301 | 170 | 0.70129 | 4.349774 | false | false | false | false |
ryanfowler/Lateral | Lateral.swift | 1 | 8273 | //
// Lateral.swift
// SwiftData2
//
// Created by Ryan Fowler on 2015-01-07.
// Copyright (c) 2015 Ryan Fowler. All rights reserved.
//
public class Lateral {
// MARK: async
public class func async(task: ()->Void) {
dispatch_async(dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), task)
}
// MARK: main
public class func main(task: ()->Void) {
dispatch_async(dispatch_get_main_queue(), task)
}
// MARK: for
public class func times(times: UInt, task: (UInt)->Void) {
dispatch_async(dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), {
dispatch_apply(times, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), task)
})
}
// MARK: each
public class func each<T>(array: [T], iterator: (T)->Void, callback: ()->Void) {
let dGroup = dispatch_group_create()
for item in array {
dispatch_group_async(dGroup, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), {
iterator(item)
})
}
dispatch_group_notify(dGroup, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), callback)
}
public class func each<T>(array: [T], failableIterator: (T)->Bool, callback: (Bool)->Void) {
var err = false
let dGroup = dispatch_group_create()
for item in array {
dispatch_group_async(dGroup, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), {
if !failableIterator(item) {
err = true
callback(false)
return
}
})
}
dispatch_group_notify(dGroup, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), {
if !err {
callback(true)
}
})
}
// MARK: eachSeries
public class func eachSeries<T>(array: [T], iterator: (T)->Void, callback: (Bool)->Void) {
dispatch_async(dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), {
for item in array {
iterator(item)
}
callback(true)
})
}
public class func eachSeries<T>(array: [T], failableIterator: (T)->Bool, callback: (Bool)->Void) {
dispatch_async(dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), {
for item in array {
if !failableIterator(item) {
callback(false)
return
}
}
callback(true)
})
}
// MARK: map
public class func map<T,U>(array: [T], iterator: (T)->U, callback: ([U])->Void) {
var dict: [Int: U] = [:]
let dGroup = dispatch_group_create()
for var i = 0; i < array.count; i++ {
dispatch_group_async(dGroup, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), {
dict[i] = iterator(array[i])
})
}
dispatch_group_notify(dGroup, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), {
var newArr: [U] = []
for var i = 0; i < dict.count; i++ {
newArr.append(dict[i]!)
}
callback(newArr)
})
}
public class func map<T,U>(array: [T], failableIterator: (T)->(Bool, U), callback: ([U]?)->Void) {
var dict: [Int: U] = [:]
var err = false
let dGroup = dispatch_group_create()
for var i = 0; i < array.count; i++ {
dispatch_group_async(dGroup, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), {
let (error, val) = failableIterator(array[i])
if error {
err = true
callback(nil)
return
}
dict[i] = val
})
}
dispatch_group_notify(dGroup, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), {
if !err {
var newArr: [U] = []
for var i = 0; i < dict.count; i++ {
newArr.append(dict[i]!)
}
callback(newArr)
}
})
}
// MARK: mapSeries
public class func mapSeries<T,U>(array: [T], iterator: (T)->U, callback: ([U])->Void) {
dispatch_async(dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), {
callback(array.map(iterator))
})
}
public class func mapSeries<T,U>(array: [T], failableIterator: (T)->(Bool, U), callback: ([U]?)->Void) {
dispatch_async(dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), {
var newArr: [U] = []
for item in array {
let (error, val) = failableIterator(item)
if error {
callback(nil)
break
}
newArr.append(val)
}
callback(newArr)
})
}
// MARK: series
public class func series(tasks: [()->Void]) {
dispatch_async(dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), {
for task in tasks {
task()
}
})
}
public class func series(tasks: [()->Void], callback: ()->Void) {
dispatch_async(dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), {
for task in tasks {
task()
}
callback()
})
}
public class func series(failableTasks: [()->Bool], callback: (Bool)->Void) {
dispatch_async(dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), {
for task in failableTasks {
if !task() {
callback(false)
return
}
}
callback(true)
})
}
// MARK: parallel
public class func parallel(tasks: [()->Void]) {
for task in tasks {
dispatch_async(dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), task)
}
}
public class func parallel(tasks: [()->Void], callback: ()->Void) {
let dGroup = dispatch_group_create()
for task in tasks {
dispatch_group_async(dGroup, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), task)
}
dispatch_group_notify(dGroup, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), callback)
}
public class func parallel(failableTasks: [()->Bool], callback: (Bool)->Void) {
var err = false
let dGroup = dispatch_group_create()
for task in failableTasks {
dispatch_group_async(dGroup, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), {
if !task() {
err = true
callback(false)
return
}
})
}
dispatch_group_notify(dGroup, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), {
if !err {
callback(true)
}
})
}
// MARK: waterfall
public class func waterfall<T>(initial: T, tasks: [(T)->T], callback: (T)->Void) {
dispatch_async(dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), {
var value = initial
for task in tasks {
value = task(value)
}
callback(value)
})
}
public class func waterfall<T>(initial: T?, failableTasks: [(T?)->T?], callback: (T?)->Void) {
dispatch_async(dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), {
var value = initial
for task in failableTasks {
value = task(value)
if value == nil {
callback(nil)
break
}
}
callback(value)
})
}
// MARK: retry
public class func retry(times: Int, task: ()->Bool, callback: (Bool)->Void) {
dispatch_async(dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), {
var tries = 0
while (tries < times) {
if task() {
callback(true)
return
}
tries++
}
callback(false)
})
}
}
| mit | 0aae6bc9a6bdaf3e05ebb98ebacc17ba | 29.415441 | 108 | 0.48205 | 4.167758 | false | false | false | false |
achappell/dungeonsanddragonscharactersheet | DungeonsDragonsCCTests/Models/Mapping/ModifierFEMMappingTests.swift | 1 | 2436 | //
// Modifier+FEMMappingTests.swift
// DungeonsDragonsCC
//
// Created by Amanda Chappell on 3/5/16.
// Copyright © 2016 AmplifiedProjects. All rights reserved.
//
import XCTest
@testable import DungeonsDragonsCC
class ModifierFEMMappingTests: 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 testFEMMapping() {
let deserializer = JSONDeserializer()
let modifiers = getModifiers()
let modifier = deserializer.objectFromDictionary(modifiers![0], classType: Modifier.self)! as Modifier
XCTAssertEqual(modifier.value, 0)
XCTAssertEqual(modifier.type, "Size")
XCTAssertEqual(modifier.originalText, "Dwarves are Medium creatures and have no bonuses or penalties due to their size.")
}
func testSkillMapping() {
let deserializer = JSONDeserializer()
let modifiers = getModifiers()
let modifier = deserializer.objectFromDictionary(modifiers![2], classType: Modifier.self)! as Modifier
XCTAssertEqual(modifier.value, 2)
XCTAssertEqual(modifier.type, "Skill")
XCTAssertEqual(modifier.originalText, "Dwarves receive a +2 racial bonus on Appraise skill checks made to determine the price of nonmagical goods that contain precious metals or gemstones.")
XCTAssertEqual(modifier.circumstance, "Only for nonmagical goods that contain precious metals or gemstones.")
}
func getModifiers() -> [[String:AnyObject]]? {
let bundle = Bundle(for: CoreRulebookFEMMappingTests.self)
let path = bundle.path(forResource: "testcorerulebook", ofType: "json")
let data = try? Data(contentsOf: URL(fileURLWithPath: path!))
do {
let JSONDict = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as! [String:AnyObject]
if let book = JSONDict["coreRulebook"] as? [String: AnyObject], let races = book["races"] as? [[String: AnyObject]], let modifiers = races[0]["modifiers"] as? [[String:AnyObject]] {
return modifiers
}
} catch {
}
return nil
}
}
| mit | 4c82773da7b0079c7093ad5b1d39ec4c | 36.461538 | 198 | 0.680903 | 4.559925 | false | true | false | false |
sovereignshare/fly-smuthe | Fly Smuthe/Fly Smuthe/AppDelegate.swift | 1 | 6454 | //
// AppDelegate.swift
// Fly Smuthe
//
// Created by Adam M Rivera on 8/26/15.
// Copyright (c) 2015 Adam M Rivera. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, TurbulenceStatisticRepositorySaveDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
TurbulenceStatisticRepository.sharedInstance.setContextAndSaveDelegate(managedObjectContext!, saveDelegate: self);
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// 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.sovereignshare.Fly_Smuthe" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("Fly_Smuthe", 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("Fly_Smuthe.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch var error1 as NSError {
error = error1
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)")
} catch {
fatalError()
}
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 {
do {
try moc.save()
} catch let error1 as NSError {
error = error1
// 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)")
}
}
}
}
}
| gpl-3.0 | f2740f46e49a1d7530a0e26f5f098b71 | 52.338843 | 290 | 0.70375 | 5.736889 | false | false | false | false |
pydio/t2g | Table2Grid/Classes/T2GStyle.swift | 1 | 1373 | //
// T2GStyle.swift
// Pydio
//
// Created by Leo Marcotte on 13/04/16.
// Copyright © 2016 Leo Marcotte. All rights reserved.
//
import Foundation
import UIKit
public struct T2GStyle {
public struct Node {
public static var nodeTitleColor = UIColor.black
public static var nodeTitleFont = UIFont(name: "SFUIDisplay-Regular", size: 16)
public static var nodeDescriptionColor = UIColor.gray
public static var nodeDescriptionFont = UIFont(name: "SFUIDisplay-Light", size: 13)
public static var nodeIconViewBackgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.02)
public static var nodeImageViewTintColor = UIColor(red: 119/255, green: 119/255, blue: 119/255, alpha: 1.0)
public static var nodeBackgroundViewBackgroundColor = UIColor.white
public static var nodeScrollViewBackgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.02)
public struct Collection {
public static var backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.04)
public static var whiteFooterBackgroundColor = UIColor.white
}
public struct Table {
public static var backgroundColor = UIColor(red: 0.995, green: 0.995, blue: 0.995, alpha: 1)
}
}
}
| apache-2.0 | 2a7c254c82988f1836541d45eb7a1f95 | 33.3 | 115 | 0.639213 | 4.071217 | false | false | false | false |
inderdhir/SwiftWeather | DatWeatherDoe/UI/ConfigureViewController.swift | 1 | 6791 | //
// ConfigureViewController.swift
// DatWeatherDoe
//
// Created by Inder Dhir on 1/22/16.
// Copyright © 2016 Inder Dhir. All rights reserved.
//
import Cocoa
class ConfigureViewController: NSViewController, NSTextFieldDelegate {
@IBOutlet weak var fahrenheitRadioButton: NSButton!
@IBOutlet weak var celsiusRadioButton: NSButton!
@IBOutlet weak var allTempUnitsRadioButton: NSButton!
@IBOutlet weak var useLocationToggleCheckBox: NSButton!
@IBOutlet weak var weatherSourceButton: NSPopUpButton!
@IBOutlet weak var weatherSourceTextHint: NSTextField!
@IBOutlet weak var weatherSourceTextField: NSTextField!
@IBOutlet weak var refreshIntervals: NSPopUpButton!
@IBOutlet weak var showHumidityToggleCheckBox: NSButton!
@IBOutlet weak var roundOffData: NSButton!
@IBOutlet weak var weatherConditionAsTextCheckBox: NSButton!
private let zipCodeHint = "[zipcode],[iso 3166 country code]"
private let latLongHint = "[latitude],[longitude]"
private let configManager: ConfigManagerType
init(configManager: ConfigManagerType) {
self.configManager = configManager
super.init(nibName: "ConfigureViewController", bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
fahrenheitRadioButton.title = "\u{00B0}F"
fahrenheitRadioButton.state = configManager.temperatureUnit == TemperatureUnit.fahrenheit.rawValue ? .on : .off
celsiusRadioButton.title = "\u{00B0}C"
celsiusRadioButton.state = configManager.temperatureUnit == TemperatureUnit.celsius.rawValue ? .on : .off
allTempUnitsRadioButton.title = "All"
allTempUnitsRadioButton.state = configManager.temperatureUnit == TemperatureUnit.all.rawValue ? .on : .off
refreshIntervals.removeAllItems()
refreshIntervals.addItems(withTitles: RefreshInterval.allCases.map(\.title))
switch configManager.refreshInterval {
case 300: refreshIntervals.selectItem(at: 1)
case 900: refreshIntervals.selectItem(at: 2)
case 1800: refreshIntervals.selectItem(at: 3)
case 3600: refreshIntervals.selectItem(at: 4)
default: refreshIntervals.selectItem(at: 0)
}
weatherSourceButton.removeAllItems()
weatherSourceButton.addItems(withTitles: WeatherSource.allCases.map(\.title))
let selectedIndex: Int
switch WeatherSource(rawValue: configManager.weatherSource) {
case .latLong:
weatherSourceTextHint.stringValue = latLongHint
selectedIndex = 1
case .zipCode:
weatherSourceTextHint.stringValue = zipCodeHint
selectedIndex = 2
default:
selectedIndex = 0
}
weatherSourceButton.selectItem(at: selectedIndex)
weatherSourceTextField.isEnabled = selectedIndex != 0
if let weatherSourceText = configManager.weatherSourceText {
weatherSourceTextField.stringValue = weatherSourceText
}
showHumidityToggleCheckBox.state = configManager.isShowingHumidity ? .on : .off
roundOffData.state = configManager.isRoundingOffData ? .on : .off
weatherConditionAsTextCheckBox.state = configManager.isWeatherConditionAsTextEnabled ? .on : .off
}
@IBAction func radioButtonClicked(_ sender: NSButton) {
DispatchQueue.main.async { [weak self] in
guard let strongSelf = self else { return }
strongSelf.fahrenheitRadioButton.state = sender == strongSelf.fahrenheitRadioButton ? .on : .off
strongSelf.celsiusRadioButton.state = sender == strongSelf.celsiusRadioButton ? .on : .off
strongSelf.allTempUnitsRadioButton.state = sender == strongSelf.allTempUnitsRadioButton ? .on : .off
}
}
@IBAction func doneButtonPressed(_ sender: AnyObject) {
DispatchQueue.main.async { [weak self] in
guard let strongSelf = self else { return }
switch (
strongSelf.fahrenheitRadioButton.state,
strongSelf.celsiusRadioButton.state,
strongSelf.allTempUnitsRadioButton.state
) {
case (.off, .on, .off):
strongSelf.configManager.temperatureUnit = TemperatureUnit.celsius.rawValue
case (.off, .off, .on):
strongSelf.configManager.temperatureUnit = TemperatureUnit.all.rawValue
default:
strongSelf.configManager.temperatureUnit = TemperatureUnit.fahrenheit.rawValue
}
let selectedWeatherSource = WeatherSource.allCases[strongSelf.weatherSourceButton.indexOfSelectedItem]
strongSelf.configManager.weatherSource = selectedWeatherSource.rawValue
strongSelf.configManager.weatherSourceText = selectedWeatherSource == .location ? nil : strongSelf.weatherSourceTextField.stringValue
strongSelf.configManager.refreshInterval = RefreshInterval.allCases[strongSelf.refreshIntervals.indexOfSelectedItem].rawValue
strongSelf.configManager.isShowingHumidity = strongSelf.showHumidityToggleCheckBox.state == .on
strongSelf.configManager.isRoundingOffData = strongSelf.roundOffData.state == .on
strongSelf.configManager.isWeatherConditionAsTextEnabled = strongSelf.weatherConditionAsTextCheckBox.state == .on
guard let delegate = NSApplication.shared.delegate as? AppDelegate else { return }
delegate.togglePopover(sender)
}
}
@IBAction func didUpdateWeatherSource(_ sender: Any) {
DispatchQueue.main.async { [weak self] in
guard let strongSelf = self else { return }
strongSelf.weatherSourceTextField.placeholderString = nil
strongSelf.weatherSourceTextField.stringValue = ""
let selectedWeatherSource = WeatherSource.allCases[strongSelf.weatherSourceButton.indexOfSelectedItem]
strongSelf.weatherSourceTextField.isEnabled = selectedWeatherSource != .location
guard selectedWeatherSource != .location else {
strongSelf.weatherSourceTextHint.stringValue = ""
return
}
switch selectedWeatherSource {
case .latLong:
strongSelf.weatherSourceTextHint.stringValue = strongSelf.latLongHint
strongSelf.weatherSourceTextField.placeholderString = "42,42"
case .zipCode:
strongSelf.weatherSourceTextHint.stringValue = strongSelf.zipCodeHint
strongSelf.weatherSourceTextField.placeholderString = "10021,us"
default:
break
}
}
}
}
| apache-2.0 | e7d3572d0e741493aca2ab558106093e | 44.57047 | 145 | 0.689838 | 5.239198 | false | true | false | false |
JuanjoArreola/Apic | Sources/BaseRepository.swift | 1 | 2847 | import Foundation
import AsyncRequest
open class BaseRepository {
let repositorySessionDelegate: RepositorySessionDataDelegate?
let boundary = "Boundary-\(UUID().uuidString)"
open var cachePolicy: URLRequest.CachePolicy?
open var timeoutInterval: TimeInterval?
open var allowsCellularAccess: Bool?
open var session: URLSession?
public init(repositorySessionDelegate: RepositorySessionDataDelegate? = nil) {
self.repositorySessionDelegate = repositorySessionDelegate
}
public func doRequest(route: Route, parameters: RequestParameters?, completion: @escaping (_ data: Data?, _ response: URLResponse?, _ error: Error?) -> Void) throws -> URLSessionDataTask {
if let error = parameters?.error {
throw error
}
try parameters?.preprocess()
var request = URLRequest(url: try route.getURL())
request.httpMethod = route.httpMethod
request.cachePolicy = cachePolicy ?? request.cachePolicy
request.timeoutInterval = timeoutInterval ?? request.timeoutInterval
request.allowsCellularAccess = allowsCellularAccess ?? request.allowsCellularAccess
parameters?.headers.forEach({ request.addValue($0.value, forHTTPHeaderField: $0.key) })
if let params = parameters {
try setParameters(params, to: &request, route: route)
}
return dataTask(with: request, completion: completion)
}
func setParameters(_ parameters: RequestParameters, to request: inout URLRequest, route: Route) throws {
if let data = parameters.data {
request.httpBody = data
} else if let partData = try parameters.getData(withBoundary: boundary) {
var data = try parameters.parameters?.encode(withBoundary: boundary) ?? Data()
data.append(partData)
request.httpBody = data
request.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
} else if let params = parameters.parameters {
let encoding = parameters.encoding ?? route.preferredParameterEncoding
try request.encode(parameters: params, with: encoding)
}
}
@inline(__always) func dataTask(with request: URLRequest, completion: @escaping (_ data: Data?, _ response: URLResponse?, _ error: Error?) -> Void) -> URLSessionDataTask {
let session = self.session ?? URLSession.shared
let task: URLSessionDataTask
if let delegate = repositorySessionDelegate {
task = session.dataTask(with: request)
delegate.add(completion: completion, for: task)
} else {
task = session.dataTask(with: request, completionHandler: completion)
}
task.resume()
return task
}
}
| mit | 9dc4c0ecde4586a3dadbdf043ea14e59 | 42.136364 | 192 | 0.661398 | 5.371698 | false | false | false | false |
ilhanadiyaman/firefox-ios | Client/Frontend/Browser/ShareExtensionHelper.swift | 2 | 5434 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
private let log = Logger.browserLogger
class ShareExtensionHelper: NSObject {
private let selectedTab: Browser
private var onePasswordExtensionItem: NSExtensionItem!
init(tab: Browser) {
selectedTab = tab
}
func createActivityViewController(completionHandler: () -> Void) -> UIActivityViewController {
let printInfo = UIPrintInfo(dictionary: nil)
let url = selectedTab.url!
printInfo.jobName = url.absoluteString
printInfo.outputType = .General
let renderer = BrowserPrintPageRenderer(browser: selectedTab)
var activityItems = [printInfo, renderer]
if let title = selectedTab.title {
activityItems.append(TitleActivityItemProvider(title: title))
}
activityItems.append(self)
let activityViewController = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
// Hide 'Add to Reading List' which currently uses Safari.
// Also hide our own View Later… after all, you're in the browser!
let viewLater = NSBundle.mainBundle().bundleIdentifier! + ".ViewLater"
activityViewController.excludedActivityTypes = [
UIActivityTypeAddToReadingList,
viewLater, // Doesn't work: rdar://19430419
]
// This needs to be ready by the time the share menu has been displayed and
// activityViewController(activityViewController:, activityType:) is called,
// which is after the user taps the button. So a million cycles away.
if (ShareExtensionHelper.isPasswordManagerExtensionAvailable()) {
findLoginExtensionItem()
}
activityViewController.completionWithItemsHandler = { activityType, completed, returnedItems, activityError in
if !completed {
return
}
if self.isPasswordManagerActivityType(activityType) {
if let logins = returnedItems {
self.fillPasswords(logins)
}
}
completionHandler()
}
return activityViewController
}
}
extension ShareExtensionHelper: UIActivityItemSource {
func activityViewControllerPlaceholderItem(activityViewController: UIActivityViewController) -> AnyObject {
return selectedTab.displayURL!
}
func activityViewController(activityViewController: UIActivityViewController, itemForActivityType activityType: String) -> AnyObject? {
if isPasswordManagerActivityType(activityType) {
// Return the 1Password extension item
return onePasswordExtensionItem
} else {
// Return the URL for the selected tab. If we are in reader view then decode
// it so that we copy the original and not the internal localhost one.
if let url = selectedTab.displayURL where ReaderModeUtils.isReaderModeURL(url) {
return ReaderModeUtils.decodeURL(url)
}
return selectedTab.displayURL
}
}
func activityViewController(activityViewController: UIActivityViewController, dataTypeIdentifierForActivityType activityType: String?) -> String {
// Because of our UTI declaration, this UTI now satisfies both the 1Password Extension and the usual NSURL for Share extensions.
return "org.appextension.fill-browser-action"
}
}
private extension ShareExtensionHelper {
static func isPasswordManagerExtensionAvailable() -> Bool {
return OnePasswordExtension.sharedExtension().isAppExtensionAvailable()
}
func isPasswordManagerActivityType(activityType: String?) -> Bool {
if (!ShareExtensionHelper.isPasswordManagerExtensionAvailable()) {
return false
}
// A 'password' substring covers the most cases, such as pwsafe and 1Password.
// com.agilebits.onepassword-ios.extension
// com.app77.ios.pwsafe2.find-login-action-password-actionExtension
// If your extension's bundle identifier does not contain "password", simply submit a pull request by adding your bundle idenfidier.
return (activityType!.rangeOfString("password") != nil)
|| (activityType == "com.lastpass.ilastpass.LastPassExt")
}
func findLoginExtensionItem() {
// Add 1Password to share sheet
OnePasswordExtension.sharedExtension().createExtensionItemForWebView(selectedTab.webView!, completion: {(extensionItem, error) -> Void in
if extensionItem == nil {
log.error("Failed to create the password manager extension item: \(error).")
return
}
// Set the 1Password extension item property
self.onePasswordExtensionItem = extensionItem
})
}
func fillPasswords(returnedItems: [AnyObject]) {
OnePasswordExtension.sharedExtension().fillReturnedItems(returnedItems, intoWebView: self.selectedTab.webView!, completion: { (success, returnedItemsError) -> Void in
if !success {
log.error("Failed to fill item into webview: \(returnedItemsError).")
}
})
}
}
| mpl-2.0 | 47071f7da8c81ce3e915ae144ffbf9fc | 41.4375 | 174 | 0.675074 | 5.803419 | false | false | false | false |
hani-ibrahim/SlicingImage | SlicingImage/SlicingImage/TranslationAnimator.swift | 1 | 1389 | //
// TranslationAnimator.swift
// SlicingImage
//
// Created by Hani Ibrahim on 7/25/17.
// Copyright © 2017 Hani Ibrahim. All rights reserved.
//
import UIKit
public class TranslationAnimator {
private let direction: Direction
public enum Direction {
case top
case right
case bottom
case left
}
public init(direction: Direction) {
self.direction = direction
}
}
extension TranslationAnimator: Animator {
public func update(progress: CGFloat, for slices: [Slice]) {
slices.enumerated().forEach { (idx, slice) in
let position = (progress - slice.progressRange.upperBound) / (slice.progressRange.upperBound - slice.progressRange.lowerBound)
let relativePosition = min(max(position, -1), 0)
switch direction {
case .top: slice.view.transform = CGAffineTransform(translationX: 0, y: -relativePosition * slice.view.frame.height)
case .right: slice.view.transform = CGAffineTransform(translationX: relativePosition * slice.view.frame.width, y: 0)
case .bottom: slice.view.transform = CGAffineTransform(translationX: 0, y: relativePosition * slice.view.frame.height)
case .left: slice.view.transform = CGAffineTransform(translationX: -relativePosition * slice.view.frame.width, y: 0)
}
}
}
}
| mit | e5d303d463a79e7de3f5833096c7c8ab | 33.7 | 138 | 0.659222 | 4.392405 | false | false | false | false |
practicalswift/swift | stdlib/public/core/UnsafePointer.swift | 3 | 42234 | //===--- UnsafePointer.swift ----------------------------------*- swift -*-===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// A pointer for accessing data of a
/// specific type.
///
/// You use instances of the `UnsafePointer` type to access data of a
/// specific type in memory. The type of data that a pointer can access is the
/// pointer's `Pointee` type. `UnsafePointer` provides no automated
/// memory management or alignment guarantees. You are responsible for
/// handling the life cycle of any memory you work with through unsafe
/// pointers to avoid leaks or undefined behavior.
///
/// Memory that you manually manage can be either *untyped* or *bound* to a
/// specific type. You use the `UnsafePointer` type to access and
/// manage memory that has been bound to a specific type.
///
/// Understanding a Pointer's Memory State
/// ======================================
///
/// The memory referenced by an `UnsafePointer` instance can be in
/// one of several states. Many pointer operations must only be applied to
/// pointers with memory in a specific state---you must keep track of the
/// state of the memory you are working with and understand the changes to
/// that state that different operations perform. Memory can be untyped and
/// uninitialized, bound to a type and uninitialized, or bound to a type and
/// initialized to a value. Finally, memory that was allocated previously may
/// have been deallocated, leaving existing pointers referencing unallocated
/// memory.
///
/// Uninitialized Memory
/// --------------------
///
/// Memory that has just been allocated through a typed pointer or has been
/// deinitialized is in an *uninitialized* state. Uninitialized memory must be
/// initialized before it can be accessed for reading.
///
/// Initialized Memory
/// ------------------
///
/// *Initialized* memory has a value that can be read using a pointer's
/// `pointee` property or through subscript notation. In the following
/// example, `ptr` is a pointer to memory initialized with a value of `23`:
///
/// let ptr: UnsafePointer<Int> = ...
/// // ptr.pointee == 23
/// // ptr[0] == 23
///
/// Accessing a Pointer's Memory as a Different Type
/// ================================================
///
/// When you access memory through an `UnsafePointer` instance, the
/// `Pointee` type must be consistent with the bound type of the memory. If
/// you do need to access memory that is bound to one type as a different
/// type, Swift's pointer types provide type-safe ways to temporarily or
/// permanently change the bound type of the memory, or to load typed
/// instances directly from raw memory.
///
/// An `UnsafePointer<UInt8>` instance allocated with eight bytes of
/// memory, `uint8Pointer`, will be used for the examples below.
///
/// let uint8Pointer: UnsafePointer<UInt8> = fetchEightBytes()
///
/// When you only need to temporarily access a pointer's memory as a different
/// type, use the `withMemoryRebound(to:capacity:)` method. For example, you
/// can use this method to call an API that expects a pointer to a different
/// type that is layout compatible with your pointer's `Pointee`. The following
/// code temporarily rebinds the memory that `uint8Pointer` references from
/// `UInt8` to `Int8` to call the imported C `strlen` function.
///
/// // Imported from C
/// func strlen(_ __s: UnsafePointer<Int8>!) -> UInt
///
/// let length = uint8Pointer.withMemoryRebound(to: Int8.self, capacity: 8) {
/// return strlen($0)
/// }
/// // length == 7
///
/// When you need to permanently rebind memory to a different type, first
/// obtain a raw pointer to the memory and then call the
/// `bindMemory(to:capacity:)` method on the raw pointer. The following
/// example binds the memory referenced by `uint8Pointer` to one instance of
/// the `UInt64` type:
///
/// let uint64Pointer = UnsafeRawPointer(uint8Pointer)
/// .bindMemory(to: UInt64.self, capacity: 1)
///
/// After rebinding the memory referenced by `uint8Pointer` to `UInt64`,
/// accessing that pointer's referenced memory as a `UInt8` instance is
/// undefined.
///
/// var fullInteger = uint64Pointer.pointee // OK
/// var firstByte = uint8Pointer.pointee // undefined
///
/// Alternatively, you can access the same memory as a different type without
/// rebinding through untyped memory access, so long as the bound type and the
/// destination type are trivial types. Convert your pointer to an
/// `UnsafeRawPointer` instance and then use the raw pointer's
/// `load(fromByteOffset:as:)` method to read values.
///
/// let rawPointer = UnsafeRawPointer(uint64Pointer)
/// fullInteger = rawPointer.load(as: UInt64.self) // OK
/// firstByte = rawPointer.load(as: UInt8.self) // OK
///
/// Performing Typed Pointer Arithmetic
/// ===================================
///
/// Pointer arithmetic with a typed pointer is counted in strides of the
/// pointer's `Pointee` type. When you add to or subtract from an `UnsafePointer`
/// instance, the result is a new pointer of the same type, offset by that
/// number of instances of the `Pointee` type.
///
/// // 'intPointer' points to memory initialized with [10, 20, 30, 40]
/// let intPointer: UnsafePointer<Int> = ...
///
/// // Load the first value in memory
/// let x = intPointer.pointee
/// // x == 10
///
/// // Load the third value in memory
/// let offsetPointer = intPointer + 2
/// let y = offsetPointer.pointee
/// // y == 30
///
/// You can also use subscript notation to access the value in memory at a
/// specific offset.
///
/// let z = intPointer[2]
/// // z == 30
///
/// Implicit Casting and Bridging
/// =============================
///
/// When calling a function or method with an `UnsafePointer` parameter, you can pass
/// an instance of that specific pointer type, pass an instance of a
/// compatible pointer type, or use Swift's implicit bridging to pass a
/// compatible pointer.
///
/// For example, the `printInt(atAddress:)` function in the following code
/// sample expects an `UnsafePointer<Int>` instance as its first parameter:
///
/// func printInt(atAddress p: UnsafePointer<Int>) {
/// print(p.pointee)
/// }
///
/// As is typical in Swift, you can call the `printInt(atAddress:)` function
/// with an `UnsafePointer` instance. This example passes `intPointer`, a pointer to
/// an `Int` value, to `print(address:)`.
///
/// printInt(atAddress: intPointer)
/// // Prints "42"
///
/// Because a mutable typed pointer can be implicitly cast to an immutable
/// pointer with the same `Pointee` type when passed as a parameter, you can
/// also call `printInt(atAddress:)` with an `UnsafeMutablePointer` instance.
///
/// let mutableIntPointer = UnsafeMutablePointer(mutating: intPointer)
/// printInt(atAddress: mutableIntPointer)
/// // Prints "42"
///
/// Alternatively, you can use Swift's *implicit bridging* to pass a pointer to
/// an instance or to the elements of an array. The following example passes a
/// pointer to the `value` variable by using inout syntax:
///
/// var value: Int = 23
/// printInt(atAddress: &value)
/// // Prints "23"
///
/// An immutable pointer to the elements of an array is implicitly created when
/// you pass the array as an argument. This example uses implicit bridging to
/// pass a pointer to the elements of `numbers` when calling
/// `printInt(atAddress:)`.
///
/// let numbers = [5, 10, 15, 20]
/// printInt(atAddress: numbers)
/// // Prints "5"
///
/// You can also use inout syntax to pass a mutable pointer to the elements of
/// an array. Because `printInt(atAddress:)` requires an immutable pointer,
/// although this is syntactically valid, it isn't necessary.
///
/// var mutableNumbers = numbers
/// printInt(atAddress: &mutableNumbers)
///
/// No matter which way you call `printInt(atAddress:)`, Swift's type safety
/// guarantees that you can only pass a pointer to the type required by the
/// function---in this case, a pointer to an `Int`.
///
/// - Important: The pointer created through implicit bridging of an instance
/// or of an array's elements is only valid during the execution of the
/// called function. Escaping the pointer to use after the execution of the
/// function is undefined behavior. In particular, do not use implicit
/// bridging when calling an `UnsafePointer` initializer.
///
/// var number = 5
/// let numberPointer = UnsafePointer<Int>(&number)
/// // Accessing 'numberPointer' is undefined behavior.
@_fixed_layout // unsafe-performance
public struct UnsafePointer<Pointee>: _Pointer {
/// A type that represents the distance between two pointers.
public typealias Distance = Int
/// The underlying raw (untyped) pointer.
public let _rawValue: Builtin.RawPointer
/// Creates an `UnsafePointer` from a builtin raw pointer.
@_transparent
public init(_ _rawValue : Builtin.RawPointer) {
self._rawValue = _rawValue
}
/// Deallocates the memory block previously allocated at this pointer.
///
/// This pointer must be a pointer to the start of a previously allocated memory
/// block. The memory must not be initialized or `Pointee` must be a trivial type.
@inlinable
public func deallocate() {
// Passing zero alignment to the runtime forces "aligned
// deallocation". Since allocation via `UnsafeMutable[Raw][Buffer]Pointer`
// always uses the "aligned allocation" path, this ensures that the
// runtime's allocation and deallocation paths are compatible.
Builtin.deallocRaw(_rawValue, (-1)._builtinWordValue, (0)._builtinWordValue)
}
/// Accesses the instance referenced by this pointer.
///
/// When reading from the `pointee` property, the instance referenced by
/// this pointer must already be initialized.
@inlinable // unsafe-performance
public var pointee: Pointee {
@_transparent unsafeAddress {
return self
}
}
/// Executes the given closure while temporarily binding the specified number
/// of instances to the given type.
///
/// Use this method when you have a pointer to memory bound to one type and
/// you need to access that memory as instances of another type. Accessing
/// memory as a type `T` requires that the memory be bound to that type. A
/// memory location may only be bound to one type at a time, so accessing
/// the same memory as an unrelated type without first rebinding the memory
/// is undefined.
///
/// The region of memory starting at this pointer and covering `count`
/// instances of the pointer's `Pointee` type must be initialized.
///
/// The following example temporarily rebinds the memory of a `UInt64`
/// pointer to `Int64`, then accesses a property on the signed integer.
///
/// let uint64Pointer: UnsafePointer<UInt64> = fetchValue()
/// let isNegative = uint64Pointer.withMemoryRebound(to: Int64.self) { ptr in
/// return ptr.pointee < 0
/// }
///
/// Because this pointer's memory is no longer bound to its `Pointee` type
/// while the `body` closure executes, do not access memory using the
/// original pointer from within `body`. Instead, use the `body` closure's
/// pointer argument to access the values in memory as instances of type
/// `T`.
///
/// After executing `body`, this method rebinds memory back to the original
/// `Pointee` type.
///
/// - Note: Only use this method to rebind the pointer's memory to a type
/// with the same size and stride as the currently bound `Pointee` type.
/// To bind a region of memory to a type that is a different size, convert
/// the pointer to a raw pointer and use the `bindMemory(to:capacity:)`
/// method.
///
/// - Parameters:
/// - type: The type to temporarily bind the memory referenced by this
/// pointer. The type `T` must be the same size and be layout compatible
/// with the pointer's `Pointee` type.
/// - count: The number of instances of `Pointee` to bind to `type`.
/// - body: A closure that takes a typed pointer to the
/// same memory as this pointer, only bound to type `T`. The closure's
/// pointer argument is valid only for the duration of the closure's
/// execution. If `body` has a return value, that value is also used as
/// the return value for the `withMemoryRebound(to:capacity:_:)` method.
/// - Returns: The return value, if any, of the `body` closure parameter.
@inlinable
public func withMemoryRebound<T, Result>(to type: T.Type, capacity count: Int,
_ body: (UnsafePointer<T>) throws -> Result
) rethrows -> Result {
Builtin.bindMemory(_rawValue, count._builtinWordValue, T.self)
defer {
Builtin.bindMemory(_rawValue, count._builtinWordValue, Pointee.self)
}
return try body(UnsafePointer<T>(_rawValue))
}
/// Accesses the pointee at the specified offset from this pointer.
///
///
/// For a pointer `p`, the memory at `p + i` must be initialized.
///
/// - Parameter i: The offset from this pointer at which to access an
/// instance, measured in strides of the pointer's `Pointee` type.
@inlinable
public subscript(i: Int) -> Pointee {
@_transparent
unsafeAddress {
return self + i
}
}
@inlinable // unsafe-performance
internal static var _max : UnsafePointer {
return UnsafePointer(
bitPattern: 0 as Int &- MemoryLayout<Pointee>.stride
)._unsafelyUnwrappedUnchecked
}
}
/// A pointer for accessing and manipulating data of a
/// specific type.
///
/// You use instances of the `UnsafeMutablePointer` type to access data of a
/// specific type in memory. The type of data that a pointer can access is the
/// pointer's `Pointee` type. `UnsafeMutablePointer` provides no automated
/// memory management or alignment guarantees. You are responsible for
/// handling the life cycle of any memory you work with through unsafe
/// pointers to avoid leaks or undefined behavior.
///
/// Memory that you manually manage can be either *untyped* or *bound* to a
/// specific type. You use the `UnsafeMutablePointer` type to access and
/// manage memory that has been bound to a specific type.
///
/// Understanding a Pointer's Memory State
/// ======================================
///
/// The memory referenced by an `UnsafeMutablePointer` instance can be in
/// one of several states. Many pointer operations must only be applied to
/// pointers with memory in a specific state---you must keep track of the
/// state of the memory you are working with and understand the changes to
/// that state that different operations perform. Memory can be untyped and
/// uninitialized, bound to a type and uninitialized, or bound to a type and
/// initialized to a value. Finally, memory that was allocated previously may
/// have been deallocated, leaving existing pointers referencing unallocated
/// memory.
///
/// Uninitialized Memory
/// --------------------
///
/// Memory that has just been allocated through a typed pointer or has been
/// deinitialized is in an *uninitialized* state. Uninitialized memory must be
/// initialized before it can be accessed for reading.
///
/// You can use methods like `initialize(to:count:)`, `initialize(from:count:)`,
/// and `moveInitialize(from:count:)` to initialize the memory referenced by a
/// pointer with a value or series of values.
///
/// Initialized Memory
/// ------------------
///
/// *Initialized* memory has a value that can be read using a pointer's
/// `pointee` property or through subscript notation. In the following
/// example, `ptr` is a pointer to memory initialized with a value of `23`:
///
/// let ptr: UnsafeMutablePointer<Int> = ...
/// // ptr.pointee == 23
/// // ptr[0] == 23
///
/// Accessing a Pointer's Memory as a Different Type
/// ================================================
///
/// When you access memory through an `UnsafeMutablePointer` instance, the
/// `Pointee` type must be consistent with the bound type of the memory. If
/// you do need to access memory that is bound to one type as a different
/// type, Swift's pointer types provide type-safe ways to temporarily or
/// permanently change the bound type of the memory, or to load typed
/// instances directly from raw memory.
///
/// An `UnsafeMutablePointer<UInt8>` instance allocated with eight bytes of
/// memory, `uint8Pointer`, will be used for the examples below.
///
/// var bytes: [UInt8] = [39, 77, 111, 111, 102, 33, 39, 0]
/// let uint8Pointer = UnsafeMutablePointer<UInt8>.allocate(capacity: 8)
/// uint8Pointer.initialize(from: &bytes, count: 8)
///
/// When you only need to temporarily access a pointer's memory as a different
/// type, use the `withMemoryRebound(to:capacity:)` method. For example, you
/// can use this method to call an API that expects a pointer to a different
/// type that is layout compatible with your pointer's `Pointee`. The following
/// code temporarily rebinds the memory that `uint8Pointer` references from
/// `UInt8` to `Int8` to call the imported C `strlen` function.
///
/// // Imported from C
/// func strlen(_ __s: UnsafePointer<Int8>!) -> UInt
///
/// let length = uint8Pointer.withMemoryRebound(to: Int8.self, capacity: 8) {
/// return strlen($0)
/// }
/// // length == 7
///
/// When you need to permanently rebind memory to a different type, first
/// obtain a raw pointer to the memory and then call the
/// `bindMemory(to:capacity:)` method on the raw pointer. The following
/// example binds the memory referenced by `uint8Pointer` to one instance of
/// the `UInt64` type:
///
/// let uint64Pointer = UnsafeMutableRawPointer(uint8Pointer)
/// .bindMemory(to: UInt64.self, capacity: 1)
///
/// After rebinding the memory referenced by `uint8Pointer` to `UInt64`,
/// accessing that pointer's referenced memory as a `UInt8` instance is
/// undefined.
///
/// var fullInteger = uint64Pointer.pointee // OK
/// var firstByte = uint8Pointer.pointee // undefined
///
/// Alternatively, you can access the same memory as a different type without
/// rebinding through untyped memory access, so long as the bound type and the
/// destination type are trivial types. Convert your pointer to an
/// `UnsafeMutableRawPointer` instance and then use the raw pointer's
/// `load(fromByteOffset:as:)` and `storeBytes(of:toByteOffset:as:)` methods
/// to read and write values.
///
/// let rawPointer = UnsafeMutableRawPointer(uint64Pointer)
/// fullInteger = rawPointer.load(as: UInt64.self) // OK
/// firstByte = rawPointer.load(as: UInt8.self) // OK
///
/// Performing Typed Pointer Arithmetic
/// ===================================
///
/// Pointer arithmetic with a typed pointer is counted in strides of the
/// pointer's `Pointee` type. When you add to or subtract from an `UnsafeMutablePointer`
/// instance, the result is a new pointer of the same type, offset by that
/// number of instances of the `Pointee` type.
///
/// // 'intPointer' points to memory initialized with [10, 20, 30, 40]
/// let intPointer: UnsafeMutablePointer<Int> = ...
///
/// // Load the first value in memory
/// let x = intPointer.pointee
/// // x == 10
///
/// // Load the third value in memory
/// let offsetPointer = intPointer + 2
/// let y = offsetPointer.pointee
/// // y == 30
///
/// You can also use subscript notation to access the value in memory at a
/// specific offset.
///
/// let z = intPointer[2]
/// // z == 30
///
/// Implicit Casting and Bridging
/// =============================
///
/// When calling a function or method with an `UnsafeMutablePointer` parameter, you can pass
/// an instance of that specific pointer type or use Swift's implicit bridging
/// to pass a compatible pointer.
///
/// For example, the `printInt(atAddress:)` function in the following code
/// sample expects an `UnsafeMutablePointer<Int>` instance as its first parameter:
///
/// func printInt(atAddress p: UnsafeMutablePointer<Int>) {
/// print(p.pointee)
/// }
///
/// As is typical in Swift, you can call the `printInt(atAddress:)` function
/// with an `UnsafeMutablePointer` instance. This example passes `intPointer`, a mutable
/// pointer to an `Int` value, to `print(address:)`.
///
/// printInt(atAddress: intPointer)
/// // Prints "42"
///
/// Alternatively, you can use Swift's *implicit bridging* to pass a pointer to
/// an instance or to the elements of an array. The following example passes a
/// pointer to the `value` variable by using inout syntax:
///
/// var value: Int = 23
/// printInt(atAddress: &value)
/// // Prints "23"
///
/// A mutable pointer to the elements of an array is implicitly created when
/// you pass the array using inout syntax. This example uses implicit bridging
/// to pass a pointer to the elements of `numbers` when calling
/// `printInt(atAddress:)`.
///
/// var numbers = [5, 10, 15, 20]
/// printInt(atAddress: &numbers)
/// // Prints "5"
///
/// No matter which way you call `printInt(atAddress:)`, Swift's type safety
/// guarantees that you can only pass a pointer to the type required by the
/// function---in this case, a pointer to an `Int`.
///
/// - Important: The pointer created through implicit bridging of an instance
/// or of an array's elements is only valid during the execution of the
/// called function. Escaping the pointer to use after the execution of the
/// function is undefined behavior. In particular, do not use implicit
/// bridging when calling an `UnsafeMutablePointer` initializer.
///
/// var number = 5
/// let numberPointer = UnsafeMutablePointer<Int>(&number)
/// // Accessing 'numberPointer' is undefined behavior.
@_fixed_layout // unsafe-performance
public struct UnsafeMutablePointer<Pointee>: _Pointer {
/// A type that represents the distance between two pointers.
public typealias Distance = Int
/// The underlying raw (untyped) pointer.
public let _rawValue: Builtin.RawPointer
/// Creates an `UnsafeMutablePointer` from a builtin raw pointer.
@_transparent
public init(_ _rawValue : Builtin.RawPointer) {
self._rawValue = _rawValue
}
/// Creates a mutable typed pointer referencing the same memory as the given
/// immutable pointer.
///
/// - Parameter other: The immutable pointer to convert.
@_transparent
public init(mutating other: UnsafePointer<Pointee>) {
self._rawValue = other._rawValue
}
/// Creates a mutable typed pointer referencing the same memory as the given
/// immutable pointer.
///
/// - Parameter other: The immutable pointer to convert. If `other` is `nil`,
/// the result is `nil`.
@_transparent
public init?(mutating other: UnsafePointer<Pointee>?) {
guard let unwrapped = other else { return nil }
self.init(mutating: unwrapped)
}
/// Creates an immutable typed pointer referencing the same memory as the
/// given mutable pointer.
///
/// - Parameter other: The pointer to convert.
@_transparent
public init(_ other: UnsafeMutablePointer<Pointee>) {
self._rawValue = other._rawValue
}
/// Creates an immutable typed pointer referencing the same memory as the
/// given mutable pointer.
///
/// - Parameter other: The pointer to convert. If `other` is `nil`, the
/// result is `nil`.
@_transparent
public init?(_ other: UnsafeMutablePointer<Pointee>?) {
guard let unwrapped = other else { return nil }
self.init(unwrapped)
}
/// Allocates uninitialized memory for the specified number of instances of
/// type `Pointee`.
///
/// The resulting pointer references a region of memory that is bound to
/// `Pointee` and is `count * MemoryLayout<Pointee>.stride` bytes in size.
///
/// The following example allocates enough new memory to store four `Int`
/// instances and then initializes that memory with the elements of a range.
///
/// let intPointer = UnsafeMutablePointer<Int>.allocate(capacity: 4)
/// for i in 0..<4 {
/// (intPointer + i).initialize(to: i)
/// }
/// print(intPointer.pointee)
/// // Prints "0"
///
/// When you allocate memory, always remember to deallocate once you're
/// finished.
///
/// intPointer.deallocate()
///
/// - Parameter count: The amount of memory to allocate, counted in instances
/// of `Pointee`.
@inlinable
public static func allocate(capacity count: Int)
-> UnsafeMutablePointer<Pointee> {
let size = MemoryLayout<Pointee>.stride * count
// For any alignment <= _minAllocationAlignment, force alignment = 0.
// This forces the runtime's "aligned" allocation path so that
// deallocation does not require the original alignment.
//
// The runtime guarantees:
//
// align == 0 || align > _minAllocationAlignment:
// Runtime uses "aligned allocation".
//
// 0 < align <= _minAllocationAlignment:
// Runtime may use either malloc or "aligned allocation".
var align = Builtin.alignof(Pointee.self)
if Int(align) <= _minAllocationAlignment() {
align = (0)._builtinWordValue
}
let rawPtr = Builtin.allocRaw(size._builtinWordValue, align)
Builtin.bindMemory(rawPtr, count._builtinWordValue, Pointee.self)
return UnsafeMutablePointer(rawPtr)
}
/// Deallocates the memory block previously allocated at this pointer.
///
/// This pointer must be a pointer to the start of a previously allocated memory
/// block. The memory must not be initialized or `Pointee` must be a trivial type.
@inlinable
public func deallocate() {
// Passing zero alignment to the runtime forces "aligned
// deallocation". Since allocation via `UnsafeMutable[Raw][Buffer]Pointer`
// always uses the "aligned allocation" path, this ensures that the
// runtime's allocation and deallocation paths are compatible.
Builtin.deallocRaw(_rawValue, (-1)._builtinWordValue, (0)._builtinWordValue)
}
/// Accesses the instance referenced by this pointer.
///
/// When reading from the `pointee` property, the instance referenced by this
/// pointer must already be initialized. When `pointee` is used as the left
/// side of an assignment, the instance must be initialized or this
/// pointer's `Pointee` type must be a trivial type.
///
/// Do not assign an instance of a nontrivial type through `pointee` to
/// uninitialized memory. Instead, use an initializing method, such as
/// `initialize(to:count:)`.
@inlinable // unsafe-performance
public var pointee: Pointee {
@_transparent unsafeAddress {
return UnsafePointer(self)
}
@_transparent nonmutating unsafeMutableAddress {
return self
}
}
/// Initializes this pointer's memory with the specified number of
/// consecutive copies of the given value.
///
/// The destination memory must be uninitialized or the pointer's `Pointee`
/// must be a trivial type. After a call to `initialize(repeating:count:)`, the
/// memory referenced by this pointer is initialized.
///
/// - Parameters:
/// - repeatedValue: The instance to initialize this pointer's memory with.
/// - count: The number of consecutive copies of `newValue` to initialize.
/// `count` must not be negative.
@inlinable
public func initialize(repeating repeatedValue: Pointee, count: Int) {
// FIXME: add tests (since the `count` has been added)
_debugPrecondition(count >= 0,
"UnsafeMutablePointer.initialize(repeating:count:): negative count")
// Must not use `initializeFrom` with a `Collection` as that will introduce
// a cycle.
for offset in 0..<count {
Builtin.initialize(repeatedValue, (self + offset)._rawValue)
}
}
/// Initializes this pointer's memory with a single instance of the given value.
///
/// The destination memory must be uninitialized or the pointer's `Pointee`
/// must be a trivial type. After a call to `initialize(to:)`, the
/// memory referenced by this pointer is initialized. Calling this method is
/// roughly equivalent to calling `initialize(repeating:count:)` with a
/// `count` of 1.
///
/// - Parameters:
/// - value: The instance to initialize this pointer's pointee to.
@inlinable
public func initialize(to value: Pointee) {
Builtin.initialize(value, self._rawValue)
}
/// Retrieves and returns the referenced instance, returning the pointer's
/// memory to an uninitialized state.
///
/// Calling the `move()` method on a pointer `p` that references memory of
/// type `T` is equivalent to the following code, aside from any cost and
/// incidental side effects of copying and destroying the value:
///
/// let value: T = {
/// defer { p.deinitialize(count: 1) }
/// return p.pointee
/// }()
///
/// The memory referenced by this pointer must be initialized. After calling
/// `move()`, the memory is uninitialized.
///
/// - Returns: The instance referenced by this pointer.
@inlinable
public func move() -> Pointee {
return Builtin.take(_rawValue)
}
/// Replaces this pointer's memory with the specified number of
/// consecutive copies of the given value.
///
/// The region of memory starting at this pointer and covering `count`
/// instances of the pointer's `Pointee` type must be initialized or
/// `Pointee` must be a trivial type. After calling
/// `assign(repeating:count:)`, the region is initialized.
///
/// - Parameters:
/// - repeatedValue: The instance to assign this pointer's memory to.
/// - count: The number of consecutive copies of `newValue` to assign.
/// `count` must not be negative.
@inlinable
public func assign(repeating repeatedValue: Pointee, count: Int) {
_debugPrecondition(count >= 0, "UnsafeMutablePointer.assign(repeating:count:) with negative count")
for i in 0..<count {
self[i] = repeatedValue
}
}
/// Replaces this pointer's initialized memory with the specified number of
/// instances from the given pointer's memory.
///
/// The region of memory starting at this pointer and covering `count`
/// instances of the pointer's `Pointee` type must be initialized or
/// `Pointee` must be a trivial type. After calling
/// `assign(from:count:)`, the region is initialized.
///
/// - Note: Returns without performing work if `self` and `source` are equal.
///
/// - Parameters:
/// - source: A pointer to at least `count` initialized instances of type
/// `Pointee`. The memory regions referenced by `source` and this
/// pointer may overlap.
/// - count: The number of instances to copy from the memory referenced by
/// `source` to this pointer's memory. `count` must not be negative.
@inlinable
public func assign(from source: UnsafePointer<Pointee>, count: Int) {
_debugPrecondition(
count >= 0, "UnsafeMutablePointer.assign with negative count")
if UnsafePointer(self) < source || UnsafePointer(self) >= source + count {
// assign forward from a disjoint or following overlapping range.
Builtin.assignCopyArrayFrontToBack(
Pointee.self, self._rawValue, source._rawValue, count._builtinWordValue)
// This builtin is equivalent to:
// for i in 0..<count {
// self[i] = source[i]
// }
}
else if UnsafePointer(self) != source {
// assign backward from a non-following overlapping range.
Builtin.assignCopyArrayBackToFront(
Pointee.self, self._rawValue, source._rawValue, count._builtinWordValue)
// This builtin is equivalent to:
// var i = count-1
// while i >= 0 {
// self[i] = source[i]
// i -= 1
// }
}
}
/// Moves instances from initialized source memory into the uninitialized
/// memory referenced by this pointer, leaving the source memory
/// uninitialized and the memory referenced by this pointer initialized.
///
/// The region of memory starting at this pointer and covering `count`
/// instances of the pointer's `Pointee` type must be uninitialized or
/// `Pointee` must be a trivial type. After calling
/// `moveInitialize(from:count:)`, the region is initialized and the memory
/// region `source..<(source + count)` is uninitialized.
///
/// - Parameters:
/// - source: A pointer to the values to copy. The memory region
/// `source..<(source + count)` must be initialized. The memory regions
/// referenced by `source` and this pointer may overlap.
/// - count: The number of instances to move from `source` to this
/// pointer's memory. `count` must not be negative.
@inlinable
public func moveInitialize(from source: UnsafeMutablePointer, count: Int) {
_debugPrecondition(
count >= 0, "UnsafeMutablePointer.moveInitialize with negative count")
if self < source || self >= source + count {
// initialize forward from a disjoint or following overlapping range.
Builtin.takeArrayFrontToBack(
Pointee.self, self._rawValue, source._rawValue, count._builtinWordValue)
// This builtin is equivalent to:
// for i in 0..<count {
// (self + i).initialize(to: (source + i).move())
// }
}
else {
// initialize backward from a non-following overlapping range.
Builtin.takeArrayBackToFront(
Pointee.self, self._rawValue, source._rawValue, count._builtinWordValue)
// This builtin is equivalent to:
// var src = source + count
// var dst = self + count
// while dst != self {
// (--dst).initialize(to: (--src).move())
// }
}
}
/// Initializes the memory referenced by this pointer with the values
/// starting at the given pointer.
///
/// The region of memory starting at this pointer and covering `count`
/// instances of the pointer's `Pointee` type must be uninitialized or
/// `Pointee` must be a trivial type. After calling
/// `initialize(from:count:)`, the region is initialized.
///
/// - Parameters:
/// - source: A pointer to the values to copy. The memory region
/// `source..<(source + count)` must be initialized. The memory regions
/// referenced by `source` and this pointer must not overlap.
/// - count: The number of instances to move from `source` to this
/// pointer's memory. `count` must not be negative.
@inlinable
public func initialize(from source: UnsafePointer<Pointee>, count: Int) {
_debugPrecondition(
count >= 0, "UnsafeMutablePointer.initialize with negative count")
_debugPrecondition(
UnsafePointer(self) + count <= source ||
source + count <= UnsafePointer(self),
"UnsafeMutablePointer.initialize overlapping range")
Builtin.copyArray(
Pointee.self, self._rawValue, source._rawValue, count._builtinWordValue)
// This builtin is equivalent to:
// for i in 0..<count {
// (self + i).initialize(to: source[i])
// }
}
/// Replaces the memory referenced by this pointer with the values
/// starting at the given pointer, leaving the source memory uninitialized.
///
/// The region of memory starting at this pointer and covering `count`
/// instances of the pointer's `Pointee` type must be initialized or
/// `Pointee` must be a trivial type. After calling
/// `moveAssign(from:count:)`, the region is initialized and the memory
/// region `source..<(source + count)` is uninitialized.
///
/// - Parameters:
/// - source: A pointer to the values to copy. The memory region
/// `source..<(source + count)` must be initialized. The memory regions
/// referenced by `source` and this pointer must not overlap.
/// - count: The number of instances to move from `source` to this
/// pointer's memory. `count` must not be negative.
@inlinable
public func moveAssign(from source: UnsafeMutablePointer, count: Int) {
_debugPrecondition(
count >= 0, "UnsafeMutablePointer.moveAssign(from:) with negative count")
_debugPrecondition(
self + count <= source || source + count <= self,
"moveAssign overlapping range")
Builtin.assignTakeArray(
Pointee.self, self._rawValue, source._rawValue, count._builtinWordValue)
// These builtins are equivalent to:
// for i in 0..<count {
// self[i] = (source + i).move()
// }
}
/// Deinitializes the specified number of values starting at this pointer.
///
/// The region of memory starting at this pointer and covering `count`
/// instances of the pointer's `Pointee` type must be initialized. After
/// calling `deinitialize(count:)`, the memory is uninitialized, but still
/// bound to the `Pointee` type.
///
/// - Parameter count: The number of instances to deinitialize. `count` must
/// not be negative.
/// - Returns: A raw pointer to the same address as this pointer. The memory
/// referenced by the returned raw pointer is still bound to `Pointee`.
@inlinable
@discardableResult
public func deinitialize(count: Int) -> UnsafeMutableRawPointer {
_debugPrecondition(count >= 0, "UnsafeMutablePointer.deinitialize with negative count")
// FIXME: optimization should be implemented, where if the `count` value
// is 1, the `Builtin.destroy(Pointee.self, _rawValue)` gets called.
Builtin.destroyArray(Pointee.self, _rawValue, count._builtinWordValue)
return UnsafeMutableRawPointer(self)
}
/// Executes the given closure while temporarily binding the specified number
/// of instances to the given type.
///
/// Use this method when you have a pointer to memory bound to one type and
/// you need to access that memory as instances of another type. Accessing
/// memory as a type `T` requires that the memory be bound to that type. A
/// memory location may only be bound to one type at a time, so accessing
/// the same memory as an unrelated type without first rebinding the memory
/// is undefined.
///
/// The region of memory starting at this pointer and covering `count`
/// instances of the pointer's `Pointee` type must be initialized.
///
/// The following example temporarily rebinds the memory of a `UInt64`
/// pointer to `Int64`, then accesses a property on the signed integer.
///
/// let uint64Pointer: UnsafeMutablePointer<UInt64> = fetchValue()
/// let isNegative = uint64Pointer.withMemoryRebound(to: Int64.self) { ptr in
/// return ptr.pointee < 0
/// }
///
/// Because this pointer's memory is no longer bound to its `Pointee` type
/// while the `body` closure executes, do not access memory using the
/// original pointer from within `body`. Instead, use the `body` closure's
/// pointer argument to access the values in memory as instances of type
/// `T`.
///
/// After executing `body`, this method rebinds memory back to the original
/// `Pointee` type.
///
/// - Note: Only use this method to rebind the pointer's memory to a type
/// with the same size and stride as the currently bound `Pointee` type.
/// To bind a region of memory to a type that is a different size, convert
/// the pointer to a raw pointer and use the `bindMemory(to:capacity:)`
/// method.
///
/// - Parameters:
/// - type: The type to temporarily bind the memory referenced by this
/// pointer. The type `T` must be the same size and be layout compatible
/// with the pointer's `Pointee` type.
/// - count: The number of instances of `Pointee` to bind to `type`.
/// - body: A closure that takes a mutable typed pointer to the
/// same memory as this pointer, only bound to type `T`. The closure's
/// pointer argument is valid only for the duration of the closure's
/// execution. If `body` has a return value, that value is also used as
/// the return value for the `withMemoryRebound(to:capacity:_:)` method.
/// - Returns: The return value, if any, of the `body` closure parameter.
@inlinable
public func withMemoryRebound<T, Result>(to type: T.Type, capacity count: Int,
_ body: (UnsafeMutablePointer<T>) throws -> Result
) rethrows -> Result {
Builtin.bindMemory(_rawValue, count._builtinWordValue, T.self)
defer {
Builtin.bindMemory(_rawValue, count._builtinWordValue, Pointee.self)
}
return try body(UnsafeMutablePointer<T>(_rawValue))
}
/// Accesses the pointee at the specified offset from this pointer.
///
/// For a pointer `p`, the memory at `p + i` must be initialized when reading
/// the value by using the subscript. When the subscript is used as the left
/// side of an assignment, the memory at `p + i` must be initialized or
/// the pointer's `Pointee` type must be a trivial type.
///
/// Do not assign an instance of a nontrivial type through the subscript to
/// uninitialized memory. Instead, use an initializing method, such as
/// `initialize(to:count:)`.
///
/// - Parameter i: The offset from this pointer at which to access an
/// instance, measured in strides of the pointer's `Pointee` type.
@inlinable
public subscript(i: Int) -> Pointee {
@_transparent
unsafeAddress {
return UnsafePointer(self + i)
}
@_transparent
nonmutating unsafeMutableAddress {
return self + i
}
}
@inlinable // unsafe-performance
internal static var _max : UnsafeMutablePointer {
return UnsafeMutablePointer(
bitPattern: 0 as Int &- MemoryLayout<Pointee>.stride
)._unsafelyUnwrappedUnchecked
}
}
| apache-2.0 | 25cf77d07536c3964affb1210f854fa7 | 42.008147 | 103 | 0.674054 | 4.401209 | false | false | false | false |
fingerco/neural-net-swift-snake | NNTestGame/GameScene.swift | 1 | 4567 | //
// GameScene.swift
// NNTestGame
//
// Created by fingerco on 9/4/15.
// Copyright (c) 2015 fingerco. All rights reserved.
//
import SpriteKit
class GameScene: SKScene {
var food = SKShapeNode(rectOfSize: CGSize(width: 10, height: 10))
var foodGridPos = CGPoint(x: 10, y: 10)
var obstacles : Array<SKShapeNode> = []
var speedup = 100
var stop_speedup = 10000
var total_frames = 0
var gridWidth : Int = 0
var gridHeight : Int = 0
var bot = Agent()
var sheep = Array<Agent>()
var botNode = SKShapeNode(rectOfSize: CGSize(width: 10, height: 10))
var sheepNodes = Array<SKShapeNode>()
override func didMoveToView(view: SKView) {
/* Setup your scene here */
botNode.fillColor = SKColor.whiteColor()
food.fillColor = SKColor.greenColor()
self.addChild(botNode)
self.addChild(food)
self.gridWidth = Int(view.scene!.size.width/10)
self.gridHeight = Int(view.scene!.size.height/10)
bot.pos = self.randomPosition()
for i in 1..<20 {
let newSheep = Agent()
newSheep.movementSpeed = 0.9
newSheep.pos = self.randomPosition()
newSheep.initializeToEnvironment(self.getInputs(newSheep, toFollow: self.bot.pos), maxX: self.gridWidth, maxY: self.gridHeight)
self.sheep.append(newSheep)
let newSheepNode = SKShapeNode(rectOfSize: CGSize(width: 10, height: 10))
newSheepNode.fillColor = SKColor.redColor()
sheepNodes.append(newSheepNode)
self.addChild(newSheepNode)
}
self.bot.initializeToEnvironment(self.getInputs(bot, toFollow: self.foodGridPos), maxX: self.gridWidth, maxY: self.gridHeight)
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
var loss : CGFloat = 0
for frame in 1...self.speedup {
loss += updateGame()
if(total_frames % 10000 == 0) {
let avg_loss = loss / 10000
loss = 0
println("Iteration: " + total_frames.description, "Avg loss: " + avg_loss.description)
}
if(total_frames >= self.stop_speedup) { self.speedup = 1 }
total_frames += 1
botNode.position.x = bot.pos.x * 10
botNode.position.y = bot.pos.y * 10
for (index, currSheep) in enumerate(sheep) {
let sheepNode = sheepNodes[index]
sheepNode.position.x = currSheep.pos.x * 10
sheepNode.position.y = currSheep.pos.y * 10
}
food.position.x = foodGridPos.x * 10
food.position.y = foodGridPos.y * 10
}
}
func updateGame() -> CGFloat {
let botInputs = getInputs(bot, toFollow: foodGridPos)
let botAction = bot.chooseAction(botInputs)
let loss = bot.learn(botInputs, toFollow: foodGridPos)
for currSheep in sheep {
let sheepInputs = getInputs(currSheep, toFollow: foodGridPos)
currSheep.learn(sheepInputs, toFollow: foodGridPos)
let sheepAction = currSheep.chooseAction(sheepInputs)
currSheep.pos = currSheep.movePosition(currSheep.pos, direction: sheepAction)
}
bot.pos = bot.movePosition(bot.pos, direction: botAction)
if(self.botNode.intersectsNode(self.food)) {
self.foodGridPos = self.randomPosition()
}
return loss
}
func getInputs(bot : Agent, toFollow follow: CGPoint) -> Array<CGFloat> {
let followHorizontal : CGFloat = (bot.pos.x == follow.x) ? 0.1 : (bot.pos.x < follow.x ? 0.5 : -0.5)
let followVertical : CGFloat = (bot.pos.y == follow.y) ? 0.1 : (bot.pos.y < follow.y ? 0.5 : -0.5)
let avoidHorizontal : CGFloat = (bot.pos.x == follow.x) ? 0.1 : (bot.pos.x < follow.x ? 0.5 : -0.5)
let avoidVertical : CGFloat = (bot.pos.y == follow.y) ? 0.1 : (bot.pos.y < follow.y ? 0.5 : -0.5)
return [followHorizontal, followVertical]
}
func randomPosition() -> CGPoint {
let rand_x = arc4random_uniform(UInt32(self.gridWidth))
let rand_y = arc4random_uniform(UInt32(self.gridHeight))
return CGPoint(x: CGFloat(rand_x), y: CGFloat(rand_y))
}
}
| apache-2.0 | 31ed38c8423f25f2dc9b5c9a92eac5d8 | 34.403101 | 139 | 0.569302 | 3.957539 | false | false | false | false |
wikimedia/apps-ios-wikipedia | Wikipedia/Code/EditLinkViewController.swift | 1 | 10158 | import UIKit
protocol EditLinkViewControllerDelegate: AnyObject {
func editLinkViewController(_ editLinkViewController: EditLinkViewController, didTapCloseButton button: UIBarButtonItem)
func editLinkViewController(_ editLinkViewController: EditLinkViewController, didFinishEditingLink displayText: String?, linkTarget: String)
func editLinkViewController(_ editLinkViewController: EditLinkViewController, didFailToExtractArticleTitleFromArticleURL articleURL: URL)
func editLinkViewControllerDidRemoveLink(_ editLinkViewController: EditLinkViewController)
}
class EditLinkViewController: ViewController {
weak var delegate: EditLinkViewControllerDelegate?
typealias Link = SectionEditorWebViewMessagingController.Link
private let link: Link
private let siteURL: URL
private var articleURL: URL
private let articleCell = ArticleRightAlignedImageCollectionViewCell()
private let dataStore: MWKDataStore
private var navigationBarVisibleHeightObservation: NSKeyValueObservation?
@IBOutlet private weak var contentView: UIView!
@IBOutlet private weak var scrollViewTopConstraint: NSLayoutConstraint!
@IBOutlet private weak var displayTextLabel: UILabel!
@IBOutlet private weak var displayTextView: UITextView!
@IBOutlet private weak var displayTextViewHeightConstraint: NSLayoutConstraint!
@IBOutlet private weak var linkTargetLabel: UILabel!
@IBOutlet private weak var linkTargetContainerView: UIView!
@IBOutlet private weak var linkTargetContainerViewHeightConstraint: NSLayoutConstraint!
@IBOutlet private weak var activityIndicatorView: UIActivityIndicatorView!
@IBOutlet private weak var removeLinkButton: AutoLayoutSafeMultiLineButton!
@IBOutlet private var separatorViews: [UIView] = []
private lazy var closeButton: UIBarButtonItem = {
let closeButton = UIBarButtonItem.wmf_buttonType(.X, target: self, action: #selector(close(_:)))
closeButton.accessibilityLabel = CommonStrings.closeButtonAccessibilityLabel
return closeButton
}()
private lazy var doneButton = UIBarButtonItem(title: CommonStrings.doneTitle, style: .done, target: self, action: #selector(finishEditing(_:)))
init?(link: Link, siteURL: URL?, dataStore: MWKDataStore) {
guard
let siteURL = siteURL ?? MWKLanguageLinkController.sharedInstance().appLanguage?.siteURL() ?? NSURL.wmf_URLWithDefaultSiteAndCurrentLocale(),
let articleURL = link.articleURL(for: siteURL)
else {
return nil
}
self.link = link
self.siteURL = siteURL
self.articleURL = articleURL
self.dataStore = dataStore
super.init(nibName: "EditLinkViewController", bundle: nil)
}
deinit {
navigationBarVisibleHeightObservation?.invalidate()
navigationBarVisibleHeightObservation = nil
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
navigationBar.displayType = .modal
title = CommonStrings.editLinkTitle
navigationItem.leftBarButtonItem = closeButton
navigationItem.rightBarButtonItem = doneButton
navigationItem.backBarButtonItem = UIBarButtonItem(title: CommonStrings.accessibilityBackTitle, style: .plain, target: nil, action: nil)
var textContainerInset = displayTextView.textContainerInset
textContainerInset.top = 15
displayTextLabel.text = WMFLocalizedString("edit-link-display-text-title", value: "Display text", comment: "Title for the display text label")
displayTextView.textContainerInset = textContainerInset
displayTextView.textContainer.lineFragmentPadding = 0
displayTextView.text = link.label ?? link.page
linkTargetLabel.text = WMFLocalizedString("edit-link-link-target-title", value: "Link target", comment: "Title for the link target label")
removeLinkButton.setTitle(WMFLocalizedString("edit-link-remove-link-title", value: "Remove link", comment: "Title for the remove link button"), for: .normal)
articleCell.isHidden = true
linkTargetContainerView.addSubview(articleCell)
navigationBarVisibleHeightObservation = navigationBar.observe(\.visibleHeight, options: [.new, .initial], changeHandler: { [weak self] (observation, change) in
guard let self = self else {
return
}
self.scrollViewTopConstraint.constant = self.navigationBar.visibleHeight
})
apply(theme: theme)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
fetchArticle()
}
private func fetchArticle() {
guard let article = dataStore.fetchArticle(with: articleURL) else {
guard let key = articleURL.wmf_databaseKey else {
return
}
dataStore.articleSummaryController.updateOrCreateArticleSummaryForArticle(withKey: key) { (article, _) in
guard let article = article else {
return
}
self.updateView(with: article)
}
return
}
updateView(with: article)
}
private func updateView(with article: WMFArticle) {
articleCell.configure(article: article, displayType: .compactList, index: 0, theme: theme, layoutOnly: false)
articleCell.topSeparator.isHidden = true
articleCell.bottomSeparator.isHidden = true
articleCell.extractLabel?.numberOfLines = 5
updateLinkTargetContainer()
articleCell.isHidden = false
activityIndicatorView.stopAnimating()
view.setNeedsLayout()
}
private func updateLinkTargetContainer() {
articleCell.frame = CGRect(origin: linkTargetContainerView.bounds.origin, size: articleCell.sizeThatFits(CGSize(width: linkTargetContainerView.bounds.width, height: UIView.noIntrinsicMetric), apply: true))
linkTargetContainerViewHeightConstraint.constant = articleCell.frame.height
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
displayTextLabel.font = UIFont.wmf_font(.footnote, compatibleWithTraitCollection: traitCollection)
linkTargetLabel.font = UIFont.wmf_font(.footnote, compatibleWithTraitCollection: traitCollection)
displayTextView.font = UIFont.wmf_font(.subheadline, compatibleWithTraitCollection: traitCollection)
removeLinkButton.titleLabel?.font = UIFont.wmf_font(.subheadline, compatibleWithTraitCollection: traitCollection)
}
@objc private func close(_ sender: UIBarButtonItem) {
delegate?.editLinkViewController(self, didTapCloseButton: sender)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
displayTextViewHeightConstraint.constant = displayTextView.sizeThatFits(CGSize(width: displayTextView.bounds.width, height: UIView.noIntrinsicMetric)).height
updateLinkTargetContainer()
}
@objc private func finishEditing(_ sender: UIBarButtonItem) {
let displayText = displayTextView.text
guard let linkTarget = articleURL.wmf_title else {
assertionFailure("Failed to extract article title from url: \(articleURL)")
delegate?.editLinkViewController(self, didFailToExtractArticleTitleFromArticleURL: articleURL)
return
}
delegate?.editLinkViewController(self, didFinishEditingLink: displayText, linkTarget: linkTarget)
}
@IBAction private func removeLink(_ sender: UIButton) {
delegate?.editLinkViewControllerDidRemoveLink(self)
}
@IBAction private func searchArticles(_ sender: UITapGestureRecognizer) {
let searchViewController = SearchViewController()
searchViewController.shouldSetTitleViewWhenRecentSearchesAreDisabled = false
searchViewController.siteURL = siteURL
searchViewController.shouldSetSearchVisible = false
searchViewController.shouldBecomeFirstResponder = true
searchViewController.displayType = .backVisible
searchViewController.areRecentSearchesEnabled = false
searchViewController.dataStore = SessionSingleton.sharedInstance()?.dataStore
searchViewController.shouldShowCancelButton = false
searchViewController.delegate = self
searchViewController.delegatesSelection = true
searchViewController.showLanguageBar = false
searchViewController.navigationItem.title = title
searchViewController.searchTerm = articleURL.wmf_title
searchViewController.search()
searchViewController.apply(theme: theme)
navigationController?.pushViewController(searchViewController, animated: true)
}
override func apply(theme: Theme) {
super.apply(theme: theme)
self.theme = theme
guard viewIfLoaded != nil else {
return
}
contentView.backgroundColor = theme.colors.paperBackground
view.backgroundColor = theme.colors.baseBackground
separatorViews.forEach { $0.backgroundColor = theme.colors.border }
displayTextLabel.textColor = theme.colors.secondaryText
linkTargetLabel.textColor = theme.colors.secondaryText
removeLinkButton.tintColor = theme.colors.destructive
removeLinkButton.backgroundColor = theme.colors.paperBackground
closeButton.tintColor = theme.colors.primaryText
doneButton.tintColor = theme.colors.link
displayTextView.textColor = theme.colors.primaryText
activityIndicatorView.style = theme.isDark ? .white : .gray
}
}
extension EditLinkViewController: ArticleCollectionViewControllerDelegate {
func articleCollectionViewController(_ articleCollectionViewController: ArticleCollectionViewController, didSelectArticleWith articleURL: URL, at indexPath: IndexPath) {
self.articleURL = articleURL
navigationController?.popViewController(animated: true)
}
}
| mit | ca38ee442c5f2152ab7e9e6b45c282ff | 48.072464 | 213 | 0.731739 | 5.848014 | false | false | false | false |
Ryce/flickrpickr | Carthage/Checkouts/judokit/Source/UIColor+Judo.swift | 2 | 2136 | //
// UIColor+Judo.swift
// JudoKit
//
// Copyright (c) 2016 Alternative Payments 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 Foundation
public extension UIColor {
/**
Inverse color
- returns: The inverse color of the receiver
*/
public func inverseColor() -> UIColor {
var r: CGFloat = 0.0
var g: CGFloat = 0.0
var b: CGFloat = 0.0
var a: CGFloat = 0.0
self.getRed(&r, green:&g, blue:&b, alpha:&a)
return UIColor(red: 1 - r, green: 1 - g, blue: 1 - b, alpha: a)
}
/**
Calculates a weighed greyscale representation percentage of the receiver
- returns: A greyscale representation percentage CGFloat
*/
public func greyScale() -> CGFloat {
// 0.299r + 0.587g + 0.114b
var r: CGFloat = 0.0
var g: CGFloat = 0.0
var b: CGFloat = 0.0
var a: CGFloat = 0.0
self.getRed(&r, green:&g, blue:&b, alpha:&a)
let newValue: CGFloat = (0.299 * r + 0.587 * g + 0.114 * b)
return newValue
}
}
| mit | bf8368cfdebc6a8c960f1b61f49f0be4 | 34.016393 | 82 | 0.653558 | 4.030189 | false | false | false | false |
amraboelela/swift | test/DebugInfo/variables.swift | 1 | 4698 | // RUN: %target-swift-frontend %s -g -emit-ir -o - | %FileCheck %s
// Ensure that the debug info we're emitting passes the back end verifier.
// RUN: %target-swift-frontend %s -g -S -o - | %FileCheck %s --check-prefix ASM-%target-object-format
// ASM-macho: .section __DWARF,__debug_info
// ASM-elf: .section .debug_info,"",{{[@%]}}progbits
// ASM-coff: .section .debug_info,"dr"
// Test variables-interpreter.swift runs this code with `swift -g -i`.
// Test variables-repl.swift runs this code with `swift -g < variables.swift`.
// CHECK-DAG: ![[TLC:.*]] = !DIModule({{.*}}, name: "variables"
// Global variables.
var glob_i8: Int8 = 8
// CHECK-DAG: !DIGlobalVariable(name: "glob_i8",{{.*}} scope: ![[TLC]],{{.*}} line: [[@LINE-1]],{{.*}} type: ![[I8:[^,]+]]
var glob_i16: Int16 = 16
// CHECK-DAG: !DIGlobalVariable(name: "glob_i16",{{.*}} scope: ![[TLC]],{{.*}} line: [[@LINE-1]],{{.*}} type: ![[I16:[^,]+]]
var glob_i32: Int32 = 32
// CHECK-DAG: !DIGlobalVariable(name: "glob_i32",{{.*}} scope: ![[TLC]],{{.*}} line: [[@LINE-1]],{{.*}} type: ![[I32:[^,]+]]
var glob_i64: Int64 = 64
// CHECK-DAG: !DIGlobalVariable(name: "glob_i64",{{.*}} scope: ![[TLC]],{{.*}} line: [[@LINE-1]],{{.*}} type: ![[I64:[^,]+]]
var glob_f: Float = 2.89
// CHECK-DAG: !DIGlobalVariable(name: "glob_f",{{.*}} scope: ![[TLC]],{{.*}} line: [[@LINE-1]],{{.*}} type: ![[F:[^,]+]]
var glob_d: Double = 3.14
// CHECK-DAG: !DIGlobalVariable(name: "glob_d",{{.*}} scope: ![[TLC]],{{.*}} line: [[@LINE-1]],{{.*}} type: ![[D:[^,]+]]
var glob_b: Bool = true
// CHECK-DAG: !DIGlobalVariable(name: "glob_b",{{.*}} scope: ![[TLC]],{{.*}} line: [[@LINE-1]],{{.*}} type: ![[B:[^,]+]]
var glob_s: String = "😄"
// CHECK-DAG: !DIGlobalVariable(name: "glob_s",{{.*}} scope: ![[TLC]],{{.*}} line: [[@LINE-1]],{{.*}} type: ![[S:[^,]+]]
// FIXME: Dreadful type-checker performance prevents this from being this single
// print expression:
// print("\(glob_v), \(glob_i8), \(glob_i16), \(glob_i32), \(glob_i64), \(glob_f), \(glob_d), \(glob_b), \(glob_s)", terminator: "")
print(", \(glob_i8)", terminator: "")
print(", \(glob_i16)", terminator: "")
print(", \(glob_i32)", terminator: "")
print(", \(glob_i64)", terminator: "")
print(", \(glob_f)", terminator: "")
print(", \(glob_d)", terminator: "")
print(", \(glob_b)", terminator: "")
print(", \(glob_s)", terminator: "")
var unused: Int32 = -1
// CHECK-DAG: ![[RT:[0-9]+]] ={{.*}}"{{.*}}Swift.swiftmodule"
// Stack variables.
func foo(_ dt: Float) -> Float {
// CHECK-DAG: call void @llvm.dbg.declare
// CHECK-DAG: !DILocalVariable(name: "f"
let f: Float = 9.78
// CHECK-DAG: !DILocalVariable(name: "r"
let r: Float = f*dt
return r
}
var g = foo(1.0);
// Tuple types.
var tuple: (Int, Bool) = (1, true)
// CHECK-DAG: !DIGlobalVariable(name: "tuple", linkageName: "$s{{9variables|4main}}5tupleSi_Sbtvp",{{.*}} type: ![[TUPTY:[^,)]+]]
// CHECK-DAG: ![[TUPTY]] = !DICompositeType({{.*}}identifier: "$sSi_SbtD"
func myprint(_ p: (i: Int, b: Bool)) {
print("\(p.i) -> \(p.b)")
}
myprint(tuple)
// Arrays are represented as an instantiation of Array.
// CHECK-DAG: ![[ARRAYTY:.*]] = !DICompositeType(tag: DW_TAG_structure_type, name: "Array",
// CHECK-DAG: !DIGlobalVariable(name: "array_of_tuples",{{.*}} type: ![[ARRAYTY]]
var array_of_tuples : [(a : Int, b : Int)] = [(1,2)]
var twod : [[Int]] = [[1]]
func bar(_ x: [(a : Int, b : Int)], y: [[Int]]) {
}
// CHECK-DAG: !DIGlobalVariable(name: "P",{{.*}} type: ![[PTY:[0-9]+]]
// CHECK-DAG: ![[PTUP:.*]] = !DICompositeType(tag: DW_TAG_structure_type, name: "$sSd1x_Sd1ySd1ztD",
// CHECK-DAG: ![[PTY]] = !DIDerivedType(tag: DW_TAG_typedef, name: "$s{{9variables|4main}}5PointaD",{{.*}} baseType: ![[PTUP]]
typealias Point = (x: Double, y: Double, z: Double)
var P:Point = (1, 2, 3)
func myprint(_ p: (x: Double, y: Double, z: Double)) {
print("(\(p.x), \(p.y), \(p.z))")
}
myprint(P)
// CHECK-DAG: !DIGlobalVariable(name: "P2",{{.*}} type: ![[APTY:[0-9]+]]
// CHECK-DAG: ![[APTY]] = !DIDerivedType(tag: DW_TAG_typedef, name: "$s{{9variables|4main}}13AliasForPointaD",{{.*}} baseType: ![[PTY:[0-9]+]]
typealias AliasForPoint = Point
var P2:AliasForPoint = (4, 5, 6)
myprint(P2)
// Unions.
enum TriValue {
case false_
case true_
case top
}
// CHECK-DAG: !DIGlobalVariable(name: "unknown",{{.*}} type: ![[TRIVAL:[0-9]+]]
// CHECK-DAG: ![[TRIVAL]] = !DICompositeType({{.*}}name: "TriValue",
var unknown = TriValue.top
func myprint(_ value: TriValue) {
switch value {
case TriValue.false_: print("false")
case TriValue.true_: print("true")
case TriValue.top: print("⊤")
}
}
myprint(unknown)
// CHECK-DAG: !DIFile(filename: "{{.*}}variables.swift"
| apache-2.0 | dd7bbfb5fd9d9c132b1ef91bacfe870d | 39.111111 | 142 | 0.574686 | 3.01413 | false | false | false | false |
sshams/puremvc-swift-standard-framework | PureMVC/org/puremvc/swift/core/Controller.swift | 1 | 6316 | //
// Controller.swift
// PureMVC SWIFT Standard
//
// Copyright(c) 2015-2025 Saad Shams <[email protected]>
// Your reuse is governed by the Creative Commons Attribution 3.0 License
//
import Foundation
/**
A Singleton `IController` implementation.
In PureMVC, the `Controller` class follows the
'Command and Controller' strategy, and assumes these
responsibilities:
* Remembering which `ICommand`s are intended to handle which `INotifications`.
* Registering itself as an `IObserver` with the `View` for each `INotification` that it has an `ICommand` mapping for.
* Creating a new instance of the proper `ICommand` to handle a given `INotification` when notified by the `View`.
* Calling the `ICommand`'s `execute` method, passing in the `INotification`.
Your application must register `ICommands` with the
Controller.
The simplest way is to subclass `Facade`,
and use its `initializeController` method to add your
registrations.
`@see org.puremvc.swift.core.view.View View`
`@see org.puremvc.swift.patterns.observer.Observer Observer`
`@see org.puremvc.swift.patterns.observer.Notification Notification`
`@see org.puremvc.swift.patterns.command.SimpleCommand SimpleCommand`
`@see org.puremvc.swift.patterns.command.MacroCommand MacroCommand`
*/
public class Controller: IController {
// Local reference to View
private var _view: IView?
// Mapping of Notification names to references of the closures that instantiates and return `ICommand` instance
private var commandMap: [String: () -> ICommand]
// Singleton instance
private static var instance: IController?
/// Message constant
public static let SINGLETON_MSG = "Controller Singleton already constructed!"
// to ensure operation happens only once
private static var token: dispatch_once_t = 0
// Concurrent queue for commandMap
// for speed and convenience of running concurrently while reading, and thread safety of blocking while mutating
private let commandMapQueue = dispatch_queue_create("org.puremvc.controller.commandMapQueue", DISPATCH_QUEUE_CONCURRENT)
/**
Constructor.
This `IController` implementation is a Singleton,
so you should not call the constructor
directly, but instead call the static Singleton
Factory method `Controller.getInstance()`
@throws Error if Singleton instance has already been constructed
*/
public init() {
assert(Controller.instance == nil, Controller.SINGLETON_MSG)
commandMap = [:]
Controller.instance = self
initializeController()
}
/**
Initialize the Singleton `Controller` instance.
Called automatically by the constructor.
Note that if you are using a subclass of `View`
in your application, you should *also* subclass `Controller`
and override the `initializeController` method in the
following way:
// ensure that the Controller is talking to my IView implementation
public func initializeController() {
view = MyView.getInstance { MyView() }
}
*/
public func initializeController() {
view = View.getInstance { View() }
}
/**
`Controller` Singleton Factory method.
- parameter closure: reference that returns `IController`
- returns: the Singleton instance of `Controller`
*/
public class func getInstance(closure: () -> IController) -> IController {
dispatch_once(&self.token) {
self.instance = closure()
}
return instance!
}
/**
If an `ICommand` has previously been registered
to handle a the given `INotification`, then it is executed.
- parameter note: an `INotification`
*/
public func executeCommand(notification: INotification) {
dispatch_sync(commandMapQueue) {
if let closure = self.commandMap[notification.name] {
let commandInstance = closure()
commandInstance.execute(notification)
}
}
}
/**
Register a particular `ICommand` class as the handler
for a particular `INotification`.
If an `ICommand` has already been registered to
handle `INotification`s with this name, it is no longer
used, the new `ICommand` is used instead.
The Observer for the new ICommand is only created if this the
first time an ICommand has been regisered for this Notification name.
- parameter notificationName: the name of the `INotification`
- parameter closure: reference that instantiates and returns `ICommand`
*/
public func registerCommand(notificationName: String, closure: () -> ICommand) {
dispatch_barrier_sync(commandMapQueue) {
if self.commandMap[notificationName] == nil { //weak reference to Controller (self) to avoid reference cycle with View and Observer
self.view!.registerObserver(notificationName, observer: Observer(notifyMethod: {[weak self] notification in self!.executeCommand(notification)}, notifyContext: self))
}
self.commandMap[notificationName] = closure
}
}
/**
Check if a Command is registered for a given Notification
- parameter notificationName:
- returns: whether a Command is currently registered for the given `notificationName`.
*/
public func hasCommand(notificationName: String) -> Bool {
var result = false
dispatch_sync(commandMapQueue) {
result = self.commandMap[notificationName] != nil
}
return result
}
/**
Remove a previously registered `ICommand` to `INotification` mapping.
- parameter notificationName: the name of the `INotification` to remove the `ICommand` mapping for
*/
public func removeCommand(notificationName: String) {
if self.hasCommand(notificationName) {
dispatch_barrier_sync(commandMapQueue) {
self.view!.removeObserver(notificationName, notifyContext: self)
self.commandMap.removeValueForKey(notificationName)
}
}
}
/// Local reference to View
public var view: IView? {
get { return _view }
set { _view = newValue }
}
} | bsd-3-clause | a9aa03bf63137b06b458ec0fa6f982f8 | 33.900552 | 182 | 0.680019 | 4.709918 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.