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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
IanKeen/IKRouter | IKRouterTests/RouteTests.swift | 1 | 2506 | //
// RouteTests.swift
// IKRouter
//
// Created by Ian Keen on 29/10/2015.
// Copyright © 2015 Mustard. All rights reserved.
//
import XCTest
@testable import IKRouter
class RouteTests: XCTestCase {
func test_Route_validUrl_should_populateProperties() {
let url = "appscheme://path/to/thing?foo=bar"
guard let route = Route(url: url) else { XCTFail(); return }
XCTAssertTrue(route.components.scheme == "appscheme")
XCTAssertTrue(route.components.path == ["path", "to", "thing"])
XCTAssertTrue(route.components.query["foo"] == "bar")
}
func test_Route_invalidUrl_should_returnNil() {
let url = "/path/to/thing?foo=bar"
guard let _ = Route(url: url) else {
XCTAssert(true)
return
}
XCTFail()
}
func test_Route_invalidQuery_should_returnNil() {
let url = "/path/to/thing?foo=bar&thing=blah&thing"
guard let _ = RouteComponents(url: url) else {
XCTAssert(true)
return
}
XCTFail()
}
func test_Route_matchingRoute_should_produceMatchedRoute() {
let matcher = RouteMatcher(url: "myapp://path/to/:thing")!
let route = Route(url: "myapp://path/to/foobar")!
if let _ = route.matchedRoute(matcher) {
XCTAssertTrue(true)
} else {
XCTFail()
}
}
func test_Route_matchingRoute_should_produceMatchedRouteWithSameQueryPairs() {
let matcher = RouteMatcher(url: "myapp://path/to/:thing")!
let route = Route(url: "myapp://path/to/foobar?foo=bar")!
if let match = route.matchedRoute(matcher) {
XCTAssertTrue(match.query["foo"] == "bar")
} else {
XCTFail()
}
}
func test_Route_routeWithWrongParameters_should_notProduceMatchedRoute() {
let matcher = RouteMatcher(url: "myapp://path/to/:thing")!
let route = Route(url: "myapp://path/to/foo/bar")!
if let _ = route.matchedRoute(matcher) {
XCTFail()
} else {
XCTAssertTrue(true)
}
}
func test_Route_routeWithWrongScheme_should_notProduceMatchedRoute() {
let matcher = RouteMatcher(url: "myapp://path/to/:thing")!
let route = Route(url: "anotherApp://path/to/foobar")!
if let _ = route.matchedRoute(matcher) {
XCTFail()
} else {
XCTAssertTrue(true)
}
}
}
| mit | 23106437469a7123199cb163c81de1b2 | 30.708861 | 82 | 0.571657 | 4.033816 | false | true | false | false |
mikeynap/P2PChat | P2PChat/Chat.swift | 1 | 3534 | //
// Chat.swift
// P2PChat
//
// Created by mnapolit on 2/13/17.
// Copyright © 2017 micmoo. All rights reserved.
//
import Foundation
import MultipeerConnectivity
protocol ChatManagerDelegate {
func chatManager(_ cm: ChatManager, didReceive data: Data, fromPeer peer: String)
}
class ChatManager : NSObject, MCSessionDelegate {
var peerID: MCPeerID
var session: MCSession
var browser: MCBrowserViewController
var advertiser: MCAdvertiserAssistant
var peers: [MCPeerID] = Array()
var delegate: ChatManagerDelegate?
let SERVICEID: String = "chat-files"
init(id: String){
self.peerID = MCPeerID(displayName: id)
self.session = MCSession(peer: self.peerID,securityIdentity: nil, encryptionPreference: MCEncryptionPreference.optional)
self.browser = MCBrowserViewController(serviceType: SERVICEID, session: self.session)
self.advertiser = MCAdvertiserAssistant(serviceType: SERVICEID, discoveryInfo: nil, session: self.session)
super.init()
self.session.delegate = self
self.browser.maximumNumberOfPeers = 50
}
func sendToAll(string: String) {
sendToAll(data: string.data(using: .utf8)!)
}
func sendToAll(data: Data){
do {
try self.session.send(data, toPeers: self.peers, with: MCSessionSendDataMode.reliable)
}
catch {
print("Couldn't send... \(error)")
}
}
func session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID) {
self.delegate?.chatManager(self, didReceive: data, fromPeer: peerID.displayName)
}
func session(_ session: MCSession, peer peerID: MCPeerID, didChange state: MCSessionState) {
print("peerDidChangeState", peerID, state)
if state == MCSessionState.connected {
var replaced = false
for i in 0 ..< self.peers.count {
if self.peers[i].displayName == peerID.displayName {
self.peers[i] = peerID
replaced = true
break
}
}
if !replaced {
self.peers.append(peerID)
}
} else if state == MCSessionState.notConnected {
for i in 0 ..< self.peers.count {
if self.peers[i].displayName == peerID.displayName {
self.peers.remove(at: i)
break
}
}
}
}
func session(_ session: MCSession, didReceive stream: InputStream, withName streamName: String, fromPeer peerID: MCPeerID) {
print("didReceiveStream", stream, streamName, peerID)
}
func session(_ session: MCSession, didStartReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, with progress: Progress) {
print("didStartReceiving", peerID, progress, resourceName)
}
func session(_ session: MCSession, didReceiveCertificate certificate: [Any]?, fromPeer peerID: MCPeerID, certificateHandler: @escaping (Bool) -> Void) {
print("didReceiveCert", peerID, certificate, certificateHandler(true))
}
func session(_ session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, at localURL: URL, withError error: Error?) {
print("didFinishReceiving", error, localURL, peerID, resourceName)
}
func advertiseMe() {
advertiser.start()
}
}
| mit | 516b5efc9e551bf1bf92abf3c0195152 | 34.33 | 167 | 0.627512 | 4.853022 | false | false | false | false |
vgorloff/AUHost | Vendor/mc/mcxUI/Sources/Layout/LayoutConstraint.swift | 1 | 27951 | //
// LayoutConstraint.swift
// MCA-OSS-VSTNS;MCA-OSS-AUH
//
// Created by Vlad Gorlov on 04/05/16.
// Copyright © 2016 Vlad Gorlov. All rights reserved.
//
#if os(iOS) || os(tvOS)
import UIKit
#elseif os(OSX)
import AppKit
#endif
import mcxTypes
import mcxFoundationExtensions
private enum Target {
case center, margins, bounds
case vertically, horizontally
case verticallyToMargins, horizontallyToMargins
case horizontallyToSafeArea, verticallyToSafeArea, toSafeArea
case insets(LayoutConstraint.EdgeInsets), horizontallyWithInsets(LayoutConstraint.EdgeInsets)
}
public class __LayoutConstraintHeight: InstanceHolder<LayoutConstraint> {
public func to(_ constant: CGFloat, relation: LayoutConstraint.LayoutRelation = .equal,
multiplier: CGFloat = 1, _ views: LayoutConstraint.ViewType...) -> [NSLayoutConstraint]
{
return views.map {
NSLayoutConstraint(item: $0, attribute: .height, relatedBy: relation, toItem: nil, attribute: .notAnAttribute,
multiplier: multiplier, constant: constant)
}
}
}
public class __LayoutConstraintSize: InstanceHolder<LayoutConstraint> {
public func to(_ size: CGSize,
relationForHeight: LayoutConstraint.LayoutRelation = .equal,
relationForWidth: LayoutConstraint.LayoutRelation = .equal,
multiplierForHeight: CGFloat = 1, multiplierForWidth: CGFloat = 1,
_ view: LayoutConstraint.ViewType) -> [NSLayoutConstraint]
{
let constraintW = NSLayoutConstraint(item: view, attribute: .width, relatedBy: relationForWidth,
toItem: nil, attribute: .notAnAttribute,
multiplier: multiplierForWidth, constant: size.width)
let constraintH = NSLayoutConstraint(item: view, attribute: .height, relatedBy: relationForHeight,
toItem: nil, attribute: .notAnAttribute,
multiplier: multiplierForHeight, constant: size.height)
return [constraintH, constraintW]
}
public func toDimension(_ dimension: CGFloat, _ view: LayoutConstraint.ViewType) -> [NSLayoutConstraint] {
return to(CGSize(dimension: dimension), view)
}
public func toMinimun(_ size: CGSize, _ view: LayoutConstraint.ViewType) -> [NSLayoutConstraint] {
return to(size, relationForHeight: .greaterThanOrEqual, relationForWidth: .greaterThanOrEqual, view)
}
}
public class __LayoutConstraintPin: InstanceHolder<LayoutConstraint> {
public func toBounds(insets: LayoutConstraint.EdgeInsets, _ views: LayoutConstraint.ViewType...) -> [NSLayoutConstraint] {
return instance.pin(to: .insets(insets), views)
}
public func toBounds(insets: CGFloat, _ views: LayoutConstraint.ViewType...) -> [NSLayoutConstraint] {
return instance.pin(to: .insets(LayoutConstraint.EdgeInsets(dimension: insets)), views)
}
public func toBounds(_ views: LayoutConstraint.ViewType...) -> [NSLayoutConstraint] {
return instance.pin(to: .bounds, views)
}
public func toBounds(in view: LayoutConstraint.ViewType, _ views: LayoutConstraint.ViewType...) -> [NSLayoutConstraint] {
return instance.pin(in: view, to: .bounds, views)
}
public func toMargins(_ views: LayoutConstraint.ViewType...) -> [NSLayoutConstraint] {
return instance.pin(to: .margins, views)
}
public func horizontally(_ views: LayoutConstraint.ViewType...) -> [NSLayoutConstraint] {
return instance.pin(to: .horizontally, views)
}
public func horizontally(in view: LayoutConstraint.ViewType, _ views: LayoutConstraint.ViewType...) -> [NSLayoutConstraint] {
return instance.pin(in: view, to: .horizontally, views)
}
public func horizontallyToMargins(_ views: LayoutConstraint.ViewType...) -> [NSLayoutConstraint] {
return instance.pin(to: .horizontallyToMargins, views)
}
public func vertically(_ views: LayoutConstraint.ViewType...) -> [NSLayoutConstraint] {
return instance.pin(to: .vertically, views)
}
public func verticallyToMargins(_ views: LayoutConstraint.ViewType...) -> [NSLayoutConstraint] {
return instance.pin(to: .verticallyToMargins, views)
}
public func top(_ view: LayoutConstraint.ViewType, relatedBy: LayoutConstraint.LayoutRelation = .equal,
multiplier: CGFloat = 1, constant: CGFloat = 0) -> [NSLayoutConstraint]
{
if let superview = view.superview {
return [NSLayoutConstraint(item: view, attribute: .top, relatedBy: .equal, toItem: superview, attribute: .top,
multiplier: multiplier, constant: constant)]
} else {
return []
}
}
}
public class __LayoutConstraintCenter: InstanceHolder<LayoutConstraint> {
public func xy(viewA: LayoutConstraint.ViewType, viewB: LayoutConstraint.ViewType, multiplierX: CGFloat = 1, constantX: CGFloat = 0,
multiplierY: CGFloat = 1, constantY: CGFloat = 0) -> [NSLayoutConstraint]
{
let constraintX = x(viewA: viewA, viewB: viewB, multiplier: multiplierX, constant: constantX)
let constraintY = y(viewA: viewA, viewB: viewB, multiplier: multiplierY, constant: constantY)
return [constraintX, constraintY]
}
public func xy(_ view: LayoutConstraint.ViewType, multiplierX: CGFloat = 1, constantX: CGFloat = 0,
multiplierY: CGFloat = 1, constantY: CGFloat = 0) -> [NSLayoutConstraint]
{
if let viewB = view.superview {
return xy(viewA: view, viewB: viewB,
multiplierX: multiplierX, constantX: constantX, multiplierY: multiplierY, constantY: constantY)
} else {
return []
}
}
public func y(viewA: LayoutConstraint.ViewType, viewB: LayoutConstraint.ViewType, multiplier: CGFloat = 1,
constant: CGFloat = 0) -> NSLayoutConstraint
{
return NSLayoutConstraint(item: viewA, attribute: .centerY, relatedBy: .equal, toItem: viewB, attribute: .centerY,
multiplier: multiplier, constant: constant)
}
public func y(_ views: LayoutConstraint.ViewType..., multiplier: CGFloat = 1, constant: CGFloat = 0) -> [NSLayoutConstraint] {
var result: [NSLayoutConstraint] = []
views.forEach {
if let viewB = $0.superview {
result.append(y(viewA: $0, viewB: viewB, multiplier: multiplier, constant: constant))
}
}
return result
}
public func y(verticalSpacing: CGFloat, _ views: LayoutConstraint.ViewType...) -> [NSLayoutConstraint] {
var result: [NSLayoutConstraint] = []
views.forEach { view in
if let container = view.superview {
result += [view.centerYAnchor.constraint(equalTo: container.centerYAnchor),
view.topAnchor.constraint(greaterThanOrEqualTo: container.topAnchor, constant: verticalSpacing)]
}
}
return result
}
public func x(viewA: LayoutConstraint.ViewType, viewB: LayoutConstraint.ViewType, multiplier: CGFloat = 1,
constant: CGFloat = 0) -> NSLayoutConstraint
{
return NSLayoutConstraint(item: viewA, attribute: .centerX, relatedBy: .equal, toItem: viewB, attribute: .centerX,
multiplier: multiplier, constant: constant)
}
public func x(_ views: LayoutConstraint.ViewType..., multiplier: CGFloat = 1, constant: CGFloat = 0) -> [NSLayoutConstraint] {
var result: [NSLayoutConstraint] = []
views.forEach {
if let viewB = $0.superview {
result.append(x(viewA: $0, viewB: viewB, multiplier: multiplier, constant: constant))
}
}
return result
}
}
public struct LayoutConstraint {
public init() {}
public var pin: __LayoutConstraintPin {
return __LayoutConstraintPin(instance: self)
}
public var center: __LayoutConstraintCenter {
return __LayoutConstraintCenter(instance: self)
}
public var size: __LayoutConstraintSize {
return __LayoutConstraintSize(instance: self)
}
public var height: __LayoutConstraintHeight {
return __LayoutConstraintHeight(instance: self)
}
public func bindings(_ bindings: [String: ViewType]) -> [String: ViewType] {
return bindings
}
public func metrics(_ metrics: [String: CGFloat]) -> [String: Float] {
return metrics.mapElements { ($0, Float($1)) }
}
#if os(iOS) || os(tvOS)
public typealias LayoutRelation = NSLayoutConstraint.Relation
public typealias ViewType = UIView
public typealias LayoutFormatOptions = NSLayoutConstraint.FormatOptions
public typealias EdgeInsets = UIEdgeInsets
#elseif os(OSX)
public typealias LayoutRelation = NSLayoutConstraint.Relation
public typealias ViewType = NSView
public typealias LayoutFormatOptions = NSLayoutConstraint.FormatOptions
public typealias EdgeInsets = NSEdgeInsets
#endif
public enum Corner: Int {
case bottomTrailing
#if os(iOS) || os(tvOS)
case bottomTrailingMargins
#endif
}
public enum Border: Int {
case leading, trailing, top, bottom
}
public enum Center {
case both, vertically, horizontally
}
}
extension LayoutConstraint {
private func pinAtCenter(in container: ViewType, view: ViewType) -> [NSLayoutConstraint] {
let result = [container.centerXAnchor.constraint(equalTo: view.centerXAnchor),
container.centerYAnchor.constraint(equalTo: view.centerYAnchor),
view.leadingAnchor.constraint(greaterThanOrEqualTo: container.leadingAnchor),
view.topAnchor.constraint(greaterThanOrEqualTo: container.topAnchor)]
return result
}
private func pin(in container: ViewType, to: Target, view: ViewType) -> [NSLayoutConstraint] {
var result: [NSLayoutConstraint] = []
switch to {
case .center:
result = pinAtCenter(in: container, view: view)
case .insets(let insets):
let metrics = ["top": insets.top, "bottom": insets.bottom, "left": insets.left, "right": insets.right]
let metricsValue = metrics.mapElements { ($0, NSNumber(value: Float($1))) }
var constraints: [NSLayoutConstraint] = []
constraints += NSLayoutConstraint.constraints(withVisualFormat: "|-(left)-[v]-(right)-|",
options: [], metrics: metricsValue, views: ["v": view])
constraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-(top)-[v]-(bottom)-|",
options: [], metrics: metricsValue, views: ["v": view])
result = constraints
case .bounds:
result += pin(in: container, to: .horizontally, view: view)
result += pin(in: container, to: .vertically, view: view)
case .margins:
result += pin(in: container, to: .horizontallyToMargins, view: view)
result += pin(in: container, to: .verticallyToMargins, view: view)
case .horizontally:
result += [view.leadingAnchor.constraint(equalTo: container.leadingAnchor),
container.trailingAnchor.constraint(equalTo: view.trailingAnchor)]
case .vertically:
result += [view.topAnchor.constraint(equalTo: container.topAnchor),
container.bottomAnchor.constraint(equalTo: view.bottomAnchor)]
case .horizontallyToMargins:
result = NSLayoutConstraint.constraints(withVisualFormat: "|-[v]-|", options: [], metrics: nil, views: ["v": view])
case .verticallyToMargins:
result = NSLayoutConstraint.constraints(withVisualFormat: "V:|-[v]-|", options: [], metrics: nil, views: ["v": view])
case .horizontallyToSafeArea:
#if !os(macOS)
result = [view.leadingAnchor.constraint(equalTo: container.safeAreaLayoutGuide.leadingAnchor),
container.safeAreaLayoutGuide.trailingAnchor.constraint(equalTo: view.trailingAnchor)]
#else
fatalError()
#endif
case .verticallyToSafeArea:
#if !os(macOS)
result = [view.topAnchor.constraint(equalTo: container.safeAreaLayoutGuide.topAnchor),
container.safeAreaLayoutGuide.bottomAnchor.constraint(equalTo: view.bottomAnchor)]
#else
fatalError()
#endif
case .toSafeArea:
result = pin(in: container, to: .horizontallyToSafeArea, view: view)
+ pin(in: container, to: .verticallyToSafeArea, view: view)
case .horizontallyWithInsets(let insets):
result = NSLayoutConstraint.constraints(withVisualFormat: "|-\(insets.left)-[v]-\(insets.right)-|",
options: [], metrics: nil, views: ["v": view])
}
return result
}
private func pin(to: Target, _ view: ViewType) -> [NSLayoutConstraint] {
var result: [NSLayoutConstraint] = []
if let superview = view.superview {
result = pin(in: superview, to: to, view: view)
}
return result
}
fileprivate func pin(in view: ViewType, to: Target, _ views: [ViewType]) -> [NSLayoutConstraint] {
let result = views.map { pin(in: view, to: to, view: $0) }.reduce([]) { $0 + $1 }
return result
}
fileprivate func pin(to: Target, _ views: ViewType...) -> [NSLayoutConstraint] {
return pin(to: to, views)
}
fileprivate func pin(to: Target, _ views: [ViewType]) -> [NSLayoutConstraint] {
let result = views.map { pin(to: to, $0) }.reduce([]) { $0 + $1 }
return result
}
}
extension LayoutConstraint {
private func pin(in container: ViewType, to: Border, view: ViewType) -> [NSLayoutConstraint] {
let result: [NSLayoutConstraint]
switch to {
case .leading:
result = pin(to: .vertically, view) + [pinLeadings(viewA: container, viewB: view)]
case .trailing:
result = pin(to: .vertically, view) + [pinTrailings(viewA: container, viewB: view)]
case .top:
result = pin(to: .horizontally, view) + [pinTops(viewA: container, viewB: view)]
case .bottom:
result = pin(to: .horizontally, view) + [pinBottoms(viewA: container, viewB: view)]
}
return result
}
private func pin(to: Border, _ view: ViewType) -> [NSLayoutConstraint] {
var result: [NSLayoutConstraint] = []
if let superview = view.superview {
result = pin(in: superview, to: to, view: view)
}
return result
}
public func pin(in view: ViewType, to: Border, _ views: ViewType...) -> [NSLayoutConstraint] {
let result = views.map { pin(in: view, to: to, view: $0) }.reduce([]) { $0 + $1 }
return result
}
public func pin(to: Border, _ views: ViewType...) -> [NSLayoutConstraint] {
let result = views.map { pin(to: to, $0) }.reduce([]) { $0 + $1 }
return result
}
}
extension LayoutConstraint {
private func pin(in container: ViewType, at: Center, view: ViewType) -> [NSLayoutConstraint] {
let result: [NSLayoutConstraint]
switch at {
case .both:
result = pin(in: container, at: .vertically, view: view) + pin(in: container, at: .horizontally, view: view)
case .vertically:
result = [container.centerYAnchor.constraint(equalTo: view.centerYAnchor),
view.topAnchor.constraint(greaterThanOrEqualTo: container.topAnchor)]
case .horizontally:
result = [container.centerXAnchor.constraint(equalTo: view.centerXAnchor),
view.leadingAnchor.constraint(greaterThanOrEqualTo: container.leadingAnchor)]
}
return result
}
private func pin(at: Center, _ view: ViewType) -> [NSLayoutConstraint] {
var result: [NSLayoutConstraint] = []
if let superview = view.superview {
result = pin(in: superview, at: at, view: view)
}
return result
}
public func pin(in view: ViewType, at: Center, _ views: ViewType...) -> [NSLayoutConstraint] {
let result = views.map { pin(in: view, at: at, view: $0) }.reduce([]) { $0 + $1 }
return result
}
public func pin(at: Center, _ views: ViewType...) -> [NSLayoutConstraint] {
let result = views.map { pin(at: at, $0) }.reduce([]) { $0 + $1 }
return result
}
}
extension LayoutConstraint {
private func pin(in container: ViewType, to: Corner, view: ViewType) -> [NSLayoutConstraint] {
let result: [NSLayoutConstraint]
switch to {
case .bottomTrailing:
result = [container.bottomAnchor.constraint(equalTo: view.bottomAnchor),
container.trailingAnchor.constraint(equalTo: view.trailingAnchor)]
#if os(iOS) || os(tvOS)
case .bottomTrailingMargins:
result = [container.layoutMarginsGuide.bottomAnchor.constraint(equalTo: view.bottomAnchor),
container.layoutMarginsGuide.trailingAnchor.constraint(equalTo: view.trailingAnchor)]
#endif
}
return result
}
private func pinInSuperView(to: Corner, _ view: ViewType) -> [NSLayoutConstraint] {
var result: [NSLayoutConstraint] = []
if let superview = view.superview {
result = pin(in: superview, to: to, view: view)
}
return result
}
public func pin(in view: ViewType, to: Corner, _ views: ViewType...) -> [NSLayoutConstraint] {
let result = views.map { pin(in: view, to: to, view: $0) }.reduce([]) { $0 + $1 }
return result
}
public func pinInSuperView(to: Corner, _ views: ViewType...) -> [NSLayoutConstraint] {
let result = views.map { pinInSuperView(to: to, $0) }.reduce([]) { $0 + $1 }
return result
}
}
extension LayoutConstraint {
public func withFormat(_ format: String, options: LayoutFormatOptions = [],
metrics: [String: Float] = [:], _ views: [ViewType]) -> [NSLayoutConstraint]
{
let parsedInfo = parseFormat(format: format, views: views)
let metrics = metrics.mapValues { NSNumber(value: $0) }
let result = NSLayoutConstraint.constraints(withVisualFormat: parsedInfo.0, options: options, metrics: metrics,
views: parsedInfo.1)
return result
}
public func withFormat(_ format: String, options: LayoutFormatOptions = [],
metrics: [String: Float] = [:], _ views: ViewType...) -> [NSLayoutConstraint]
{
return withFormat(format, options: options, metrics: metrics, views)
}
public func withFormat(_ format: String, options: LayoutFormatOptions = [],
metrics: [String: Float] = [:], forEveryViewIn: ViewType...) -> [NSLayoutConstraint]
{
let result = forEveryViewIn.map { withFormat(format, options: options, metrics: metrics, $0) }.reduce([]) { $0 + $1 }
return result
}
private func parseFormat(format: String, views: [ViewType]) -> (String, [String: Any]) {
let viewPlaceholderCharacter = "*"
var viewBindings: [String: Any] = [:]
var parsedFormat = format
for (index, view) in views.enumerated() {
let viewBinding = "v\(index)"
viewBindings[viewBinding] = view
parsedFormat = parsedFormat.replacingFirstOccurrence(of: viewPlaceholderCharacter, with: viewBinding)
}
return (parsedFormat, viewBindings)
}
// MARK: - Dimensions
public func constrainWidth(constant: CGFloat, relation: LayoutRelation = .equal,
multiplier: CGFloat = 1, _ views: ViewType...) -> [NSLayoutConstraint]
{
return views.map {
NSLayoutConstraint(item: $0, attribute: .width, relatedBy: relation, toItem: nil, attribute: .notAnAttribute,
multiplier: multiplier, constant: constant)
}
}
public func equalWidth(viewA: ViewType, viewB: ViewType, relation: LayoutRelation = .equal,
multiplier: CGFloat = 1, constant: CGFloat = 0) -> NSLayoutConstraint
{
return NSLayoutConstraint(item: viewA, attribute: .width, relatedBy: relation, toItem: viewB, attribute: .width,
multiplier: multiplier, constant: constant)
}
public func equalHeight(viewA: ViewType, viewB: ViewType, relation: LayoutRelation = .equal,
multiplier: CGFloat = 1, constant: CGFloat = 0) -> NSLayoutConstraint
{
return NSLayoutConstraint(item: viewA, attribute: .height, relatedBy: relation, toItem: viewB, attribute: .height,
multiplier: multiplier, constant: constant)
}
public func equalHeight(_ views: [ViewType]) -> [NSLayoutConstraint] {
var constraints: [NSLayoutConstraint] = []
var previousView: ViewType?
for view in views {
if let previousView = previousView {
constraints.append(equalHeight(viewA: previousView, viewB: view))
}
previousView = view
}
return constraints
}
public func equalSize(viewA: ViewType, viewB: ViewType) -> [NSLayoutConstraint] {
let cH = NSLayoutConstraint(item: viewA, attribute: .height, relatedBy: .equal,
toItem: viewB, attribute: .height,
multiplier: 1, constant: 0)
let cW = NSLayoutConstraint(item: viewA, attribute: .width, relatedBy: .equal,
toItem: viewB, attribute: .width,
multiplier: 1, constant: 0)
return [cH, cW]
}
public func constrainAspectRatio(view: ViewType, aspectRatio: CGFloat = 1) -> NSLayoutConstraint {
return NSLayoutConstraint(item: view, attribute: .width, relatedBy: .equal, toItem: view, attribute: .height,
multiplier: aspectRatio, constant: 0)
}
// MARK: - Pinning
public func pinLeading(_ view: ViewType, multiplier: CGFloat = 1, constant: CGFloat = 0) -> [NSLayoutConstraint] {
if let superview = view.superview {
return [NSLayoutConstraint(item: view, attribute: .leading, relatedBy: .equal, toItem: superview, attribute: .leading,
multiplier: multiplier, constant: constant)]
} else {
return []
}
}
public func pinLeadings(viewA: ViewType, viewB: ViewType, multiplier: CGFloat = 1,
constant: CGFloat = 0) -> NSLayoutConstraint
{
return NSLayoutConstraint(item: viewA, attribute: .leading, relatedBy: .equal, toItem: viewB, attribute: .leading,
multiplier: multiplier, constant: constant)
}
public func pinTrailings(viewA: ViewType, viewB: ViewType, multiplier: CGFloat = 1,
constant: CGFloat = 0) -> NSLayoutConstraint
{
return NSLayoutConstraint(item: viewA, attribute: .trailing, relatedBy: .equal, toItem: viewB, attribute: .trailing,
multiplier: multiplier, constant: constant)
}
public func pinTrailing(_ view: ViewType, multiplier: CGFloat = 1, constant: CGFloat = 0) -> [NSLayoutConstraint] {
if let superview = view.superview {
return [pinTrailings(viewA: view, viewB: superview, multiplier: multiplier, constant: constant)]
} else {
return []
}
}
public func pinCenterToLeading(viewA: ViewType, viewB: ViewType, multiplier: CGFloat = 1,
constant: CGFloat = 0) -> NSLayoutConstraint
{
return NSLayoutConstraint(item: viewA, attribute: .centerX, relatedBy: .equal, toItem: viewB, attribute: .leading,
multiplier: multiplier, constant: constant)
}
public func pinCenterToTrailing(viewA: ViewType, viewB: ViewType, multiplier: CGFloat = 1,
constant: CGFloat = 0) -> NSLayoutConstraint
{
return NSLayoutConstraint(item: viewA, attribute: .centerX, relatedBy: .equal, toItem: viewB, attribute: .trailing,
multiplier: multiplier, constant: constant)
}
public func pinTops(viewA: ViewType, viewB: ViewType, relatedBy: LayoutRelation = .equal,
multiplier: CGFloat = 1, constant: CGFloat = 0) -> NSLayoutConstraint
{
return NSLayoutConstraint(item: viewA, attribute: .top, relatedBy: .equal, toItem: viewB, attribute: .top,
multiplier: multiplier, constant: constant)
}
public func pinBottoms(viewA: ViewType, viewB: ViewType, relatedBy: LayoutRelation = .equal,
multiplier: CGFloat = 1, constant: CGFloat = 0) -> NSLayoutConstraint
{
return NSLayoutConstraint(item: viewA, attribute: .bottom, relatedBy: .equal, toItem: viewB, attribute: .bottom,
multiplier: multiplier, constant: constant)
}
public func pinBottom(_ view: ViewType, relatedBy: LayoutRelation = .equal,
multiplier: CGFloat = 1, constant: CGFloat = 0) -> [NSLayoutConstraint]
{
if let superview = view.superview {
return [NSLayoutConstraint(item: view, attribute: .bottom, relatedBy: .equal, toItem: superview, attribute: .bottom,
multiplier: multiplier, constant: constant)]
} else {
return []
}
}
public func pinTopToBottom(viewA: ViewType, viewB: ViewType, multiplier: CGFloat = 1,
constant: CGFloat = 0) -> NSLayoutConstraint
{
return NSLayoutConstraint(item: viewA, attribute: .top, relatedBy: .equal, toItem: viewB, attribute: .bottom,
multiplier: multiplier, constant: constant)
}
public func pinBottomToTop(viewA: ViewType, viewB: ViewType, multiplier: CGFloat = 1,
constant: CGFloat = 0) -> NSLayoutConstraint
{
return NSLayoutConstraint(item: viewA, attribute: .bottom, relatedBy: .equal, toItem: viewB, attribute: .top,
multiplier: multiplier, constant: constant)
}
#if os(iOS) || os(tvOS)
public func pinToEdge(_ edge: UIRectEdge, view: ViewType) -> [NSLayoutConstraint] {
if edge == .top {
return withFormat("|[*]|", view) + withFormat("V:|[*]", view)
} else if edge == .bottom {
return withFormat("|[*]|", view) + withFormat("V:[*]|", view)
} else if edge == .left {
return withFormat("|[*]", view) + withFormat("V:|[*]|", view)
} else if edge == .right {
return withFormat("[*]|", view) + withFormat("V:|[*]|", view)
} else {
return []
}
}
#endif
}
extension LayoutConstraint {
public func distributeHorizontally(_ views: [ViewType], spacing: CGFloat) -> [NSLayoutConstraint] {
let format = repeatElement("[*]", count: views.count).joined(separator: "-\(spacing)-")
return withFormat(format, views)
}
public func alignCenterY(_ views: [ViewType]) -> [NSLayoutConstraint] {
var constraints: [NSLayoutConstraint] = []
var previousView: ViewType?
for view in views {
if let previousView = previousView {
constraints.append(center.y(viewA: previousView, viewB: view))
}
previousView = view
}
return constraints
}
}
extension Array where Element: NSLayoutConstraint {
public func activate(priority: LayoutPriority? = nil) {
if let priority = priority {
forEach { $0.priority = priority }
}
NSLayoutConstraint.activate(self)
}
/// I.e. `999` fix for Apple layout engine issues observed in Cells.
public func activateApplyingNonRequiredLastItemPriotity() {
last?.priority = .required - 1
NSLayoutConstraint.activate(self)
}
public func deactivate() {
NSLayoutConstraint.deactivate(self)
}
}
| mit | 4b1a083061c22370c364ea20e011084f | 40.778774 | 135 | 0.631413 | 4.66611 | false | false | false | false |
RoverPlatform/rover-ios-beta | Sources/UI/Views/BarcodeCell.swift | 2 | 1650 | //
// BarcodeCell.swift
// Rover
//
// Created by Sean Rucker on 2018-04-20.
// Copyright © 2018 Rover Labs Inc. All rights reserved.
//
import UIKit
class BarcodeCell: BlockCell {
let imageView: UIImageView = {
let imageView = UIImageView()
// Using stretch fit because we've ensured that the image will scale aspect-correct, so will always have the
// correct aspect ratio (because auto-height will be always on), and we also are using integer scaling to ensure
// a sharp scale of the pixels. While we could use .scaleToFit, .scaleToFill will avoid the barcode
// leaving any unexpected gaps around the outside in case of lack of agreement.
imageView.contentMode = .scaleToFill
imageView.accessibilityLabel = "Barcode"
#if swift(>=4.2)
imageView.layer.magnificationFilter = CALayerContentsFilter.nearest
#else
imageView.layer.magnificationFilter = kCAFilterNearest
#endif
return imageView
}()
override var content: UIView? {
return imageView
}
override func configure(with block: Block) {
super.configure(with: block)
guard let barcodeBlock = block as? BarcodeBlock else {
imageView.isHidden = true
return
}
imageView.isHidden = false
imageView.image = nil
let barcode = barcodeBlock.barcode
guard let barcodeImage = barcode.cgImage else {
imageView.image = nil
return
}
imageView.image = UIImage(cgImage: barcodeImage)
}
}
| mit | 23d680bed440dbb5aac72068ea64f63b | 28.446429 | 120 | 0.625834 | 5.027439 | false | false | false | false |
1amageek/StripeAPI | StripeAPI/URLEncodedSerialization.swift | 1 | 5250 | //
// URLEncodedSerialization.swift
// StripeAPI
//
// Created by nori on 2017/10/19.
// Copyright © 2017年 Stamp Inc. All rights reserved.
//
import Foundation
private func escape(_ string: String) -> String {
// Reserved characters defined by RFC 3986
// Reference: https://www.ietf.org/rfc/rfc3986.txt
let generalDelimiters = ":#[]@"
let subDelimiters = "!$&'()*+,;="
let reservedCharacters = generalDelimiters + subDelimiters
var allowedCharacterSet = CharacterSet()
allowedCharacterSet.formUnion(.urlQueryAllowed)
allowedCharacterSet.remove(charactersIn: reservedCharacters)
// Crashes due to internal bug in iOS 7 ~ iOS 8.2.
// References:
// - https://github.com/Alamofire/Alamofire/issues/206
// - https://github.com/AFNetworking/AFNetworking/issues/3028
// return string.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacterSet) ?? string
let batchSize = 50
var index = string.startIndex
var escaped = ""
while index != string.endIndex {
let startIndex = index
let endIndex = string.index(index, offsetBy: batchSize, limitedBy: string.endIndex) ?? string.endIndex
let range = startIndex..<endIndex
let substring = string.substring(with: range)
escaped += substring.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? substring
index = endIndex
}
return escaped
}
private func unescape(_ string: String) -> String {
return CFURLCreateStringByReplacingPercentEscapes(nil, string as CFString, nil) as String
}
/// `URLEncodedSerialization` parses `Data` and `String` as urlencoded,
/// and returns dictionary that represents the data or the string.
public final class _URLEncodedSerialization {
public enum Error: Swift.Error {
case cannotGetStringFromData(Data, String.Encoding)
case cannotGetDataFromString(String, String.Encoding)
case cannotCastObjectToDictionary(Any)
case invalidFormatString(String)
}
/// Returns `[String: String]` that represents urlencoded `Data`.
/// - Throws: URLEncodedSerialization.Error
public static func object(from data: Data, encoding: String.Encoding) throws -> [String: String] {
guard let string = String(data: data, encoding: encoding) else {
throw Error.cannotGetStringFromData(data, encoding)
}
var dictionary = [String: String]()
for pair in string.components(separatedBy: "&") {
let contents = pair.components(separatedBy: "=")
guard contents.count == 2 else {
throw Error.invalidFormatString(string)
}
dictionary[contents[0]] = unescape(contents[1])
}
return dictionary
}
/// Returns urlencoded `Data` from the object.
/// - Throws: URLEncodedSerialization.Error
public static func data(from object: Any, encoding: String.Encoding) throws -> Data {
guard let dictionary = object as? [String: Any] else {
throw Error.cannotCastObjectToDictionary(object)
}
let string = self.string(parentKey: nil, value: dictionary)
guard let data = string.data(using: encoding, allowLossyConversion: false) else {
throw Error.cannotGetDataFromString(string, encoding)
}
return data
}
/// Returns urlencoded `Data` from the string.
public static func string(parentKey: String?, value: [String: Any]) -> String {
let pairs = value.map { key, value -> String in
if value is NSNull {
return "\(escape(key))"
}
var key = key
if let parentKey: String = parentKey {
key = "\(parentKey)[\(key)]"
}
if let dictionary: [String: Any] = value as? [String: Any] {
return self.string(parentKey: key, value: dictionary)
}
if let array: [Any] = value as? [Any] {
return self.string(parentKey: key, value: array)
}
let valueAsString: String = self.string(value: value)
return "\(escape(key))=\(escape(valueAsString))"
}
return pairs.joined(separator: "&")
}
/// Returns urlencoded `Data` from the string.
public static func string(parentKey: String, value: [Any]) -> String {
let pairs = value.map { value -> String in
let key = "\(parentKey)[]"
if let dictionary: [String: Any] = value as? [String: Any] {
return self.string(parentKey: key, value: dictionary)
}
if let array: [Any] = value as? [Any] {
return self.string(parentKey: key, value: array)
}
let valueAsString: String = self.string(value: value)
return "\(escape(key))=\(escape(valueAsString))"
}
return pairs.joined(separator: "&")
}
public static func string(value: Any) -> String {
if let value: String = value as? String {
return value
} else if let value: Bool = value as? Bool {
return value ? "true" : "false"
} else {
return "\(value)"
}
}
}
| mit | e5ac3983092fbd63d295e55fcaadf79b | 35.17931 | 110 | 0.61971 | 4.66726 | false | false | false | false |
mute778/MUtil | MUtil/Classes/MUtil.swift | 1 | 8996 | //
// MUtil.swift
// Pods
//
// Created by mute778 on 2016/12/26.
//
//
import UIKit
@objc public class MUtil: NSObject {
public enum CheckVersionTarget {
case OSVersion
case AppVersion
case BuildVersion
}
// =============================================================================
// MARK: - PublicMethod
// =============================================================================
/**
ログを出力する
- parameter message: 出力文字列
- parameter file: ファイル名(省略)
- parameter function: メソッド名(省略)
- parameter line: 行番号(省略)
*/
public class func log(
_ message: String,
file: String = #file,
function: String = #function,
line: Int = #line
) -> Void {
let filePath = file.components(separatedBy: "/");
let fileName = filePath.last!.components(separatedBy: ".")
let dateStr = self.getGregorianDateString(date: Date(), format: "yyyy-MM-dd HH:mm:ss.sss")
#if DLOG
print("\(dateStr) [\(fileName.first!) \(function) - \(line)]\n\(message)")
#else
// 出力しない
#endif
}
/**
OSバージョン文字列を取得する
- returns: String OSバージョン
*/
public class func getOsVersion() -> String {
return UIDevice.current.systemVersion
}
/**
アプリバージョン文字列を取得する
- returns: String アプリバージョン文字列
*/
public class func getAppVersion() -> String {
return Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String
}
/**
アプリのビルドバージョン文字列を取得する
- returns: String ビルドバージョン文字列
*/
public class func getBuildVersion() -> String {
return Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as! String
}
/**
ベンダーIDを取得する
- returns: String ベンダーID
*/
public class func getVendorId() -> String {
return (UIDevice.current.identifierForVendor?.uuidString)!
}
/**
画面サイズを取得する
- returns: CGSize 画面サイズ
*/
public class func getScreenBounds() -> CGSize {
return UIScreen.main.bounds.size
}
/**
現在のアプリバージョンが指定範囲内であるか確認する
- parameter min: 範囲最小バージョン
- parameter max: 範囲最大バージョン
- return: Bool YES:範囲内, NO:範囲外
*/
public class func checkVersionRange(target: CheckVersionTarget, min: String, max: String) -> Bool {
var currentVersion: String
switch target {
case .OSVersion:
currentVersion = self.getOsVersion()
case .AppVersion:
currentVersion = self.getAppVersion()
case .BuildVersion:
currentVersion = self.getBuildVersion()
}
let minResult = min.compare(currentVersion, options: .numeric)
let maxResult = max.compare(currentVersion, options: .numeric)
if ( (minResult == .orderedAscending || minResult == .orderedSame) && (maxResult == .orderedSame || maxResult == .orderedDescending) ) {
return true
}
return false
}
/**
ローカライズファイルから文字列を取得する
- returns: String
*/
public class func getLocalizedString(_ key: String) -> String {
return NSLocalizedString(key, comment: "");
}
/**
グレゴリオ暦形式で日付文字列を返却する
- parameter date: 変換対象日付
- paremeter format: 出力形式フォーマット
- returns: String
*/
public class func getGregorianDateString(date: Date, format: String) -> String {
// DateFormatter設定
let dateFormat = DateFormatter()
dateFormat.dateFormat = format
// カレンダーをグレゴリオ暦に指定
let calendar = Calendar(identifier: .gregorian)
// DateFormatterに暦をセット
dateFormat.calendar = calendar
return dateFormat.string(from: date)
}
/**
文字列を日付に変換する
- parameter fromString: 変換対象日付文字列
- parameter format: 変換対象日付文字列のフォーマット
- returns: Date
*/
public class func getDate(fromString: String, format: String) -> Date {
// DateFormatter設定
let dateFormat = DateFormatter()
dateFormat.dateFormat = format
dateFormat.locale = Locale.current
return dateFormat.date(from: fromString)!
}
/**
指定URLを開くことができるか確認する
- parameter url: 指定URL文字列
- returns: Bool YES:開くことができる, NO:開くことができない
*/
public class func canOpenURL(_ url: String) -> Bool {
return UIApplication.shared.canOpenURL(URL(string: url)!)
}
/**
指定URLを開く
- parameter url: 指定URL文字列
- returns: Bool YES:開くことができた場合, NO:開くことができなかった場合
*/
public class func openURL(_ url: String) -> Bool {
if ( canOpenURL(url) ) {
// 指定URLを開くことができる場合
// 指定URLを開く
UIApplication.shared.openURL(URL(string: url)!)
return true
}
return false
}
/**
文字列がアプリで設定されているスキームであるか確認する
- parameter scheme: String 確認対象文字列
- returns: Bool YES:設定されている, NO:設定されていない
*/
public class func isAppScheme(_ scheme: String) -> Bool {
let util = MUtil()
let schemeList: Array<String> = util.getAppSchemeList()
for settingScheme: String in schemeList {
if ( settingScheme == scheme ) {
return true
}
}
return false
}
/**
指定文字列をエンコードする
- parameter url: String エンコード対象文字列
- returns: String エンコード後文字列
*/
public class func encodeUrlString(_ url: String) -> String {
return url.addingPercentEncoding(withAllowedCharacters: .alphanumerics)!
}
/**
指定文字列をデコードする
- parameter url: String デコード対象文字列
- returns: String デコード後文字列
*/
public class func decodeUrlString(_ url: String) -> String {
return url.removingPercentEncoding!
}
/**
ラベルの高さを取得する
- parameter label: 表示するUILabel
- returns: CGFloat ラベルの高さ
*/
public class func getLabelHeight(label: UILabel) -> CGFloat {
let attrString = NSAttributedString.init(string: label.text!,
attributes: [NSFontAttributeName:label.font])
let rect = attrString.boundingRect(with: CGSize(width: label.frame.size.width,
height: CGFloat.greatestFiniteMagnitude),
options: .usesLineFragmentOrigin,
context: nil)
return rect.height
}
/**
アプリアイコンにバッジを設定する
- parameter badgeNumber: 設定数値(0の場合は削除)
*/
public class func setAppBadge(_ badgeNum: Int) -> Void {
UIApplication.shared.applicationIconBadgeNumber = badgeNum
}
// =============================================================================
// MARK: - PrivateMethod
// =============================================================================
/**
設定されているアプリのスキームを全て取得する
- returns: Array<String>
*/
private func getAppSchemeList() -> Array<String> {
var result: Array<String> = []
let bundleUrlTypes = Bundle.main.infoDictionary?["CFBundleURLTypes"]
if ( bundleUrlTypes != nil ) {
let bundleUrlTypesArray = bundleUrlTypes as! NSArray
for bundleUrlType in bundleUrlTypesArray {
let urlSchemes = (bundleUrlType as! NSDictionary)["CFBundleURLSchemes"]
if ( urlSchemes != nil ) {
let schemeStr: String = (urlSchemes as! NSArray)[0] as! String
result.append(schemeStr)
}
}
}
return result
}
}
| mit | d1d4fdd35c09d2dab29f222996677bf1 | 27.649635 | 144 | 0.541911 | 4.410112 | false | false | false | false |
danielhour/DINC | DINC/PlaidService.swift | 1 | 11651 | //
// Plaid.swift
// Plaid Swift Wrapper
//
// Created by Cameron Smith on 4/20/15.
// Copyright (c) 2015 Cameron Smith. All rights reserved.
//
//import Foundation
//import Alamofire
//import SwiftyJSON
//
//
///**
// *
// */
//class PlaidService {
//
// ///
// var currentRequest:Request?
// ///
// var allRequests:[Request]?
//
//
// init(){
// self.currentRequest = nil
// self.allRequests = [Request]()
// }
//
//
// ///
// enum Router: URLRequestConvertible {
//
// ///
// case FetchTransactions([String: AnyObject])
//
//
// ///
// var method: Alamofire.Method {
// switch self {
// case .FetchTransactions:
// return .POST
// }
// }
//
// ///
// var path: String {
// switch self {
// case .FetchTransactions:
// return "connect/get"
// }
// }
//
// ///
// var URLRequest: NSMutableURLRequest {
// let URL = NSURL(string: Constants.Plaid.baseURLString)!
// let mutableURLRequest = NSMutableURLRequest(URL: URL.URLByAppendingPathComponent(path))
// mutableURLRequest.HTTPMethod = method.rawValue
//
// switch self {
// case .FetchTransactions(let parameters):
// return ParameterEncoding.JSON.encode(mutableURLRequest, parameters: parameters).0
// }
// }
// }
//
//
// /**
// Performs an API request
//
// ***.Success:*** convert value to JSON & pass it through the completion block
//
// ***.Failure:*** pass error through the completion block
//
// - parameter URLRequest: URLRequestConvertible
// - parameter completion: ((error:NSError?, json: JSON?) ->())?)
//
// - returns: Void
// */
// func makeAPIRequest(URLRequest: URLRequestConvertible, completion: ((error:NSError?, json: JSON?) -> ())?) {
//
// currentRequest = request(URLRequest).responseJSON { (response) -> Void in
// switch response.result {
//
// case .Success:
// guard let value = response.result.value else {
// let userInfo = [NSLocalizedFailureReasonErrorKey : "Value could not be found."]
// let error = NSError(domain: "APIErrorWithJsonValueDomain", code: 404, userInfo: userInfo)
// completion!(error: error, json: nil)
// return
// }
//
// let json = JSON(value)
// completion!(error: nil, json: json)
//
// case .Failure(let error):
// completion!(error: error, json: nil)
// }
// }
//
// allRequests!.append(self.currentRequest!)
// }
//
//
//
//
//
//
//
//
//
//
// //---------------------------------------------------------------------------------------------------------
//
// //MARK: - Properties
//
// let baseURL = Constants.Plaid.baseURLString
// let clientId = Constants.Plaid.clientID
// let secret = Constants.Plaid.secret
//
//
//
// //
// func PS_addUser(userType: Type, username: String, password: String, pin: String?, institution: Institution, completion: (response: NSURLResponse?, accessToken:String, mfaType:String?, mfa:[[String:AnyObject]]?, accounts: [Account]?, transactions: [Transaction]?, error:NSError?) -> ()) {
//
// let institutionStr = institution.rawValue
// let optionsDict: [String:AnyObject] = ["list":true]
// let optionsDictStr = dictToString(optionsDict)
//
// var urlString:String?
// if pin != nil {
// urlString = "\(baseURL)connect?client_id=\(clientId)&secret=\(secret)&username=\(username)&password=\(password.encodValue)&pin=\(pin!)&type=\(institutionStr)&\(optionsDictStr.encodValue)"
// }
// else {
// urlString = "\(baseURL)connect?client_id=\(clientId)&secret=\(secret)&username=\(username)&password=\(password.encodValue)&type=\(institutionStr)&options=\(optionsDictStr.encodValue)"
// }
//
// let url:NSURL! = NSURL(string: urlString!)
// let request = NSMutableURLRequest(URL: url)
// request.HTTPMethod = "POST"
//
// let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: {
// data, response, error in
// var mfaDict:[[String:AnyObject]]?
// var type:String?
//
// do {
// let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary
// guard jsonResult?.valueForKey("code") as? Int != 1303 else { throw PlaidError.InstitutionNotAvailable }
// guard jsonResult!.valueForKey("code") as? Int != 1200 else {throw PlaidError.InvalidCredentials(jsonResult!.valueForKey("resolve") as! String)}
// guard jsonResult!.valueForKey("code") as? Int != 1005 else {throw PlaidError.CredentialsMissing(jsonResult!.valueForKey("resolve") as! String)}
// guard jsonResult!.valueForKey("code") as? Int != 1601 else {throw PlaidError.InstitutionNotAvailable}
//
// if let token:String = jsonResult?.valueForKey("access_token") as? String {
// if let mfaResponse = jsonResult!.valueForKey("mfa") as? [[String:AnyObject]] {
// mfaDict = mfaResponse
// if let typeMfa = jsonResult!.valueForKey("type") as? String {
// type = typeMfa
// }
// completion(response: response, accessToken: token, mfaType: type, mfa: mfaDict, accounts: nil, transactions: nil, error: error)
// } else {
// let acctsArray:[[String:AnyObject]] = jsonResult?.valueForKey("accounts") as! [[String:AnyObject]]
// let accts = acctsArray.map{Account(account: $0)}
// let trxnArray:[[String:AnyObject]] = jsonResult?.valueForKey("transactions") as! [[String:AnyObject]]
// let trxns = trxnArray.map{Transaction(transaction: $0)}
//
// completion(response: response, accessToken: token, mfaType: nil, mfa: nil, accounts: accts, transactions: trxns, error: error)
// }
// } else {
// //Handle invalid cred login
// }
//
// } catch {
// magic("Error \(error)")
// }
//
// })
// task.resume()
// }
//
//
//
// func PS_submitMFAResponse(accessToken: String, code:Bool?, response: String, completion: (response: NSURLResponse?, accounts: [Account]?, transactions: [Transaction]?, error: NSError?) -> ()) {
// var urlString:String?
//
// let optionsDict: [String:AnyObject] = ["send_method": ["type":response]]
// let optionsDictStr = dictToString(optionsDict)
//
// if code == true {
// urlString = "\(baseURL)connect/step?client_id=\(clientId)&secret=\(secret)&access_token=\(accessToken)&options=\(optionsDictStr.encodValue)"
// magic("urlString: \(urlString!)")
// } else {
// urlString = "\(baseURL)connect/step?client_id=\(clientId)&secret=\(secret)&access_token=\(accessToken)&mfa=\(response.encodValue)"
// magic("urlString: \(urlString!)")
// }
//
// let url:NSURL! = NSURL(string: urlString!)
// let request = NSMutableURLRequest(URL: url)
// request.HTTPMethod = "POST"
//
// let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: {
// data, response, error in
//
// do {
// let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary
//
// magic(jsonResult)
//
// guard jsonResult?.valueForKey("code") as? Int != 1303 else { throw PlaidError.InstitutionNotAvailable }
// guard jsonResult?.valueForKey("code") as? Int != 1203 else { throw PlaidError.IncorrectMfa(jsonResult!.valueForKey("resolve") as! String)}
// guard jsonResult?.valueForKey("accounts") != nil else { throw JsonError.Empty }
//
// let acctsArray:[[String:AnyObject]] = jsonResult?.valueForKey("accounts") as! [[String:AnyObject]]
// let accts = acctsArray.map{Account(account: $0)}
// let trxnArray:[[String:AnyObject]] = jsonResult?.valueForKey("transactions") as! [[String:AnyObject]]
// let trxns = trxnArray.map{Transaction(transaction: $0)}
//
// completion(response: response, accounts: accts, transactions: trxns, error: error)
//
// } catch {
// magic("error: \(error)")
// }
// })
//
// task.resume()
// }
//
//
// //MARK: Get balance
// func PS_getUserBalance(accessToken: String, completion: (response: NSURLResponse?, accounts:[Account], error:NSError?) -> ()) {
//
// let urlString:String = "\(baseURL)balance?client_id=\(clientId)&secret=\(secret)&access_token=\(accessToken)"
// let url:NSURL! = NSURL(string: urlString)
//
// let task = NSURLSession.sharedSession().dataTaskWithURL(url) {
// data, response, error in
//
// do {
// let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary
// magic("jsonResult: \(jsonResult!)")
// guard jsonResult?.valueForKey("code") as? Int != 1303 else { throw PlaidError.InstitutionNotAvailable }
// guard jsonResult?.valueForKey("code") as? Int != 1105 else { throw PlaidError.BadAccessToken }
// guard let dataArray:[[String:AnyObject]] = jsonResult?.valueForKey("accounts") as? [[String : AnyObject]] else { throw JsonError.Empty }
// let userAccounts = dataArray.map{Account(account: $0)}
// completion(response: response, accounts: userAccounts, error: error)
//
// } catch {
// magic("JSON parsing error (PS_getUserBalance): \(error)")
// }
// }
// task.resume()
// }
//
//
// //---------------------------------------------------------------------------------------------------------
//
// //MARK: - Private Helper Methods
//
//
// private func dictToString(value: AnyObject) -> NSString {
// if NSJSONSerialization.isValidJSONObject(value) {
//
// do {
// let data = try NSJSONSerialization.dataWithJSONObject(value, options: NSJSONWritingOptions.PrettyPrinted)
// if let string = NSString(data: data, encoding: NSUTF8StringEncoding) {
// return string
// }
// } catch _ as NSError {
// print("JSON Parsing error")
// }
// }
// return ""
// }
//
//}
//
//
//
//
//
//
//
//
| mit | 729272d5daf2ea4517e85554d00ebb13 | 40.024648 | 293 | 0.528882 | 4.353886 | false | false | false | false |
harenbrs/swix | swixUseCases/swix-iOS/swix/matrix/operators.swift | 4 | 5632 | //
// twoD-operators.swift
// swix
//
// Created by Scott Sievert on 7/9/14.
// Copyright (c) 2014 com.scott. All rights reserved.
//
import Foundation
import Accelerate
func make_operator(lhs: matrix, operation: String, rhs: matrix)->matrix{
assert(lhs.shape.0 == rhs.shape.0, "Sizes must match!")
assert(lhs.shape.1 == rhs.shape.1, "Sizes must match!")
var result = zeros_like(lhs) // real result
var lhsM = lhs.flat
var rhsM = rhs.flat
var resM:ndarray = zeros_like(lhsM) // flat ndarray
if operation=="+" {resM = lhsM + rhsM}
else if operation=="-" {resM = lhsM - rhsM}
else if operation=="*" {resM = lhsM * rhsM}
else if operation=="/" {resM = lhsM / rhsM}
else if operation=="<" {resM = lhsM < rhsM}
else if operation==">" {resM = lhsM > rhsM}
else if operation==">=" {resM = lhsM >= rhsM}
else if operation=="<=" {resM = lhsM <= rhsM}
result.flat.grid = resM.grid
return result
}
func make_operator(lhs: matrix, operation: String, rhs: Double)->matrix{
var result = zeros_like(lhs) // real result
// var lhsM = asmatrix(lhs.grid) // flat
var lhsM = lhs.flat
var resM:ndarray = zeros_like(lhsM) // flat matrix
if operation=="+" {resM = lhsM + rhs}
else if operation=="-" {resM = lhsM - rhs}
else if operation=="*" {resM = lhsM * rhs}
else if operation=="/" {resM = lhsM / rhs}
else if operation=="<" {resM = lhsM < rhs}
else if operation==">" {resM = lhsM > rhs}
else if operation==">=" {resM = lhsM >= rhs}
else if operation=="<=" {resM = lhsM <= rhs}
result.flat.grid = resM.grid
return result
}
func make_operator(lhs: Double, operation: String, rhs: matrix)->matrix{
var result = zeros_like(rhs) // real result
// var rhsM = asmatrix(rhs.grid) // flat
var rhsM = rhs.flat
var resM:ndarray = zeros_like(rhsM) // flat matrix
if operation=="+" {resM = lhs + rhsM}
else if operation=="-" {resM = lhs - rhsM}
else if operation=="*" {resM = lhs * rhsM}
else if operation=="/" {resM = lhs / rhsM}
else if operation=="<" {resM = lhs < rhsM}
else if operation==">" {resM = lhs > rhsM}
else if operation==">=" {resM = lhs >= rhsM}
else if operation=="<=" {resM = lhs <= rhsM}
result.flat.grid = resM.grid
return result
}
// DOT PRODUCT
infix operator *! {associativity none precedence 140}
func *! (lhs: matrix, rhs: matrix) -> matrix{
return dot(lhs, rhs)}
// SOLVE
infix operator !/ {associativity none precedence 140}
func !/ (lhs: matrix, rhs: ndarray) -> ndarray{
return solve(lhs, rhs)}
// EQUALITY
func ~== (lhs: matrix, rhs: matrix) -> Bool{
return (rhs.flat ~== lhs.flat)}
infix operator == {associativity none precedence 140}
func == (lhs: matrix, rhs: matrix)->matrix{
return (lhs.flat == rhs.flat).reshape(lhs.shape)
}
infix operator !== {associativity none precedence 140}
func !== (lhs: matrix, rhs: matrix)->matrix{
return (lhs.flat !== rhs.flat).reshape(lhs.shape)
}
/// ELEMENT WISE OPERATORS
// PLUS
infix operator + {associativity none precedence 140}
func + (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, "+", rhs)}
func + (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, "+", rhs)}
func + (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, "+", rhs)}
// MINUS
infix operator - {associativity none precedence 140}
func - (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, "-", rhs)}
func - (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, "-", rhs)}
func - (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, "-", rhs)}
// TIMES
infix operator * {associativity none precedence 140}
func * (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, "*", rhs)}
func * (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, "*", rhs)}
func * (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, "*", rhs)}
// DIVIDE
infix operator / {associativity none precedence 140}
func / (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, "/", rhs)
}
func / (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, "/", rhs)}
func / (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, "/", rhs)}
// LESS THAN
infix operator < {associativity none precedence 140}
func < (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, "<", rhs)}
func < (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, "<", rhs)}
func < (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, "<", rhs)}
// GREATER THAN
infix operator > {associativity none precedence 140}
func > (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, ">", rhs)}
func > (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, ">", rhs)}
func > (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, ">", rhs)}
// GREATER THAN OR EQUAL
infix operator >= {associativity none precedence 140}
func >= (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, "=>", rhs)}
func >= (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, "=>", rhs)}
func >= (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, "=>", rhs)}
// LESS THAN OR EQUAL
infix operator <= {associativity none precedence 140}
func <= (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, "=>", rhs)}
func <= (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, "=>", rhs)}
func <= (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, "=>", rhs)} | mit | b00d245f194c6c1b1083b915b9a256f5 | 36.553333 | 72 | 0.628018 | 3.316843 | false | false | false | false |
ben-ng/swift | test/stdlib/Strideable.swift | 1 | 6894 | //===--- Strideable.swift - Tests for strided iteration -------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// RUN: %target-run-simple-swift
// REQUIRES: executable_test
//
import StdlibUnittest
// Check that the generic parameter is called 'Element'.
protocol TestProtocol1 {}
extension StrideToIterator where Element : TestProtocol1 {
var _elementIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
extension StrideTo where Element : TestProtocol1 {
var _elementIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
extension StrideThroughIterator where Element : TestProtocol1 {
var _elementIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
extension StrideThrough where Element : TestProtocol1 {
var _elementIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
var StrideTestSuite = TestSuite("Strideable")
struct R : Strideable {
typealias Distance = Int
var x: Int
init(_ x: Int) {
self.x = x
}
func distance(to rhs: R) -> Int {
return rhs.x - x
}
func advanced(by n: Int) -> R {
return R(x + n)
}
}
StrideTestSuite.test("Double") {
func checkOpen(from start: Double, to end: Double, by stepSize: Double, sum: Double) {
// Work on Doubles
expectEqual(
sum,
stride(from: start, to: end, by: stepSize).reduce(0.0, +))
}
func checkClosed(from start: Double, through end: Double, by stepSize: Double, sum: Double) {
// Work on Doubles
expectEqual(
sum,
stride(from: start, through: end, by: stepSize).reduce(0.0, +))
}
checkOpen(from: 1.0, to: 15.0, by: 3.0, sum: 35.0)
checkOpen(from: 1.0, to: 16.0, by: 3.0, sum: 35.0)
checkOpen(from: 1.0, to: 17.0, by: 3.0, sum: 51.0)
checkOpen(from: 1.0, to: -13.0, by: -3.0, sum: -25.0)
checkOpen(from: 1.0, to: -14.0, by: -3.0, sum: -25.0)
checkOpen(from: 1.0, to: -15.0, by: -3.0, sum: -39.0)
checkOpen(from: 4.0, to: 16.0, by: -3.0, sum: 0.0)
checkOpen(from: 1.0, to: -16.0, by: 3.0, sum: 0.0)
checkClosed(from: 1.0, through: 15.0, by: 3.0, sum: 35.0)
checkClosed(from: 1.0, through: 16.0, by: 3.0, sum: 51.0)
checkClosed(from: 1.0, through: 17.0, by: 3.0, sum: 51.0)
checkClosed(from: 1.0, through: -13.0, by: -3.0, sum: -25.0)
checkClosed(from: 1.0, through: -14.0, by: -3.0, sum: -39.0)
checkClosed(from: 1.0, through: -15.0, by: -3.0, sum: -39.0)
checkClosed(from: 4.0, through: 16.0, by: -3.0, sum: 0.0)
checkClosed(from: 1.0, through: -16.0, by: 3.0, sum: 0.0)
}
StrideTestSuite.test("HalfOpen") {
func check(from start: Int, to end: Int, by stepSize: Int, sum: Int) {
// Work on Ints
expectEqual(
sum,
stride(from: start, to: end, by: stepSize).reduce(
0, +))
// Work on an arbitrary RandomAccessIndex
expectEqual(
sum,
stride(from: R(start), to: R(end), by: stepSize).reduce(0) { $0 + $1.x })
}
check(from: 1, to: 15, by: 3, sum: 35) // 1 + 4 + 7 + 10 + 13
check(from: 1, to: 16, by: 3, sum: 35) // 1 + 4 + 7 + 10 + 13
check(from: 1, to: 17, by: 3, sum: 51) // 1 + 4 + 7 + 10 + 13 + 16
check(from: 1, to: -13, by: -3, sum: -25) // 1 + -2 + -5 + -8 + -11
check(from: 1, to: -14, by: -3, sum: -25) // 1 + -2 + -5 + -8 + -11
check(from: 1, to: -15, by: -3, sum: -39) // 1 + -2 + -5 + -8 + -11 + -14
check(from: 4, to: 16, by: -3, sum: 0)
check(from: 1, to: -16, by: 3, sum: 0)
}
StrideTestSuite.test("Closed") {
func check(from start: Int, through end: Int, by stepSize: Int, sum: Int) {
// Work on Ints
expectEqual(
sum,
stride(from: start, through: end, by: stepSize).reduce(
0, +))
// Work on an arbitrary RandomAccessIndex
expectEqual(
sum,
stride(from: R(start), through: R(end), by: stepSize).reduce(
0, { $0 + $1.x })
)
}
check(from: 1, through: 15, by: 3, sum: 35) // 1 + 4 + 7 + 10 + 13
check(from: 1, through: 16, by: 3, sum: 51) // 1 + 4 + 7 + 10 + 13 + 16
check(from: 1, through: 17, by: 3, sum: 51) // 1 + 4 + 7 + 10 + 13 + 16
check(from: 1, through: -13, by: -3, sum: -25) // 1 + -2 + -5 + -8 + -11
check(from: 1, through: -14, by: -3, sum: -39) // 1 + -2 + -5 + -8 + -11 + -14
check(from: 1, through: -15, by: -3, sum: -39) // 1 + -2 + -5 + -8 + -11 + -14
check(from: 4, through: 16, by: -3, sum: 0)
check(from: 1, through: -16, by: 3, sum: 0)
}
StrideTestSuite.test("OperatorOverloads") {
var r1 = R(50)
var r2 = R(70)
var stride: Int = 5
do {
var result = r1 + stride
expectType(R.self, &result)
expectEqual(55, result.x)
}
do {
var result = stride + r1
expectType(R.self, &result)
expectEqual(55, result.x)
}
do {
var result = r1 - stride
expectType(R.self, &result)
expectEqual(45, result.x)
}
do {
var result = r1 - r2
expectType(Int.self, &result)
expectEqual(-20, result)
}
do {
var result = r1
result += stride
expectType(R.self, &result)
expectEqual(55, result.x)
}
do {
var result = r1
result -= stride
expectType(R.self, &result)
expectEqual(45, result.x)
}
}
StrideTestSuite.test("FloatingPointStride") {
var result = [Double]()
for i in stride(from: 1.4, through: 3.4, by: 1) {
result.append(i)
}
expectEqual([ 1.4, 2.4, 3.4 ], result)
}
StrideTestSuite.test("ErrorAccumulation") {
let a = Array(stride(from: Float(1.0), through: Float(2.0), by: Float(0.1)))
expectEqual(11, a.count)
expectEqual(Float(2.0), a.last)
let b = Array(stride(from: Float(1.0), to: Float(10.0), by: Float(0.9)))
expectEqual(10, b.count)
}
func strideIteratorTest<
Stride : Sequence
>(_ stride: Stride, nonNilResults: Int) {
var i = stride.makeIterator()
for _ in 0..<nonNilResults {
expectNotNil(i.next())
}
for _ in 0..<10 {
expectNil(i.next())
}
}
StrideTestSuite.test("StrideThroughIterator/past end") {
strideIteratorTest(stride(from: 0, through: 3, by: 1), nonNilResults: 4)
strideIteratorTest(
stride(from: UInt8(0), through: 255, by: 5), nonNilResults: 52)
}
StrideTestSuite.test("StrideThroughIterator/past end/backward") {
strideIteratorTest(stride(from: 3, through: 0, by: -1), nonNilResults: 4)
}
StrideTestSuite.test("StrideToIterator/past end") {
strideIteratorTest(stride(from: 0, to: 3, by: 1), nonNilResults: 3)
}
StrideTestSuite.test("StrideToIterator/past end/backward") {
strideIteratorTest(stride(from: 3, to: 0, by: -1), nonNilResults: 3)
}
runAllTests()
| apache-2.0 | af35d2bca10fad1348c4fcdc9fe5d674 | 27.487603 | 95 | 0.598491 | 2.907634 | false | true | false | false |
anasmeister/nRF-Coventry-University | nRF Toolbox/RegierPageViewController.swift | 1 | 3455 | //
// RegisterPageViewController.swift
// UserLoginAndRegistration
//
// Created by Anastasis Panagoulias on 04/12/2016.
// Copyright © 2016 Anastasis Panagoulias. All rights reserved.
//
import UIKit
class RegisterPageViewController: UIViewController {
@IBOutlet weak var userEmailTextField: UITextField!
@IBOutlet weak var userPasswordTextField: UITextField!
@IBOutlet weak var repeatPasswordTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
let toolbar = UIToolbar()
toolbar.sizeToFit()
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
let doneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.done, target: self, action: #selector(self.doneClicked))
toolbar.setItems([flexibleSpace, doneButton], animated: false)
userEmailTextField.inputAccessoryView = toolbar
userPasswordTextField.inputAccessoryView = toolbar
repeatPasswordTextField.inputAccessoryView = toolbar
}
func doneClicked() {
view.endEditing(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func registerButtonTapped(_ sender: Any) {
let userEmail = userEmailTextField.text
let userPassword = userPasswordTextField.text
let userRepeatPassword = repeatPasswordTextField.text
//Check for empty Fields
if((userEmail?.isEmpty)! || (userPassword?.isEmpty)! || (userRepeatPassword?.isEmpty)!) {
//Display Alert Message
displayMyAlertMessage(userMessage: "All fields are required")
return
}
//Check if Passwords are a match
if (userPassword != userRepeatPassword) {
//display alert message
displayMyAlertMessage(userMessage: "Passwords do not match")
return
}
//Store Data
UserDefaults.standard.set(userEmail, forKey: "userEmail")
UserDefaults.standard.set(userPassword, forKey: "userPassword")
UserDefaults.standard.synchronize()
//Display Alert message with confiramtion
let myAlert = UIAlertController(title: "Thank You", message: "Registration is succesful.", preferredStyle: UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title:"Ok", style:UIAlertActionStyle.default){ action in
self.dismiss(animated: true, completion: nil)
}
myAlert.addAction(okAction)
self.present(myAlert, animated:true, completion:nil)
}
func displayMyAlertMessage(userMessage: String)
{
let myAlert = UIAlertController(title: "Alert", message: userMessage, preferredStyle: UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title:"Ok", style:UIAlertActionStyle.default, handler:nil)
myAlert.addAction(okAction)
self.present(myAlert, animated:true, completion:nil)
}
@IBAction func alreadyHaveTapped(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
}
| bsd-3-clause | acae2779aa7d7b0f1ec9251decdde094 | 31.895238 | 145 | 0.640996 | 5.795302 | false | false | false | false |
typelift/Basis | BasisTests/MaybeSpec.swift | 2 | 2284 | //
// MaybeSpec.swift
// Basis
//
// Created by Robert Widmann on 9/21/14.
// Copyright (c) 2014 TypeLift. All rights reserved.
// Released under the MIT license.
//
import Basis
import XCTest
class MaybeSpec : XCTestCase {
func testMaybe() {
let def = 10
let f = { $0 + 10 }
let m1 = Optional.Some(10)
let m2 : Int? = Optional.None
XCTAssertTrue(maybe(def)(f: f)(m: m1) == 20, "")
XCTAssertTrue(maybe(def)(f: f)(m: m2) == 10, "")
}
func testGestalt() {
let m1 = Optional.Some(10)
let m2 : Int? = Optional.None
XCTAssertTrue(isSome(m1), "")
XCTAssertTrue(isNone(m2), "")
}
func testFrom() {
let def = 10
let m1 = Optional.Some(100)
let m2 : Int? = Optional.None
XCTAssertTrue(fromSome(m1) == 100, "")
XCTAssertTrue(fromOptional(def)(m: m1) == 100, "")
XCTAssertTrue(fromOptional(def)(m: m2) == 10, "")
}
func testOptionalToList() {
let m1 = Optional.Some(100)
let m2 : Int? = Optional.None
XCTAssertTrue(optionalToList(m1) == [100], "")
XCTAssertTrue(optionalToList(m2) == [], "")
}
func testListToOptional() {
let l1 = [Int]()
let l2 = [100]
XCTAssertTrue(listToOptional(l1) == nil, "")
XCTAssertTrue(listToOptional(l2) == Optional.Some(100), "")
}
func testCatOptionals() {
let x = Optional.Some(5)
let l = [ x, nil, x, nil, x, nil, x ]
XCTAssertTrue(foldr1(+)(catOptionals(l)) == 20, "")
}
func testMapOptionals() {
let l = [ [5], [], [5], [], [5], [] ]
XCTAssertTrue(foldr1(+)(mapOptional(listToOptional)(l: l)) == 15, "")
}
func liftA<A, B>(f : A -> B) -> Maybe<A> -> Maybe<B> {
return { a in Maybe.pure(f) <*> a }
}
func liftA2<A, B, C>(f : A -> B -> C) -> Maybe<A> -> Maybe<B> -> Maybe<C> {
return { a in { b in Maybe.pure(f) <*> a <*> b } }
}
func liftA3<A, B, C, D>(f : A -> B -> C -> D) -> Maybe<A> -> Maybe<B> -> Maybe<C> -> Maybe<D> {
return { a in { b in { c in Maybe.pure(f) <*> a <*> b <*> c } } }
}
func testApplicative() {
let a = Maybe.just(6)
let b = Maybe<Int>.nothing()
let c = Maybe.just(5)
let r = liftA2(curry(+))(a)(b)
XCTAssertTrue(r == Maybe<Int>.nothing())
let rr = liftA2(curry(+))(a)(c)
XCTAssertTrue(rr == Maybe.just(11))
let t = liftA3(pack3)(a)(b)(c)
XCTAssertTrue(t == Maybe<(Int, Int, Int)>.nothing())
}
}
| mit | df77f7c5393e9b18823917acdda04df9 | 21.613861 | 96 | 0.57662 | 2.683901 | false | true | false | false |
terry408911/ReactiveCocoa | ReactiveCocoa/Swift/FoundationExtensions.swift | 1 | 1696 | //
// FoundationExtensions.swift
// ReactiveCocoa
//
// Created by Justin Spahr-Summers on 2014-10-19.
// Copyright (c) 2014 GitHub. All rights reserved.
//
import Foundation
import LlamaKit
extension NSNotificationCenter {
/// Returns a signal of notifications posted that match the given criteria.
/// This signal will not terminate naturally, so it must be explicitly
/// disposed to avoid leaks.
public func rac_notifications(name: String? = nil, object: AnyObject? = nil) -> Signal<NSNotification, NoError> {
return Signal { observer in
let notificationObserver = self.addObserverForName(name, object: object, queue: nil) { notification in
sendNext(observer, notification)
}
return ActionDisposable {
self.removeObserver(notificationObserver)
}
}
}
}
extension NSURLSession {
/// Returns a producer that will execute the given request once for each
/// invocation of start().
public func rac_dataWithRequest(request: NSURLRequest) -> SignalProducer<(NSData, NSURLResponse), NSError> {
return SignalProducer { observer, disposable in
let task = self.dataTaskWithRequest(request) { (data, response, error) in
if let data = data, response = response {
sendNext(observer, (data, response))
sendCompleted(observer)
} else {
sendError(observer, error)
}
}
disposable.addDisposable {
task.cancel()
}
task.resume()
}
}
}
/// Removes all nil values from the given sequence.
internal func ignoreNil<T, S: SequenceType where S.Generator.Element == Optional<T>>(sequence: S) -> [T] {
var results: [T] = []
for value in sequence {
if let value = value {
results.append(value)
}
}
return results
}
| mit | 877b2ea269801250aa1a53e22787385d | 25.920635 | 114 | 0.706368 | 3.881007 | false | false | false | false |
BizzonInfo/SDKDemo | SdkDemoFramework/SdkDemoFramework/Model/Constants.swift | 1 | 2759 | //
// Constants.swift
// CompassForSuccess
//
// Created by Bon User on 9/5/16.
// Copyright © 2016 Bon User. All rights reserved.
//
import Foundation
import UIKit
var device_token="DEVICE_TOKEN"
var access_tokenString = "ACCESSTOKEN"
let acceptColorCode = "0ca500"
let rejectColorCode = "FF0000"
let tableViewPrimaryColor = "e8edf3"
let tableViewAlternateCellColor = "E9E7EF"
let barTintColor = "304267"
let cellSelectionColor = "4ED7FF"
let navigationBarColor = "48004c"
let borderColor = "C5C5C5"
let sideMenuOptioniDevice="com.bon.sideMenuOptionChanged_iDevice"
let sideMenuOptioniPad="com.bon.sideMenuOptionChanged_iPad"
let EMAIL="EMAIL"
let PASSWORD="PASSWORD"
let USERNAME="USERNAME"
let USER_ID = "USER_ID"
var STATUS_CODE = 200
var BackgroundImage = "AppBG1"
var currencySymbol = "CURRENCY"
var ACCESS_TOKEN = "Access_token"
var CAFE_NAME = ""
let deviceId = "deviceid"
let deviceHandShake = "devicehandshake"
let deviceCode = "devicecode"
//var sideMenuOptionChangeNotificationKey = CAUtils .getSildeMenuOptionChangeNotificationKey()
var sideMenuIndex:Int? = nil
var profileImage = UIImage()
//local Arun
//http://192.168.1.210:8000/api/dashboard
//let baseURL = "http://192.168.1.210:8000/"// "http://mbk.ams.bongroup.co.uk/oauth/token";
//let client_secret = "vyuflSReDoQpCtorE3S4L8J1H04vNKEfFxtyBExJ"
//local server
//let baseURL = "http://192.168.1.206:8005/api/"
//let superAdminBaseURL = "http://admin.madfries.chef2dine.com/api/"
//let forgotPasswordURL = "http://192.168.1.50/web/ajith/canacar-api/public_html/forgot-password"
//
//let apiTokenURL = "http://192.168.1.50/web/ajith/canacar-api/public_html/api/token"
//
//let registerURL = "http://192.168.1.50/web/ajith/canacar-api/public_html/register"
//
//let settingsURL = "http://192.168.1.50/web/ajith/canacar-api/public_html/api/get-setting-details"
//live server
//let baseURL = "http://cafe.madfries.chef2dine.com/api/"
let baseURL = "http://192.168.1.206:8005/api/"
//let superAdminBaseURL = "http://admin.madfries.chef2dine.com/api/"
let superAdminBaseURL = "http://192.168.1.206:8000/api/"
// add-order
// bill-payment
//let baseURL = "http://api.cargoonline.bonstaging.in/public_html/api/"
//
//let forgotPasswordURL = "http://api.cargoonline.bonstaging.in/public_html/forgot-password"
//
//let apiTokenURL = "http://api.cargoonline.bonstaging.in/public_html/api/token"
//
//let registerURL = "http://api.cargoonline.bonstaging.in/public_html/register"
//
//let settingsURL = "http://api.cargoonline.bonstaging.in/public_html/api/get-setting-details"
let coreDataUpdateFailed = "Couldn't Update Coredata Details"
let coreDataInsertFailed = "Could't insert data into CoreData"
let coreDataDeleteFailed = "CoreData Delete Failed"
| mit | fb9aef0212d1770b6d357568b20a5032 | 23.846847 | 99 | 0.743292 | 2.927813 | false | false | false | false |
TheDarkCode/Example-Swift-Apps | Exercises and Basic Principles/user-defaults-basics/user-defaults-basics/Person.swift | 1 | 1688 | //
// Person.swift
// user-defaults-basics
//
// Created by Mark Hamilton on 2/24/16.
// Copyright © 2016 dryverless. All rights reserved.
//
import Foundation
class Person: NSObject, NSCoding {
private var _firstName: String!
private var _lastName: String!
var firstName: String {
get {
if let fName: String = _firstName ?? "John" {
return fName
}
}
set {
return _firstName = newValue
}
}
var lastName: String {
get {
if let lName: String = _lastName ?? "Doe" {
return lName
}
}
set {
return _lastName = newValue
}
}
init(first: String, last: String) {
_firstName = first
_lastName = last
}
override init() {
}
// Required for Decoding from NSData
required convenience init?(coder aDecoder: NSCoder) {
// Call blank init
self.init()
// For each variable, use decodeObjectForKey. Usually set it to the same name as the variable.
// Must not be get-only.
self.firstName = aDecoder.decodeObjectForKey("firstName") as! String
self.lastName = aDecoder.decodeObjectForKey("lastName") as! String
}
// Required for Encoding to NSData
func encodeWithCoder(aCoder: NSCoder) {
// For each variable, use encodeObject with set key name as used with decoder.
aCoder.encodeObject(self.firstName, forKey: "firstName")
aCoder.encodeObject(self.lastName, forKey: "lastName")
}
} | mit | 34b023f4e899aad791eec792625a4390 | 22.774648 | 102 | 0.548311 | 4.833811 | false | false | false | false |
adrfer/swift | test/Sema/diag_c_style_for.swift | 6 | 3286 | // RUN: %target-parse-verify-swift
// expected-warning @+1 {{'++' is deprecated: it will be removed in Swift 3}}
for var a = 0; a < 10; a++ { // expected-warning {{C-style for statement is deprecated and will be removed in a future version of Swift}} {{5-9=}} {{10-13= in }} {{14-20= ..< }} {{22-27=}}
}
// expected-warning @+1 {{'++' is deprecated: it will be removed in Swift 3}}
for var b = 0; b < 10; ++b { // expected-warning {{C-style for statement is deprecated and will be removed in a future version of Swift}} {{5-9=}} {{10-13= in }} {{14-20= ..< }} {{22-27=}}
}
// expected-warning @+1 {{'++' is deprecated: it will be removed in Swift 3}}
for var c=1;c != 5 ;++c { // expected-warning {{C-style for statement is deprecated and will be removed in a future version of Swift}} {{5-9=}} {{10-11= in }} {{12-18= ..< }} {{20-24=}}
}
// expected-warning @+1 {{'++' is deprecated: it will be removed in Swift 3}}
for var d=100;d<5;d++ { // expected-warning {{C-style for statement is deprecated and will be removed in a future version of Swift}} {{5-9=}} {{10-11= in }} {{14-17= ..< }} {{18-22=}}
}
// next three aren't auto-fixable
// expected-warning @+1 {{'++' is deprecated: it will be removed in Swift 3}}
for var e = 3; e > 4; e++ { // expected-warning {{C-style for statement is deprecated and will be removed in a future version of Swift}} {{none}}
}
// expected-warning @+1 {{'--' is deprecated: it will be removed in Swift 3}}
for var f = 3; f < 4; f-- { // expected-warning {{C-style for statement is deprecated and will be removed in a future version of Swift}} {{none}}
}
let start = Int8(4)
let count = Int8(10)
var other = Int8(2)
// expected-warning @+1 {{'++' is deprecated: it will be removed in Swift 3}}
for ; other<count; other++ { // expected-warning {{C-style for statement is deprecated and will be removed in a future version of Swift}} {{none}}
}
// this should be fixable, and keep the type
// expected-warning @+1 {{'++' is deprecated: it will be removed in Swift 3}}
for (var number : Int8 = start; number < count; number++) { // expected-warning {{C-style for statement is deprecated and will be removed in a future version of Swift}} {{6-10=}} {{23-26= in }} {{31-42= ..< }} {{47-57=}}
print(number)
}
// should produce extra note
// expected-warning @+1 {{'++' is deprecated: it will be removed in Swift 3}}
for (var m : Int8 = start; m < count; ++m) { // expected-warning {{C-style for statement is deprecated and will be removed in a future version of Swift}} {{none}} expected-note {{C-style for statement can't be automatically fixed to for-in, because the loop variable is modified inside the loop}}
m += 3
}
for var o = 2; o < 888; o += 1 { // expected-warning {{C-style for statement is deprecated and will be removed in a future version of Swift}} {{5-9=}} {{10-13= in }} {{14-20= ..< }} {{23-31=}}
}
for var o = 2; o < 888; o += 11 { // expected-warning {{C-style for statement is deprecated and will be removed in a future version of Swift}} {{none}}
}
// could theoretically fix this with "..."
// expected-warning @+1 {{'++' is deprecated: it will be removed in Swift 3}}
for var p = 2; p <= 8; p++ { // expected-warning {{C-style for statement is deprecated and will be removed in a future version of Swift}} {{none}}
}
| apache-2.0 | e43f7ee1ee69adc68fca09fdb3ddfab1 | 56.649123 | 296 | 0.645466 | 3.448059 | false | false | false | false |
kaushaldeo/Olympics | Olympics/Pager/ViewPagerController.swift | 1 | 9995 | //
// ViewPagerController.swift
// ViewPagerController
//
// Created by xxxAIRINxxx on 2016/01/05.
// Copyright © 2016 xxxAIRINxxx. All rights reserved.
//
import Foundation
import UIKit
public enum ObservingScrollViewType {
case None
case Header
case NavigationBar(targetNavigationBar : UINavigationBar)
}
public final class ViewPagerController: UIViewController {
// MARK: - Public Handler Properties
public var didShowViewControllerHandler : (UIViewController -> Void)?
public var updateSelectedViewHandler : (UIView -> Void)?
public var willBeginTabMenuUserScrollingHandler : (UIView -> Void)?
public var didEndTabMenuUserScrollingHandler : (UIView -> Void)?
public var didChangeHeaderViewHeightHandler : (CGFloat -> Void)?
public var changeObserveScrollViewHandler : (UIViewController -> UIScrollView?)?
public var didScrollContentHandler : (CGFloat -> Void)?
// MARK: - Custom Settings Properties
public private(set) var headerViewHeight : CGFloat = 0.0
public private(set) var tabMenuViewHeight : CGFloat = 0.0
// ScrollHeaderSupport
public private(set) var scrollViewMinPositionY : CGFloat = 0.0
public private(set) var scrollViewObservingDelay : CGFloat = 0.0
public private(set) var scrollViewObservingType : ObservingScrollViewType = .None {
didSet {
switch self.scrollViewObservingType {
case .Header:
self.targetNavigationBar = nil
case .NavigationBar(let targetNavigationBar):
self.targetNavigationBar = targetNavigationBar
case .None:
self.targetNavigationBar = nil
self.observingScrollView = nil
}
}
}
// MARK: - Private Properties
internal var headerView : UIView = UIView(frame: CGRect.zero)
internal var tabMenuView : PagerTabMenuView = PagerTabMenuView(frame: CGRect.zero)
internal var containerView : PagerContainerView = PagerContainerView(frame: CGRect.zero)
internal var targetNavigationBar : UINavigationBar?
internal var headerViewHeightConstraint : NSLayoutConstraint!
internal var tabMenuViewHeightConstraint : NSLayoutConstraint!
internal var viewTopConstraint : NSLayoutConstraint!
internal var observingScrollView : UIScrollView? {
willSet { self.stopScrollViewContentOffsetObserving() }
didSet { self.startScrollViewContentOffsetObserving() }
}
// MARK: - Override
deinit {
self.scrollViewObservingType = .None
}
public override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(self.containerView)
self.view.addSubview(self.tabMenuView)
self.view.addSubview(self.headerView)
self.setupConstraint()
self.setupHandler()
self.updateAppearance(ViewPagerControllerAppearance())
}
public override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
self.tabMenuView.stopScrolling(self.containerView.currentIndex() ?? 0)
self.didEndTabMenuUserScrollingHandler?(self.tabMenuView.getSelectedView())
self.tabMenuView.updateSelectedViewLayout(false)
}
// MARK: - Public Functions
public func updateAppearance(appearance: ViewPagerControllerAppearance) {
// Header
self.headerViewHeight = appearance.headerHeight
self.headerViewHeightConstraint.constant = self.headerViewHeight
self.headerView.subviews.forEach() { $0.removeFromSuperview() }
if let _contentsView = appearance.headerContentsView {
self.headerView.addSubview(_contentsView)
self.headerView.allPin(_contentsView)
}
// Tab Menu
self.tabMenuViewHeight = appearance.tabMenuHeight
self.tabMenuViewHeightConstraint.constant = self.tabMenuViewHeight
self.tabMenuView.updateAppearance(appearance.tabMenuAppearance)
// ScrollHeaderSupport
self.scrollViewMinPositionY = appearance.scrollViewMinPositionY
self.scrollViewObservingType = appearance.scrollViewObservingType
self.scrollViewObservingDelay = appearance.scrollViewObservingDelay
self.view.layoutIfNeeded()
}
public func setParentController(controller: UIViewController, parentView: UIView) {
controller.automaticallyAdjustsScrollViewInsets = false
controller.addChildViewController(self)
parentView.addSubview(self.view)
self.viewTopConstraint = parentView.addPin(self.view, attribute: .Top, toView: parentView, constant: 0.0)
parentView.addPin(self.view, attribute: .Bottom, toView: parentView, constant: 0.0)
parentView.addPin(self.view, attribute: .Left, toView: parentView, constant: 0.0)
parentView.addPin(self.view, attribute: .Right, toView: parentView, constant: 0.0)
self.didMoveToParentViewController(controller)
}
public func addContent(title: String, viewController: UIViewController) {
let identifier = NSUUID().UUIDString
self.tabMenuView.addTitle(identifier, title: title)
self.addChildViewController(viewController)
self.containerView.addViewController(identifier, viewController: viewController)
}
public func removeContent(viewController: UIViewController) {
guard let _identifier = self.containerView.identifierFromViewController(viewController) else { return }
if self.childViewControllers.contains(viewController) {
viewController.willMoveToParentViewController(nil)
self.tabMenuView.removeContent(_identifier)
self.containerView.removeContent(_identifier)
viewController.removeFromParentViewController()
}
}
public func reloadData(index: Int) {
self.tabMenuView.scrollToCenter(index, animated: false, animation: nil, completion: nil)
self.containerView.scrollToCenter(index, animated: false, animation: nil, completion: nil)
self.view.layoutIfNeeded()
}
public func currentContent() -> UIViewController? {
return self.containerView.currentContent()
}
// MARK: - Private Functions
private func setupConstraint() {
// Header
self.view.addPin(self.headerView, attribute: .Top, toView: self.view, constant: 0.0)
self.headerViewHeightConstraint = self.headerView.addHeightConstraint(self.headerView, constant: self.headerViewHeight)
self.view.addPin(self.headerView, attribute: .Left, toView: self.view, constant: 0.0)
self.view.addPin(self.headerView, attribute: .Right, toView: self.view, constant: 0.0)
// Tab Menu
self.view.addPin(self.tabMenuView, isWithViewTop: true, toView: self.headerView, isToViewTop: false, constant: 0.0)
self.tabMenuViewHeightConstraint = self.tabMenuView.addHeightConstraint(self.tabMenuView, constant: self.tabMenuViewHeight)
self.view.addPin(self.tabMenuView, attribute: .Left, toView: self.view, constant: 0.0)
self.view.addPin(self.tabMenuView, attribute: .Right, toView: self.view, constant: 0.0)
// Container
self.view.addPin(self.containerView, isWithViewTop: true, toView: self.tabMenuView, isToViewTop: false, constant: 0.0)
self.view.addPin(self.containerView, attribute: .Bottom, toView: self.view, constant: 0.0)
self.view.addPin(self.containerView, attribute: .Left, toView: self.view, constant: 0.0)
self.view.addPin(self.containerView, attribute: .Right, toView: self.view, constant: 0.0)
}
private func setupHandler() {
self.tabMenuView.selectedIndexHandler = { [weak self] index in
self?.containerView.scrollToCenter(index, animated: true, animation: nil, completion: nil)
}
self.tabMenuView.updateSelectedViewHandler = { [weak self] selectedView in
self?.updateSelectedViewHandler?(selectedView)
}
self.tabMenuView.willBeginScrollingHandler = { [weak self] selectedView in
self?.willBeginTabMenuUserScrollingHandler?(selectedView)
}
self.tabMenuView.didEndTabMenuScrollingHandler = { [weak self] selectedView in
self?.didEndTabMenuUserScrollingHandler?(selectedView)
}
self.containerView.startSyncHandler = { [weak self] index in
self?.tabMenuView.stopScrolling(index)
}
self.containerView.syncOffsetHandler = { [weak self] index, percentComplete, scrollingTowards in
self?.tabMenuView.syncContainerViewScrollTo(index, percentComplete: percentComplete, scrollingTowards: scrollingTowards)
self?.didScrollContentHandler?(percentComplete)
}
self.containerView.finishSyncHandler = { [weak self] index in
self?.tabMenuView.finishSyncContainerViewScroll(index)
}
self.containerView.didShowViewControllerHandler = { [weak self] controller in
self?.didShowViewControllerHandler?(controller)
let scrollView = self?.changeObserveScrollViewHandler?(controller)
self?.observingScrollView = scrollView
}
}
private func startScrollViewContentOffsetObserving() {
if let _observingScrollView = self.observingScrollView {
_observingScrollView.addObserver(self, forKeyPath: "contentOffset", options: [.Old, .New], context: nil)
}
}
private func stopScrollViewContentOffsetObserving() {
if let _observingScrollView = self.observingScrollView {
_observingScrollView.removeObserver(self, forKeyPath: "contentOffset")
}
}
}
| apache-2.0 | 34981c333b49c479d3adc65686192c32 | 39.791837 | 132 | 0.68281 | 5.170202 | false | false | false | false |
CoderXiaoming/Ronaldo | SaleManager/SaleManager/Stock/Model/SAMStockProductModel.swift | 1 | 2218 | //
// SAMStockProductModel.swift
// SaleManager
//
// Created by apple on 16/11/25.
// Copyright © 2016年 YZH. All rights reserved.
//
import UIKit
class SAMStockProductModel: NSObject {
///产品编号id
var id = ""
///产品编号名称
var productIDName = "" {
didSet{
productIDName = ((productIDName == "") ? "---" : productIDName)
}
}
///产品花名
var productIDNameHM = "" {
didSet{
productIDNameHM = ((productIDNameHM == "") ? "---" : productIDNameHM)
}
}
///是否缺货的提醒,要么为空,要么是"缺货",缺货的库存是红色显示,其他的是绿色显示
var msg = ""
///产品编号的成本价
var costNoTax = ""
///总米数
var countM: Double = 0.0 {
didSet{
countMText = String(format: "%.1f", countM)
}
}
///总匹数
var countP: Int = 0 {
didSet{
countPText = String(format: "%d", countP)
}
}
///仓库ID,暂时无用
var storehouseID = ""
///产品大类ID ,暂时无用
var parentID = "" {
didSet{
parentID = ((parentID == "") ? "---" : parentID)
}
}
///产品编号单位
var unit = "" {
didSet{
unit = ((unit == "") ? "---" : unit)
}
}
///产品编号规格
var specName = "" {
didSet{
specName = ((specName == "") ? "---" : specName)
}
}
///产品编号备注
var memoInfo = "" {
didSet{
memoInfo = ((memoInfo == "") ? "---" : memoInfo)
}
}
///产品编号对应二维码ID
var codeID = ""
///产品编号对应二维码名称
var codeName = "" {
didSet{
codeName = ((codeName == "") ? "---" : codeName)
}
}
///缩略图1(主缩略图)
var thumbUrl1 = ""
///大图1
var imageUrl1 = ""
//MARK: - 附加属性
//米数内容
var countMText = "0.0"
//匹数内容
var countPText = "0"
///是否可以操作cell
var couldOperateCell = true
}
| apache-2.0 | 171fd3b9fb6821afd36ef69f44d91af2 | 17.432692 | 81 | 0.437141 | 3.333913 | false | false | false | false |
deepindo/DDLive | DDLive/DDLive/Tools/UIColor+Extension.swift | 1 | 2434 | //
// UIColor+Extension.swift
// DDLive
//
// Created by deepindo on 2017/4/25.
// Copyright © 2017年 deepindo. All rights reserved.
//
import UIKit
extension UIColor {
class func randomColor() -> UIColor {
return UIColor(
red: CGFloat(arc4random_uniform(255))/255.0,
green: CGFloat(arc4random_uniform(255))/255.0,
blue: CGFloat(arc4random_uniform(255))/255.0,
alpha: 1.0)
}
class func random() -> UIColor {
return UIColor.randomColor()
}
convenience init(r: CGFloat, g: CGFloat, b: CGFloat, alpha: CGFloat = 1.0) {
self.init(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: alpha)
}
convenience init(c: CGFloat, alpha: CGFloat = 1.0) {
self.init(red: c/255.0, green: c/255.0, blue: c/255.0, alpha: alpha)
}
convenience init?(hex: String) {
guard hex.characters.count >= 6 else {
return nil
}
//judge
var hexTemp = hex.uppercased()
if hexTemp.hasPrefix("0x") || hexTemp.hasPrefix("##") {
hexTemp = (hexTemp as NSString).substring(from: 2)
}
if hexTemp.hasPrefix("#") {
hexTemp = (hexTemp as NSString).substring(from: 1)
}
//range
var range = NSRange(location: 0, length: 2)
let rHex = (hexTemp as NSString).substring(with: range)
range.location = 2
let gHex = (hexTemp as NSString).substring(with: range)
range.location = 4
let bHex = (hexTemp as NSString).substring(with: range)
//
var r: UInt32 = 0
var g: UInt32 = 0
var b: UInt32 = 0
Scanner(string: rHex).scanHexInt32(&r)
Scanner(string: gHex).scanHexInt32(&g)
Scanner(string: bHex).scanHexInt32(&b)
self.init(red: CGFloat(r)/255.0, green: CGFloat(g)/255.0, blue: CGFloat(b)/255.0, alpha: 1.0)
}
func getRGB() -> (CGFloat,CGFloat,CGFloat) {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
if self.getRed(&r, green: &g, blue: &b, alpha: nil) {
return (r * 255, g * 255, b * 255)
}
guard let cmps = cgColor.components else {
fatalError("请使用GRB创建UIColor")
}
return (cmps[0] * 255, cmps[1] * 255, cmps[2] * 255)
}
}
| mit | 0c8b16f60353c6f28f0bb493b0e5c6f4 | 28.52439 | 101 | 0.535729 | 3.707504 | false | false | false | false |
tkremenek/swift | test/expr/closure/inference.swift | 11 | 2011 | // RUN: %target-typecheck-verify-swift
func takeIntToInt(_ f: (Int) -> Int) { }
func takeIntIntToInt(_ f: (Int, Int) -> Int) { }
// Anonymous arguments with inference
func myMap<T, U>(_ array: [T], _ f: (T) -> U) -> [U] {}
func testMap(_ array: [Int]) {
var farray = myMap(array, { Float($0) })
var _ : Float = farray[0]
let farray2 = myMap(array, { x in Float(x) })
farray = farray2
_ = farray
}
// Infer result type.
func testResultType() {
takeIntToInt({x in
return x + 1
})
takeIntIntToInt({x, y in
return 2 + 3
})
}
// Closures with unnamed parameters
func unnamed() {
takeIntToInt({_ in return 1})
takeIntIntToInt({_, _ in return 1})
}
// Regression tests.
var nestedClosuresWithBrokenInference = { f: Int in {} }
// expected-error@-1 {{closure expression is unused}} expected-note@-1 {{did you mean to use a 'do' statement?}} {{53-53=do }}
// expected-error@-2 {{consecutive statements on a line must be separated by ';'}} {{44-44=;}}
// expected-error@-3 {{expected expression}}
// expected-error@-4 {{cannot find 'f' in scope}}
// SR-11540
func SR11540<R>(action: () -> R) -> Void {}
func SR11540<T, R>(action: (T) -> R) -> Void {}
func SR11540_1<T, R>(action: (T) -> R) -> Void {}
SR11540(action: { return }) // Ok SR11540<R>(action: () -> R) was the selected overload.
// In case that's the only possible overload, it's acceptable
SR11540_1(action: { return }) // OK
// SR-8563
func SR8563<A,Z>(_ f: @escaping (A) -> Z) -> (A) -> Z {
return f
}
func SR8563<A,B,Z>(_ f: @escaping (A, B) -> Z) -> (A, B) -> Z {
return f
}
let aa = SR8563 { (a: Int) in }
let bb = SR8563 { (a1: Int, a2: String) in } // expected-note {{'bb' declared here}}
aa(1) // Ok
bb(1, "2") // Ok
bb(1) // expected-error {{missing argument for parameter #2 in call}}
// Tuple
let cc = SR8563 { (_: (Int)) in }
cc((1)) // Ok
cc(1) // Ok
// SR-12955
func SR12955() {
let f: @convention(c) (T) -> Void // expected-error {{cannot find type 'T' in scope}}
}
| apache-2.0 | 31b81c02fa3f5b0a90b33590c51eb891 | 24.1375 | 130 | 0.59274 | 2.94868 | false | false | false | false |
Spincoaster/SoundCloudKit | Source/Activity.swift | 1 | 2051 | //
// Activity.swift
// SoundCloudKit
//
// Created by Hiroki Kumamoto on 8/26/15.
// Copyright (c) 2015 Spincoaster. All rights reserved.
//
import Foundation
import SwiftyJSON
public struct ActivityList: JSONInitializable {
public var nextHref: String?
public var futureHref: String?
public var collection: [Activity]
public init(json: JSON) {
nextHref = json["next_href"].string
futureHref = json["future_href"].string
collection = json["collection"].arrayValue
.filter { ActivityType(rawValue: $0["type"].stringValue) != nil }
.map { Activity(json: $0) }
}
}
public enum ActivityType: String {
case Track = "track"
case TrackRepost = "track-repost"
case TrackSharing = "track-sharing"
case Comment = "comment"
case Favoriting = "favoriting"
case Playlist = "playlist"
case PlaylistRepost = "playlist-repost"
}
public struct Activity: JSONInitializable {
public enum TagType: String {
case Exclusive = "exclusive"
case Affiliated = "affiliated"
case First = "first"
case Own = "own"
case Conversation = "conversation"
}
public enum Origin {
case track(SoundCloudKit.Track)
case playlist(SoundCloudKit.Playlist)
}
public var type: ActivityType
public var createdAt: String
public var tags: [TagType]
public var origin: Origin
public init(json: JSON) {
type = ActivityType(rawValue: json["type"].stringValue)!
createdAt = json["created_at"].stringValue
tags = json["tags"].arrayValue.map { TagType(rawValue: $0.stringValue)! }
switch type {
case .Playlist:
origin = Origin.playlist(Playlist(json: json["origin"]))
case .PlaylistRepost:
origin = Origin.playlist(Playlist(json: json["origin"]))
default:
origin = Origin.track(Track(json: json["origin"]))
}
}
}
| mit | 1d074df03b3126d66c105edc8ffccf3b | 30.075758 | 86 | 0.605558 | 4.246377 | false | false | false | false |
xwu/swift | test/Interop/Cxx/extern-var/extern-var-irgen.swift | 14 | 2110 | // RUN: %target-swift-emit-ir %s -I %S/Inputs -enable-cxx-interop | %FileCheck %s
import ExternVar
public func getCounter() -> CInt {
return counter
}
// CHECK: @{{counter|"\?counter@@3HA"}} = external {{(dso_local )?}}global i32, align 4
// CHECK: @{{_ZN10Namespaced7counterE|"\?counter@Namespaced@@3HA"}} = external {{(dso_local )?}}global i32, align 4
// CHECK: define {{(protected |dllexport )?}}swiftcc i32 @"$s4main10getCounters5Int32VyF"() #0
// CHECK: [[LOAD:%.*]] = load i32, i32* getelementptr inbounds (%Ts5Int32V, %Ts5Int32V* bitcast (i32* @{{counter|"\?counter@@3HA"}} to %Ts5Int32V*), i32 0, i32 0), align 4
// CHECK: ret i32 [[LOAD]]
public func setCounter(_ c: CInt) {
counter = c
}
// CHECK: define {{(protected |dllexport )?}}swiftcc void @"$s4main10setCounteryys5Int32VF"(i32 %0) #0
// CHECK: store i32 %0, i32* getelementptr inbounds (%Ts5Int32V, %Ts5Int32V* bitcast (i32* @{{counter|"\?counter@@3HA"}} to %Ts5Int32V*), i32 0, i32 0), align 4
public func getNamespacedCounter() -> CInt {
return Namespaced.counter
}
// CHECK: define {{(protected |dllexport )?}}swiftcc i32 @"$s4main20getNamespacedCounters5Int32VyF"() #0
// CHECK: load i32, i32* getelementptr inbounds (%Ts5Int32V, %Ts5Int32V* bitcast (i32* @{{_ZN10Namespaced7counterE|"\?counter@Namespaced@@3HA"}} to %Ts5Int32V*), i32 0, i32 0), align 4
// CHECK: ret i32 %1
public func setNamespacedCounter(_ c: CInt) {
Namespaced.counter = c
}
// CHECK: define {{(protected |dllexport )?}}swiftcc void @"$s4main20setNamespacedCounteryys5Int32VF"(i32 %0) #0
// CHECK: store i32 %0, i32* getelementptr inbounds (%Ts5Int32V, %Ts5Int32V* bitcast (i32* @{{_ZN10Namespaced7counterE|"\?counter@Namespaced@@3HA"}} to %Ts5Int32V*), i32 0, i32 0), align 4
func modifyInout(_ c: inout CInt) {
c = 42
}
public func passingVarAsInout() {
modifyInout(&counter)
}
// CHECK: define {{(protected |dllexport )?}}swiftcc void @"$s4main17passingVarAsInoutyyF"() #0
// CHECK: call swiftcc void @"$s4main11modifyInoutyys5Int32VzF"(%Ts5Int32V* nocapture dereferenceable(4) bitcast (i32* @{{counter|"\?counter@@3HA"}} to %Ts5Int32V*))
| apache-2.0 | 99f3bcbfe824ded5c2e3a1d205a69b3d | 43.893617 | 188 | 0.692891 | 3.139881 | false | false | false | false |
programersun/HiChongSwift | HiChongSwift/PetCateFilterViewController.swift | 1 | 3647 | //
// PetCateFilterViewController.swift
// HiChongSwift
//
// Created by eagle on 14/12/24.
// Copyright (c) 2014年 多思科技. All rights reserved.
//
import UIKit
class PetCateFilterViewController: UITableViewController {
weak var delegate: PetCateFilterDelegate?
weak var root: UIViewController?
private var allTypeBase: LCYPetAllTypeBase?
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
// let parameter = NSDictionary()
LCYNetworking.sharedInstance.POST(LCYApi.PetAllType, parameters: nil, success: { [weak self](object) -> Void in
self?.allTypeBase = LCYPetAllTypeBase.modelObjectWithDictionary(object as [NSObject : AnyObject])
self?.tableView.reloadData()
return
}) { [weak self](error) -> Void in
self?.alert("获取信息失败,请检查网络状态")
return
}
tableView.backgroundColor = UIColor.LCYThemeColor()
tableView.hideExtraSeprator()
navigationItem.title = "科目"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// Return the number of sections.
if allTypeBase != nil {
return 1
} else {
return 0
}
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
return allTypeBase!.fatherStyle.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(PetCateFilterCell.identifier(), forIndexPath: indexPath) as! PetCateFilterCell
// Configure the cell...
if let styleInfo = allTypeBase?.fatherStyle[indexPath.row] as? LCYPetAllTypeFatherStyle {
cell.icyImageView?.setImageWithURL(NSURL(string: styleInfo.headImg.toAbsolutePath()), placeholderImage: UIImage(named: "placeholderLogo"))
cell.icyTextLabel?.text = styleInfo.name
}
return cell
}
// 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.
if let identifier = segue.identifier {
switch identifier {
case "showLv2":
let destination = segue.destinationViewController as! PetSubTypeViewController
if let indexPath = tableView.indexPathForSelectedRow()?.row {
let info = allTypeBase?.fatherStyle[indexPath] as? LCYPetAllTypeFatherStyle
destination.parentID = info?.catId
destination.delegate = delegate
destination.root = root
}
default:
break
}
}
}
}
| apache-2.0 | 436757e4fe2b69f863a88ea78cf0feb1 | 35.785714 | 150 | 0.650485 | 5.247453 | false | false | false | false |
XiaoChenYung/GitSwift | NetWork/Entries/User+Mapping.swift | 1 | 560 | //
// User+Mapping.swift
// GitSwift
//
// Created by 杨晓晨 on 2017/7/29.
// Copyright © 2017年 tm. All rights reserved.
//
import Domain
import ObjectMapper
extension User: ImmutableMappable {
// JSON -> Object
public init(map: Map) throws {
address = try map.value("avatar_url")
company = try map.value("login")
email = try map.value("login")
name = try map.value("login")
uid = try map.value("id")
username = try map.value("login")
website = try map.value("html_url")
}
}
| mit | c093cf770b5f6bb80cdf74f4a9d58755 | 21.958333 | 46 | 0.591652 | 3.554839 | false | false | false | false |
y16ra/CookieCrunch | CookieCrunch/Chain.swift | 1 | 1259 | //
// Chain.swift
// CookieCrunch
//
// Created by Ichimura Yuichi on 2015/08/01.
// Copyright (c) 2015年 Ichimura Yuichi. All rights reserved.
//
import Foundation
class Chain: Hashable, CustomStringConvertible {
var cookies = [Cookie]()
var score = 0
enum ChainType: CustomStringConvertible {
case Horizontal
case Vertical
var description: String {
switch self {
case .Horizontal: return "Horizontal"
case .Vertical: return "Vertical"
}
}
}
var chainType: ChainType
init(chainType: ChainType) {
self.chainType = chainType
}
func addCookie(cookie: Cookie) {
cookies.append(cookie)
}
func firstCookie() -> Cookie {
return cookies[0]
}
func lastCookie() -> Cookie {
return cookies[cookies.count - 1]
}
var length: Int {
return cookies.count
}
var description: String {
return "type:\(chainType) cookies:\(cookies)"
}
var hashValue: Int {
return cookies.reduce(0) { $0.hashValue ^ $1.hashValue }
}
}
func ==(lhs: Chain, rhs: Chain) -> Bool {
return lhs.cookies == rhs.cookies
}
| mit | 993637738f4871a11ee7e17c73035ec6 | 19.606557 | 64 | 0.564041 | 4.334483 | false | false | false | false |
Tomikes/eidolon | Kiosk/Auction Listings/MasonryCollectionViewCell.swift | 5 | 4783 | import UIKit
import Swift_RAC_Macros
let MasonryCollectionViewCellWidth: CGFloat = 254
class MasonryCollectionViewCell: ListingsCollectionViewCell {
private lazy var bidView: UIView = {
let view = UIView()
for subview in [self.currentBidLabel, self.numberOfBidsLabel] {
view.addSubview(subview)
subview.alignTopEdgeWithView(view, predicate:"13")
subview.alignBottomEdgeWithView(view, predicate:"0")
subview.constrainHeight("18")
}
self.currentBidLabel.alignLeadingEdgeWithView(view, predicate: "0")
self.numberOfBidsLabel.alignTrailingEdgeWithView(view, predicate: "0")
return view
}()
private lazy var cellSubviews: [UIView] = [self.artworkImageView, self.lotNumberLabel, self.artistNameLabel, self.artworkTitleLabel, self.estimateLabel, self.bidView, self.bidButton, self.moreInfoLabel]
private var artworkImageViewHeightConstraint: NSLayoutConstraint?
override func setup() {
super.setup()
contentView.constrainWidth("\(MasonryCollectionViewCellWidth)")
// Add subviews
for subview in cellSubviews {
self.contentView.addSubview(subview)
subview.alignLeading("0", trailing: "0", toView: self.contentView)
}
// Constrain subviews
artworkImageView.alignTop("0", bottom: nil, toView: contentView)
let lotNumberTopConstraint = lotNumberLabel.alignAttribute(.Top, toAttribute: .Bottom, ofView: artworkImageView, predicate: "20").first as! NSLayoutConstraint
let artistNameTopConstraint = artistNameLabel.alignAttribute(.Top, toAttribute: .Bottom, ofView: lotNumberLabel, predicate: "10").first as! NSLayoutConstraint
artistNameLabel.constrainHeight("20")
artworkTitleLabel.alignAttribute(.Top, toAttribute: .Bottom, ofView: artistNameLabel, predicate: "10")
artworkTitleLabel.constrainHeight("16")
estimateLabel.alignAttribute(.Top, toAttribute: .Bottom, ofView: artworkTitleLabel, predicate: "10")
estimateLabel.constrainHeight("16")
bidView.alignAttribute(.Top, toAttribute: .Bottom, ofView: estimateLabel, predicate: "13")
bidButton.alignAttribute(.Top, toAttribute: .Bottom, ofView: currentBidLabel, predicate: "13")
moreInfoLabel.alignAttribute(.Top, toAttribute: .Bottom, ofView: bidButton, predicate: "0")
moreInfoLabel.constrainHeight("44")
moreInfoLabel.alignAttribute(.Bottom, toAttribute: .Bottom, ofView: contentView, predicate: "12")
RACObserve(lotNumberLabel, "text").subscribeNext { (text) -> Void in
switch text as! String? {
case .Some(let text) where text.isEmpty:
fallthrough
case .None:
lotNumberTopConstraint.constant = 0
artistNameTopConstraint.constant = 20
default:
lotNumberTopConstraint.constant = 20
artistNameTopConstraint.constant = 10
}
}
// Bind subviews
viewModelSignal.subscribeNext { [weak self] (viewModel) -> Void in
let viewModel = viewModel as! SaleArtworkViewModel
if let artworkImageViewHeightConstraint = self?.artworkImageViewHeightConstraint {
self?.artworkImageView.removeConstraint(artworkImageViewHeightConstraint)
}
let imageHeight = heightForImageWithAspectRatio(viewModel.thumbnailAspectRatio)
self?.artworkImageViewHeightConstraint = self?.artworkImageView.constrainHeight("\(imageHeight)").first as? NSLayoutConstraint
self?.layoutIfNeeded()
}
}
override func layoutSubviews() {
super.layoutSubviews()
bidView.drawTopDottedBorderWithColor(.artsyMediumGrey())
}
}
extension MasonryCollectionViewCell {
class func heightForCellWithImageAspectRatio(aspectRatio: CGFloat?) -> CGFloat {
let imageHeight = heightForImageWithAspectRatio(aspectRatio)
let remainingHeight =
20 + // padding
20 + // artist name
10 + // padding
16 + // artwork name
10 + // padding
16 + // estimate
13 + // padding
13 + // padding
16 + // bid
13 + // padding
44 + // more info button
12 // padding
return imageHeight + ButtonHeight + CGFloat(remainingHeight)
}
}
private func heightForImageWithAspectRatio(aspectRatio: CGFloat?) -> CGFloat {
if let ratio = aspectRatio {
if ratio != 0 {
return CGFloat(MasonryCollectionViewCellWidth) / ratio
}
}
return CGFloat(MasonryCollectionViewCellWidth)
}
| mit | 1179ae67bc76b21e6032fe37ae8b0018 | 42.880734 | 206 | 0.657537 | 5.574592 | false | false | false | false |
LYM-mg/MGDS_Swift | MGDS_Swift/MGDS_Swift/Class/Music/PlayMusic/View/MGLrcCell.swift | 1 | 2039 | //
// MGLrcCell.swift
// MGDS_Swift
//
// Created by i-Techsys.com on 17/3/4.
// Copyright © 2017年 i-Techsys. All rights reserved.
//
import UIKit
class MGLrcCell: UITableViewCell {
fileprivate var lrcLabel: MGLrcLabel!
/** 歌词内容*/
var lrcText: String? {
didSet {
self.lrcLabel.text = lrcText!
}
}
/** 进度 */
var progress: Double? {
didSet {
self.lrcLabel.progress = progress!
}
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
static func cellWithTableView(tableView: UITableView,reuseIdentifier: String?,indexPath: IndexPath) -> MGLrcCell { /// , for: indexPath
var cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier!) as? MGLrcCell
if (cell == nil) {
cell = MGLrcCell(style: .default, reuseIdentifier: reuseIdentifier)
cell!.backgroundColor = UIColor.clear
cell!.contentView.backgroundColor = UIColor.clear
// cell!.selectionStyle = .none
}
return cell!
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.backgroundColor = UIColor.clear
self.contentView.backgroundColor = UIColor.clear
lrcLabel = MGLrcLabel(frame: CGRect(x: 0, y: 0, width: MGScreenW, height: 44))
lrcLabel.isUserInteractionEnabled = true
lrcLabel.tag = 199
lrcLabel.textColor = UIColor.white
lrcLabel.textAlignment = .center
lrcLabel.sizeToFit()
lrcLabel.center = self.center
self.contentView.addSubview(lrcLabel)
lrcLabel!.snp.makeConstraints { (make) in
make.edges.equalToSuperview().offset(8)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 5522d4c15ccfde68e369269e472bf881 | 29.208955 | 139 | 0.620059 | 4.45815 | false | false | false | false |
wenghengcong/Coderpursue | BeeFun/BeeFun/View/BaseViewController/BFBaseViewController+Refresh.swift | 1 | 1576 | //
// BFBaseViewController+Refresh.swift
// BeeFun
//
// Created by WengHengcong on 2017/4/17.
// Copyright © 2017年 JungleSong. All rights reserved.
//
import UIKit
import MJRefresh
enum RefreshHidderType {
case none
case all
case header
case footer
}
extension BFBaseViewController : MJRefreshManagerAction {
@objc func headerRefresh() {
tableView.mj_header.endRefreshing()
// DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) {
// }
}
@objc func footerRefresh() {
tableView.mj_footer.endRefreshing()
// DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) {
// }
}
func endHeaderRefreshing() {
tableView.mj_header.endRefreshing()
}
func endFooterRefreshing() {
tableView.mj_footer.endRefreshing()
}
func endRefreshing() {
endHeaderRefreshing()
endFooterRefreshing()
}
func setRefreshHiddenOrShow() {
switch refreshHidden {
case .none:
self.tableView.mj_footer.isHidden = false
self.tableView.mj_header.isHidden = false
case .all:
self.tableView.mj_footer.isHidden = true
self.tableView.mj_header.isHidden = true
case .header:
self.tableView.mj_footer.isHidden = true
self.tableView.mj_header.isHidden = false
case .footer:
self.tableView.mj_footer.isHidden = false
self.tableView.mj_header.isHidden = true
}
}
}
| mit | 10181469195221f27fb35d19a5b2d754 | 23.968254 | 85 | 0.608392 | 4.381616 | false | false | false | false |
zmarvin/EnjoyMusic | Pods/Macaw/Source/model/geom2d/Arc.swift | 1 | 268 | import Foundation
open class Arc: Locus {
open let ellipse: Ellipse
open let shift: Double
open let extent: Double
public init(ellipse: Ellipse, shift: Double = 0, extent: Double = 0) {
self.ellipse = ellipse
self.shift = shift
self.extent = extent
}
}
| mit | b183ca406dcf0f85499ad9e6794cd007 | 16.866667 | 71 | 0.701493 | 3.268293 | false | false | false | false |
FoodMob/FoodMob-iOS | FoodMob/Model/Restaurant.swift | 1 | 3558 | //
// Restaurant.swift
// FoodMob
//
// Created by Jonathan Jemson on 3/1/16.
// Copyright © 2016 FoodMob. All rights reserved.
//
import UIKit.UIImage
import SwiftyJSON
import CoreLocation
public struct Restaurant {
/// Restaurant name
private(set) public var name: String
/// Categories string
private(set) public var categories: String = ""
/// Stars, out of 5
private(set) public var stars: Double
/// Number of reviews
private(set) public var numReviews: Int
/// Open hours, deprecated
private(set) public var hours: String
/// Restaurant phone number
private(set) public var phoneNumber: String
/// Restaurant address
private(set) public var address: String
/// Yelp URL to open in Yelp application.
public var yelpURL: NSURL? = nil
/// Restaurant location, coordinate
private(set) public var location: CLLocationCoordinate2D?
/// Image URL for the restaurant's cover photo
public var imageURL: NSURL?
/// Deprecated, but used to convert categories to a string.
public var categoriesString: String {
return categories
}
/**
Convenience initializer for a restaurant.
- parameter name: Restaurant name
- parameter categories: Food categories represented by the restaurant
- parameter stars: Number of stars, out of 5
- parameter numReviews: Number of reviews
- parameter hours: Hours the restaurant is opened
- parameter phoneNumber: The phone number of the restaurant
- parameter address: Restaurant address
*/
public init(name: String, categories: [FoodCategory], stars: Double, numReviews: Int, hours: String, phoneNumber: String, address: String, yelpURL: NSURL? = nil) {
self.init(name: name, categories: categories.reduce("", combine: { (str, cat) -> String in return "\(str), \(cat.displayName)" }), stars: stars, numReviews: numReviews, hours: hours, phoneNumber: phoneNumber, address: address, yelpURL: yelpURL)
}
/**
Designated initializer for a restaurant.
- parameter name: Restaurant name
- parameter categories: Food categories represented by the restaurant, as a string
- parameter stars: Number of stars, out of 5
- parameter numReviews: Number of reviews
- parameter hours: Hours the restaurant is opened
- parameter phoneNumber: The phone number of the restaurant
- parameter address: Restaurant address
- parameter yelpURL: URL to Yelp page for restaurant.
*/
public init(name: String, categories: String, stars: Double, numReviews: Int, hours: String, phoneNumber: String, address: String, yelpURL: NSURL? = nil) {
self.name = name
self.categories = categories
self.stars = stars
self.numReviews = numReviews
self.hours = hours
self.phoneNumber = phoneNumber
self.address = address
self.yelpURL = yelpURL
}
}
/**
Struct which holds JSON field name constants for Restaurants
*/
internal struct RestaurantField {
static let root = "businesses"
static let objectName = "restaurant"
static let name = "name"
static let categories = "categories"
static let stars = "rating"
static let reviewCount = "review_count"
static let hoursOpen = "hoursOpen"
static let phoneNumber = "display_phone"
static let address = "display_address"
static let yelpURL = "mobile_url"
static let imageURL = "image_url"
static let location = "location"
} | mit | 6bccd16a94f30c8966512a03159b6413 | 36.452632 | 252 | 0.677256 | 4.554417 | false | false | false | false |
ResearchSuite/ResearchSuiteExtensions-iOS | Example/Pods/ResearchSuiteTaskBuilder/ResearchSuiteTaskBuilder/Classes/Task Providers/RSTBOrderedTaskGenerator.swift | 1 | 806 | //
// RSTBOrderedTaskGenerator.swift
// Pods
//
// Created by James Kizer on 6/30/17.
//
//
import UIKit
import Gloss
import ResearchKit
open class RSTBOrderedTaskGenerator: RSTBTaskGenerator {
open static func supportsType(type: String) -> Bool {
return type == "orderedTask"
}
open static func generateTask(type: String, jsonObject: JSON, helper: RSTBTaskBuilderHelper) -> ORKTask? {
guard let taskDescriptor = RSTBTaskDescriptor(json: jsonObject),
let taskBuilder = helper.builder,
let steps: [ORKStep] = taskBuilder.steps(forElement: taskDescriptor.rootStepElement as JsonElement) else {
return nil
}
return ORKOrderedTask(identifier: taskDescriptor.identifier, steps: steps)
}
}
| apache-2.0 | ea0cc9cae5ad7c8f590a317f5c3b2eb2 | 25.866667 | 118 | 0.662531 | 4.502793 | false | false | false | false |
yourkarma/Notify | Pod/Classes/Theme.swift | 1 | 1692 | import UIKit
public struct Color {
public static let White = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
public static let Red = UIColor(red: 249.0 / 255.0, green: 70.0 / 255.0, blue: 28.0 / 255.0, alpha: 1.0)
public static let RedDarkened = UIColor(red: 197.0 / 255.0, green: 55.0 / 255.0, blue: 33.0 / 255.0, alpha: 1.0)
public static let Blue = UIColor(red: 0.0 / 255.0, green: 178.0 / 255.0, blue: 226.0 / 255.0, alpha: 1.0)
public static let BlueDarkened = UIColor(red: 23.0 / 255.0, green: 149.0 / 255.0, blue: 187.0 / 255.0, alpha: 1.0)
public static let DarkBlue = UIColor(red: 14.0 / 255.0, green: 47.0 / 255.0, blue: 60.0 / 255.0, alpha: 1.0)
public static let LightBlue = UIColor(red: 199.0 / 255.0, green: 213.0 / 255.0, blue: 217.0 / 255.0, alpha: 1.0)
public static let Green = UIColor(red: 0.0 / 255.0, green: 147.0 / 255.0, blue: 62.0 / 255.0, alpha: 1.0)
public static let Black = UIColor(red: 16.0 / 255.0, green: 24.0 / 255.0, blue: 32.0 / 255.0, alpha: 1.0)
public static let Gray = UIColor(red: 193.0 / 255.0, green: 202.0 / 255.0, blue: 206.0 / 255.0, alpha: 1.0)
}
struct Theme {
static func fontOfSize(_ fontSize: CGFloat) -> UIFont {
return UIFont(name: "apercu-light", size: fontSize)!
}
static func boldFontOfSize(_ fontSize: CGFloat) -> UIFont {
return UIFont(name: "apercu-bold", size: fontSize)!
}
static func mediumFontOfSize(_ fontSize: CGFloat) -> UIFont {
return UIFont(name: "apercu-medium", size: fontSize)!
}
static func regularFontOfSize(_ fontSize: CGFloat) -> UIFont {
return UIFont(name: "apercu-regular", size: fontSize)!
}
}
| mit | cbf61d4ec67f82aa512f481c7bedce18 | 43.526316 | 118 | 0.626478 | 2.907216 | false | false | false | false |
WalterCreazyBear/Swifter30 | ClassicPhoto/ClassicPhoto/ViewController.swift | 1 | 8259 | //
// ViewController.swift
// ClassicPhoto
//
// Created by 熊伟 on 2017/7/2.
// Copyright © 2017年 Bear. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let dataSourceURL = "http://www.raywenderlich.com/downloads/ClassicPhotosDictionary.plist"
var photos : [PhotoRecord] = [PhotoRecord]()
let pendingOperations = PendingOperations()
lazy var tableView : UITableView = {
let tableView = UITableView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
tableView.dataSource = self
tableView.delegate = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: String(describing: UITableViewCell.self))
tableView.backgroundColor = UIColor.white
return tableView
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
fetchPhotoDetails()
view.addSubview(tableView)
}
fileprivate func fetchPhotoDetails() {
SessionWrapper.getData(dataSourceURL, callback: { (data) in
if let data = data {
do {
if let datasourceDictionary = try PropertyListSerialization.propertyList(from: data, options: PropertyListSerialization.ReadOptions(rawValue: 0), format: nil) as? [String: AnyObject] {
for (name, url) in datasourceDictionary {
if let url = URL(string: url as! String) {
let photoRecord = PhotoRecord(name:name, url: url)
self.photos.append(photoRecord)
}
}
self.tableView.reloadData()
}
} catch let error as NSError {
print(error.domain)
}
}
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}) { (error) in
let alert = UIAlertView(title:"Oops!", message: error.localizedDescription, delegate:nil, cancelButtonTitle:"OK")
alert.show()
}
}
fileprivate func startOperationsForPhotoRecord(photoDetails: PhotoRecord, indexPath: IndexPath){
switch (photoDetails.state) {
case .New:
startDownloadForRecord(photoDetails: photoDetails, indexPath: indexPath)
case .Downloaded:
startFiltrationForRecord(photoDetails: photoDetails, indexPath: indexPath)
default:
NSLog("do nothing")
}
}
fileprivate func startDownloadForRecord(photoDetails: PhotoRecord, indexPath: IndexPath){
if let _ = pendingOperations.downloadsInProgress[indexPath] {
return
}
let downloader = ImageDownloader(photoRecord: photoDetails)
downloader.completionBlock = {
if downloader.isCancelled {
return
}
DispatchQueue.main.async {
self.pendingOperations.downloadsInProgress.removeValue(forKey: indexPath)
self.tableView.reloadRows(at: [indexPath], with: .fade)
}
}
pendingOperations.downloadsInProgress[indexPath] = downloader
pendingOperations.downloadQueue.addOperation(downloader)
}
fileprivate func startFiltrationForRecord(photoDetails: PhotoRecord, indexPath: IndexPath){
if let _ = pendingOperations.filtrationsInProgress[indexPath]{
return
}
let filterer = ImageFiltration(photoRecord: photoDetails)
filterer.completionBlock = {
if filterer.isCancelled {
return
}
DispatchQueue.main.async {
self.pendingOperations.filtrationsInProgress.removeValue(forKey: indexPath)
self.tableView.reloadRows(at: [indexPath], with: .fade)
}
}
pendingOperations.filtrationsInProgress[indexPath] = filterer
pendingOperations.filtrationQueue.addOperation(filterer)
}
fileprivate func suspendAllOperations () {
pendingOperations.downloadQueue.isSuspended = true
pendingOperations.filtrationQueue.isSuspended = true
}
fileprivate func resumeAllOperations () {
pendingOperations.downloadQueue.isSuspended = false
pendingOperations.filtrationQueue.isSuspended = false
}
fileprivate func loadImagesForOnscreenCells () {
if let pathsArray = tableView.indexPathsForVisibleRows {
var allPendingOperations = Set(pendingOperations.downloadsInProgress.keys)
allPendingOperations = allPendingOperations.union(pendingOperations.filtrationsInProgress.keys)
// get cells should cancel operations
var toBeCancelled = allPendingOperations
let visiblePaths = Set(pathsArray)
toBeCancelled.subtract(visiblePaths)
// get cells should be started as new
var toBeStarted = visiblePaths
toBeStarted.subtract(allPendingOperations)
// cancel download and filter operations for unvisible cells
for indexPath in toBeCancelled {
if let pendingDownload = pendingOperations.downloadsInProgress[indexPath] {
pendingDownload.cancel()
}
pendingOperations.downloadsInProgress.removeValue(forKey: indexPath)
if let pendingFiltration = pendingOperations.filtrationsInProgress[indexPath] {
pendingFiltration.cancel()
}
pendingOperations.filtrationsInProgress.removeValue(forKey: indexPath)
}
// start operation for new visible cells
for indexPath in toBeStarted {
let recordToProcess = self.photos[indexPath.row]
startOperationsForPhotoRecord(photoDetails: recordToProcess, indexPath: indexPath)
}
}
}
}
extension ViewController:UIScrollViewDelegate
{
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
suspendAllOperations()
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if !decelerate {
loadImagesForOnscreenCells()
resumeAllOperations()
}
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
loadImagesForOnscreenCells()
resumeAllOperations()
}
}
extension ViewController:UITableViewDataSource, UITableViewDelegate
{
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return photos.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell : UITableViewCell = tableView.dequeueReusableCell(withIdentifier: String(describing: UITableViewCell.self), for: indexPath)
if cell.accessoryView == nil {
let indicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
cell.accessoryView = indicator
}
let indicator = cell.accessoryView as! UIActivityIndicatorView
let photoDetails = photos[indexPath.row]
cell.textLabel?.text = photoDetails.name
cell.imageView?.image = photoDetails.image
switch (photoDetails.state){
case .Filtered:
indicator.stopAnimating()
case .Failed:
indicator.stopAnimating()
cell.textLabel?.text = "Failed to load"
case .New, .Downloaded:
indicator.startAnimating()
if (!tableView.isDragging && !tableView.isDecelerating) {
self.startOperationsForPhotoRecord(photoDetails: photoDetails,indexPath: indexPath)
}
}
return cell
}
}
| mit | 497d50d10f857bc1f1cd18dca62593a7 | 36.004484 | 204 | 0.61682 | 5.648186 | false | false | false | false |
wayfair/brickkit-ios | Example/Source/Bricks/Stepper/StepperBrick.swift | 2 | 1900 | //
// ExampleStepperBrick.swift
// BrickApp
//
// Created by Ruben Cagnie on 5/26/16.
// Copyright © 2016 Wayfair. All rights reserved.
//
import UIKit
import BrickKit
public class StepperBrick: Brick {
public let dataSource: StepperBrickCellDataSource
public let delegate: StepperBrickCellDelegate
public init(_ identifier: String, width: BrickDimension = .ratio(ratio: 1), height: BrickDimension = .auto(estimate: .fixed(size: 50)), backgroundColor: UIColor = UIColor.clear, backgroundView: UIView? = nil, dataSource: StepperBrickCellDataSource, delegate: StepperBrickCellDelegate) {
self.dataSource = dataSource
self.delegate = delegate
super.init(identifier, size: BrickSize(width: width, height: height), backgroundColor: backgroundColor, backgroundView: backgroundView)
}
}
public class StepperBrickModel: StepperBrickCellDataSource {
public var count: Int
public init(count: Int){
self.count = count
}
public func countForExampleStepperBrickCell(cell: StepperBrickCell) -> Int {
return count
}
}
public protocol StepperBrickCellDataSource {
func countForExampleStepperBrickCell(cell: StepperBrickCell) -> Int
}
public protocol StepperBrickCellDelegate {
func stepperBrickCellDidUpdateStepper(cell: StepperBrickCell)
}
public class StepperBrickCell: BrickCell, Bricklike {
public typealias BrickType = StepperBrick
@IBOutlet weak public var label: UILabel!
@IBOutlet weak public var stepper: UIStepper!
override public func updateContent() {
super.updateContent()
let count = brick.dataSource.countForExampleStepperBrickCell(cell: self)
label.text = String(count)
stepper.value = Double(count)
}
@IBAction func stepperDidUpdate(_ sender: UIStepper) {
brick.delegate.stepperBrickCellDidUpdateStepper(cell: self)
}
}
| apache-2.0 | f3ab6806c47b3e16830f8e4d17f60629 | 30.131148 | 290 | 0.729858 | 4.609223 | false | false | false | false |
the-blue-alliance/the-blue-alliance-ios | Frameworks/TBAUtils/Sources/Calendar/Calendar+TBA.swift | 1 | 1752 | import Foundation
public enum Month: Int {
case January = 1, February, March, April, May, June, July, August,
September, October, November, December
}
public enum Weekday: Int {
case Sunday = 1, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday
}
extension Calendar {
/**
Number of weeks the season is - safely hardcoded to 6.
*/
public var seasonLengthWeeks: Int {
return 6
}
/**
The year for the current date.
*/
public var year: Int {
get {
return self.component(.year, from: Date())
}
}
/*
Computes the date of Kickoff for a given year. Kickoff is always the first Saturday in January after Jan 2nd.
- Parameter year: The year to find the kickoff date for - defaults to current year if nil.
- Returns: The date of Kickoff for the given year.
*/
public func kickoff(_ year: Int? = nil) -> Date {
let firstOfTheYearComponents = DateComponents(year: year ?? self.year, month: Month.January.rawValue, day: 2)
return date(from: firstOfTheYearComponents)!.next(.Saturday)
}
/**
Computes day teams are done working on robots. The stop build day is kickoff + 6 weeks + 3 days.
- Parameter year: The year to find the stop build date for - defaults to current year if nil.
- Returns: The stop build date for the given year.
*/
public func stopBuildDay(_ year: Int? = nil) -> Date {
let numberOfDaysInWeek = weekdaySymbols.count
if numberOfDaysInWeek == 0 {
assertionFailure("numberOfDaysInWeek should be > 0")
}
return date(byAdding: DateComponents(day: (numberOfDaysInWeek * seasonLengthWeeks + 3)), to: kickoff(year))!
}
}
| mit | dbb35f9cc245cfc230b6e00576fe356c | 29.736842 | 117 | 0.642123 | 4.283619 | false | false | false | false |
wireapp/wire-ios-data-model | Patches/TransferApplockKeychain.swift | 1 | 2383 | //
// Wire
// Copyright (C) 2019 Wire Swiss GmbH
//
// 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 Foundation
struct TransferApplockKeychain {
static func migrateKeychainItems(in moc: NSManagedObjectContext) {
migrateIsAppLockActiveState(in: moc)
migrateAppLockPasscode(in: moc)
}
/// Save the enable state of the applock feature in the managedObjectContext instead of the keychain.
static func migrateIsAppLockActiveState(in moc: NSManagedObjectContext) {
let selfUser = ZMUser.selfUser(in: moc)
guard
let data = ZMKeychain.data(forAccount: "lockApp"),
data.count != 0
else {
selfUser.isAppLockActive = false
return
}
selfUser.isAppLockActive = String(data: data, encoding: .utf8) == "YES"
}
/// Migrate the single legacy passcode (account agnostic) to potentially several (account specific)
/// keychain entries.
static func migrateAppLockPasscode(in moc: NSManagedObjectContext) {
guard let selfUserId = ZMUser.selfUser(in: moc).remoteIdentifier else { return }
let legacyKeychainItem = AppLockController.PasscodeKeychainItem.legacyItem
guard
let passcode = try? Keychain.fetchItem(legacyKeychainItem),
!passcode.isEmpty
else {
return
}
let item = AppLockController.PasscodeKeychainItem(userId: selfUserId)
try? Keychain.storeItem(item, value: passcode)
}
}
private extension Bundle {
var sharedContainerURL: URL? {
return appGroupIdentifier.map(FileManager.sharedContainerDirectory)
}
var appGroupIdentifier: String? {
return bundleIdentifier.map { "group." + $0 }
}
}
| gpl-3.0 | 5ed4cf40236fd624dd8a75826fc8d7ac | 30.773333 | 105 | 0.681494 | 4.700197 | false | false | false | false |
StephenZhuang/Gongyinglian | Gongyinglian/Gongyinglian/SoldViewController.swift | 1 | 11045 | //
// SoldViewController.swift
// Gongyinglian
//
// Created by Stephen Zhuang on 14-7-7.
// Copyright (c) 2014年 udows. All rights reserved.
//
import UIKit
class SoldViewController: UITableViewController {
var dataArray: NSMutableArray?
var mdArray: NSMutableArray?
var scanCode: NSString = ""
var isSell: Bool = true
@IBOutlet var codeTextField: UITextField?
@IBOutlet var topView: UIView?
init(style: UITableViewStyle) {
super.init(style: style)
// Custom initialization
}
init(coder aDecoder: NSCoder!) {
super.init(coder: aDecoder)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.navigationController.setNavigationBarHidden(false, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
self.topView!.frame.size.height = 50
if isSell {
self.addTitleView(title: "售出", subtitle: "售出查询")
} else {
self.addTitleView(title: "退货", subtitle: "退货查询")
}
self.dataArray = NSMutableArray()
self.mdArray = NSMutableArray()
self.refreshControl.addTarget(self, action: Selector("refreshControlValueChanged"), forControlEvents: .ValueChanged)
// self.refreshControl!.beginRefreshing()
// loadData()
}
func refreshControlValueChanged() {
if self.refreshControl.refreshing {
loadData()
}
}
func loadData() {
var params: NSMutableDictionary = NSMutableDictionary()
var dic: NSMutableDictionary = NSMutableDictionary()
dic.setObject("com.shqj.webservice.entity.UserKeyAndSMCode", forKey: "class")
dic.setObject(scanCode, forKey: "smcode")
dic.setObject(ToolUtils.shareInstance().user!.key, forKey: "key")
let jsonString: NSString = dic.JSONString()
params.setObject(jsonString, forKey: "str")
var webservice: WebServiceRead = WebServiceRead()
webservice = WebServiceRead(self , selecter:Selector("webServiceFinished:"))
webservice.postWithMethodName("doQueryCKBySMM", params: params)
if ToolUtils.shareInstance().user!.usertype.toInt() == 1 {
loadMD()
}
}
func webServiceFinished(data: NSString) {
var dic: NSDictionary = data.objectFromJSONString() as NSDictionary
var jdkList: QueryCKBySMMList = QueryCKBySMMList()
jdkList.build(dic)
self.dataArray!.removeAllObjects()
// var range: NSRange = data.rangeOfString("null")
// if(range.location == NSIntegerMax) {
self.dataArray!.addObjectsFromArray(jdkList.data)
// }
self.tableView!.reloadData()
if self.refreshControl.refreshing {
self.refreshControl.endRefreshing()
}
}
func loadMD() {
var params: NSMutableDictionary = NSMutableDictionary()
var dic: NSMutableDictionary = NSMutableDictionary()
dic.setObject("com.shqj.webservice.entity.UserKeyAndSMCode", forKey: "class")
dic.setObject(scanCode, forKey: "smcode")
dic.setObject(ToolUtils.shareInstance().user!.key, forKey: "key")
let jsonString: NSString = dic.JSONString()
params.setObject(jsonString, forKey: "userkey")
var webservice: WebServiceRead = WebServiceRead()
webservice = WebServiceRead(self , selecter:Selector("loadMDFinished:"))
webservice.postWithMethodName("doQueryALLkc", params: params)
}
func loadMDFinished(data: NSString) {
var dic: NSDictionary = data.objectFromJSONString() as NSDictionary
var jdkList: QueryXjCKList = QueryXjCKList()
jdkList.build(dic)
self.mdArray!.removeAllObjects()
// var range: NSRange = data.rangeOfString("null")
// if(range.location == NSIntegerMax) {
self.mdArray!.addObjectsFromArray(jdkList.data)
// }
self.tableView!.reloadData()
if self.refreshControl.refreshing {
self.refreshControl.endRefreshing()
}
}
@IBAction func sellAction(sender: UIButton?) {
var params: NSMutableDictionary = NSMutableDictionary()
var dic: NSMutableDictionary = NSMutableDictionary()
dic.setObject("com.shqj.webservice.entity.Userxsck", forKey: "class")
dic.setObject(scanCode, forKey: "smcode")
if (ToolUtils.shareInstance().user!.usertype.toInt() == 1) {
var queryckbysmm:QueryXjCK = self.mdArray!.objectAtIndex(sender!.tag) as QueryXjCK
dic.setObject(queryckbysmm.key, forKey: "mdkey")
} else {
dic.setObject("a", forKey: "mdkey")
}
if isSell {
dic.setObject("a", forKey: "isth")
} else {
dic.setObject("Y", forKey: "isth")
}
dic.setObject(ToolUtils.shareInstance().user!.key, forKey: "key")
let jsonString: NSString = dic.JSONString()
params.setObject(jsonString, forKey: "userxmck")
var webservice: WebServiceRead = WebServiceRead()
webservice = WebServiceRead(self , selecter:Selector("sellFinished:"))
webservice.postWithMethodName("doXsck", params: params)
}
func sellFinished(data: NSString) {
// println(data)
if isSell {
ProgressHUD.showSuccess("售出成功")
} else {
ProgressHUD.showSuccess("退货成功")
}
}
@IBAction func goToQRImageController() {
if (NSFoundationVersionNumber >= NSFoundationVersionNumber_iOS_7_0) {
var vc: Ios7QRViewController = Ios7QRViewController()
vc.scanBlock = {
(NSString code) in
self.scanCode = code
self.codeTextField!.text = code
self.loadData()
}
self.navigationController.pushViewController(vc ,animated:true)
} else {
var vc: Ios6QRViewController = Ios6QRViewController()
vc.scanBlock = {
(NSString code) in
self.scanCode = code
self.codeTextField!.text = code
self.loadData()
}
self.navigationController.pushViewController(vc ,animated:true)
}
}
func textFieldShouldReturn(textField: UITextField!) -> Bool {
textField.resignFirstResponder()
self.scanCode = textField.text
self.loadData()
return true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// #pragma mark - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView?) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 2
}
override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
if section == 0 {
return self.dataArray!.count
} else {
return self.mdArray!.count
}
}
override func tableView(tableView: UITableView?, heightForRowAtIndexPath indexPath: NSIndexPath?) -> CGFloat {
if indexPath!.section == 0 {
return 97
}
return 71
}
override func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell? {
if (indexPath!.section == 0) {
let cell : GoodsCell! = tableView!.dequeueReusableCellWithIdentifier("cell") as GoodsCell
// Configure the cell...
var queryckbysmm:QueryCKBySMM = self.dataArray!.objectAtIndex(indexPath!.row) as QueryCKBySMM
cell.nameLabel.text = queryckbysmm.spname?
cell.codeLabel.text = queryckbysmm.spcode?
cell.countLabel.text = queryckbysmm.spcount?.stringValue
if (ToolUtils.shareInstance().user!.usertype.toInt() == 1) {
cell.sellButton.hidden = true
} else {
cell.sellButton.hidden = false
}
if isSell {
cell.sellButton.titleLabel.text = "售出"
} else {
cell.sellButton.titleLabel.text = "退货"
}
return cell
} else {
let cell : GoodsCell! = tableView!.dequeueReusableCellWithIdentifier("mdcell") as GoodsCell
// Configure the cell...
var queryckbysmm:QueryXjCK = self.mdArray!.objectAtIndex(indexPath!.row) as QueryXjCK
cell.nameLabel.text = queryckbysmm.mdname?
cell.countLabel.text = queryckbysmm.spcount?.stringValue
cell.sellButton.tag = indexPath!.row
return cell
}
}
override func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
tableView!.deselectRowAtIndexPath(indexPath , animated:true)
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView?, canEditRowAtIndexPath indexPath: NSIndexPath?) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView?, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath?) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView?, moveRowAtIndexPath fromIndexPath: NSIndexPath?, toIndexPath: NSIndexPath?) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView?, canMoveRowAtIndexPath indexPath: NSIndexPath?) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
/*
// #pragma 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 | 64c09d8fdbd41755f1d5e37e9a05ddfe | 36.783505 | 159 | 0.622465 | 4.847884 | false | false | false | false |
voidException/Locksmith | Source/Dictionary_Initializers.swift | 28 | 721 | import Foundation
public extension Dictionary {
init(withoutOptionalValues initial: Dictionary<Key, Value?>) {
self = [Key: Value]()
for pair in initial {
if pair.1 != nil {
self[pair.0] = pair.1!
}
}
}
init(pairs: [(Key, Value)]) {
self = [Key: Value]()
pairs.forEach { (k, v) -> () in
self[k] = v
}
}
init(initial: Dictionary<Key, Value>, toMerge: Dictionary<Key, Value>) {
self = Dictionary<Key, Value>()
for pair in initial {
self[pair.0] = pair.1
}
for pair in toMerge {
self[pair.0] = pair.1
}
}
}
| mit | 404396092b926aa3e21fbcefe3732364 | 22.258065 | 76 | 0.457698 | 4.005556 | false | false | false | false |
milseman/swift | stdlib/public/core/ASCII.swift | 5 | 2888 | //===--- ASCII.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
//
//===----------------------------------------------------------------------===//
extension Unicode {
@_fixed_layout
public enum ASCII {}
}
extension Unicode.ASCII : Unicode.Encoding {
public typealias CodeUnit = UInt8
public typealias EncodedScalar = CollectionOfOne<CodeUnit>
public static var encodedReplacementCharacter : EncodedScalar {
return EncodedScalar(0x1a) // U+001A SUBSTITUTE; best we can do for ASCII
}
@inline(__always)
@_inlineable
public static func _isScalar(_ x: CodeUnit) -> Bool {
return true
}
@inline(__always)
@_inlineable
public static func decode(_ source: EncodedScalar) -> Unicode.Scalar {
return Unicode.Scalar(_unchecked: UInt32(
source.first._unsafelyUnwrappedUnchecked))
}
@inline(__always)
@_inlineable
public static func encode(
_ source: Unicode.Scalar
) -> EncodedScalar? {
guard source.value < (1&<<7) else { return nil }
return EncodedScalar(UInt8(truncatingIfNeeded: source.value))
}
@inline(__always)
public static func transcode<FromEncoding : Unicode.Encoding>(
_ content: FromEncoding.EncodedScalar, from _: FromEncoding.Type
) -> EncodedScalar? {
if _fastPath(FromEncoding.self == UTF16.self) {
let c = _identityCast(content, to: UTF16.EncodedScalar.self)
guard (c._storage & 0xFF80 == 0) else { return nil }
return EncodedScalar(CodeUnit(c._storage & 0x7f))
}
else if _fastPath(FromEncoding.self == UTF8.self) {
let c = _identityCast(content, to: UTF8.EncodedScalar.self)
let first = c.first.unsafelyUnwrapped
guard (first < 0x80) else { return nil }
return EncodedScalar(CodeUnit(first))
}
return encode(FromEncoding.decode(content))
}
public struct Parser {
public init() { }
}
public typealias ForwardParser = Parser
public typealias ReverseParser = Parser
}
extension Unicode.ASCII.Parser : Unicode.Parser {
public typealias Encoding = Unicode.ASCII
/// Parses a single Unicode scalar value from `input`.
public mutating func parseScalar<I : IteratorProtocol>(
from input: inout I
) -> Unicode.ParseResult<Encoding.EncodedScalar>
where I.Element == Encoding.CodeUnit {
let n = input.next()
if _fastPath(n != nil), let x = n {
guard _fastPath(Int8(truncatingIfNeeded: x) >= 0)
else { return .error(length: 1) }
return .valid(Unicode.ASCII.EncodedScalar(x))
}
return .emptyInput
}
}
| apache-2.0 | d1e21fe30d784bacb8222244b234f306 | 31.449438 | 80 | 0.657548 | 4.369138 | false | false | false | false |
vulcancreative/chinwag-swift | Tests/DictionaryTests.swift | 1 | 2277 | //
// DictionaryTests.swift
// Chinwag
//
// Created by Chris Calo on 2/26/15.
// Copyright (c) 2015 Chris Calo. All rights reserved.
//
import Foundation
import Chinwag
import XCTest
class DictionaryTests: XCTestCase {
var blank = Chinwag.open()
var seuss = Chinwag.open()
var latin = Chinwag.open()
override func setUp() {
super.setUp()
blank = Chinwag.open()
seuss = Chinwag.open(embedded: .Seuss)!
latin = Chinwag.open(embedded: .Latin)!
}
override func tearDown() {
super.tearDown()
blank.close()
seuss.close()
latin.close()
}
func openTestCase(filename: String)
-> String? {
let manager = NSFileManager.defaultManager()
let base = "Tests/TestCases"
let file = base + "/" + filename
if manager.fileExistsAtPath(file) {
let enc = UnsafeMutablePointer<UInt>()
return String(contentsOfFile: file, usedEncoding: enc, error: nil)
}
return nil
}
func testCWDictGetName() {
XCTAssertEqual(blank.name, "", "name should be a empty")
XCTAssertEqual(seuss.name, "Seussian", "name should be \"Seussian\"")
XCTAssertEqual(latin.name, "Latin", "name should be \"Latin\"")
}
func testCWDictSetname() {
blank.name = "blank"
seuss.name = "Geisel"
XCTAssertEqual(blank.name, "blank", "name should be \"blank\"")
XCTAssertEqual(seuss.name, "Geisel", "name should be \"Geisel\"")
}
func testCWDictCopy() {
let testCaseOne = openTestCase("chinwag_testcase_seuss_dict_to_s")
if testCaseOne == nil {
XCTFail("test case should not be nil")
}
var clone = seuss.copy() as CWDict
XCTAssertEqual(seuss.string(), testCaseOne!, "should match test case")
XCTAssertEqual(clone.string(), testCaseOne!, "should match test case")
seuss.close()
XCTAssertEqual(seuss.string(), "[]", "should be closed")
XCTAssertEqual(clone.string(), testCaseOne!, "should match test case")
seuss = clone.copy() as CWDict
XCTAssertEqual(seuss.string(), testCaseOne!, "should match test case")
XCTAssertEqual(clone.string(), testCaseOne!, "should match test case")
clone.close()
XCTAssertEqual(seuss.string(), testCaseOne!, "should match test case")
XCTAssertEqual(clone.string(), "[]", "should be closed")
}
}
| mit | a915d5ee68688feb805b6c5508c617cb | 25.788235 | 74 | 0.662714 | 3.732787 | false | true | false | false |
SusanDoggie/Doggie | Sources/DoggieGeometry/ShapeRegion/BreakLoop.swift | 1 | 11562 | //
// BreakLoop.swift
//
// The MIT License
// Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
extension Point {
fileprivate func _round_to_float() -> Point {
return Point(x: Double(Float(x)), y: Double(Float(y)))
}
}
extension Shape.Segment {
fileprivate func _round_to_float() -> Shape.Segment {
switch self {
case let .line(p1): return .line(p1._round_to_float())
case let .quad(p1, p2): return .quad(p1._round_to_float(), p2._round_to_float())
case let .cubic(p1, p2, p3): return .cubic(p1._round_to_float(), p2._round_to_float(), p3._round_to_float())
}
}
}
extension Shape.BezierSegment {
fileprivate func _round_to_float() -> Shape.BezierSegment {
return Shape.BezierSegment(start: start._round_to_float(), segment: segment._round_to_float())
}
}
extension Shape.Component {
fileprivate func _round_to_float() -> Shape.Component {
return Shape.Component(start: start._round_to_float(), closed: isClosed, segments: segments.map { $0._round_to_float() })
}
func breakLoop(reference: Double) -> [ShapeRegion.Solid] {
let epsilon = -1e-8 * Swift.max(1, abs(reference))
var intersects: [(InterscetionTable.Split, InterscetionTable.Split)] = []
for (index1, segment1) in bezier.enumerated() {
for (index2, segment2) in bezier.suffix(from: index1 + 1).indexed() {
if !segment2.boundary.inset(dx: epsilon, dy: epsilon).isIntersect(segment1.boundary.inset(dx: epsilon, dy: epsilon)) {
continue
}
if let _intersects = segment1.intersect(segment2) {
for _intersect in _intersects {
let s0 = InterscetionTable.Split(point: segment1.point(_intersect.0), index: index1, count: self.count, split: _intersect.0)
let s1 = InterscetionTable.Split(point: segment2.point(_intersect.1), index: index2, count: self.count, split: _intersect.1)
if s0.almostEqual(s1) {
continue
}
if intersects.contains(where: { $0.almostEqual(s0) && $1.almostEqual(s1) }) {
continue
}
if intersects.contains(where: { $1.almostEqual(s0) && $0.almostEqual(s1) }) {
continue
}
intersects.append((s0, s1))
}
} else {
if let a = segment2._closest(segment1.end) {
let s0 = InterscetionTable.Split(point: segment1.end, index: index1, count: self.count, split: 1)
let s1 = InterscetionTable.Split(point: segment2.point(a), index: index2, count: self.count, split: a)
if s0.almostEqual(s1) {
continue
}
if intersects.contains(where: { $0.almostEqual(s0) && $1.almostEqual(s1) }) {
continue
}
if intersects.contains(where: { $1.almostEqual(s0) && $0.almostEqual(s1) }) {
continue
}
intersects.append((s0, s1))
}
if let b = segment1._closest(segment2.start) {
let s0 = InterscetionTable.Split(point: segment1.point(b), index: index1, count: self.count, split: b)
let s1 = InterscetionTable.Split(point: segment2.start, index: index2, count: self.count, split: 0)
if s0.almostEqual(s1) {
continue
}
if intersects.contains(where: { $0.almostEqual(s0) && $1.almostEqual(s1) }) {
continue
}
if intersects.contains(where: { $1.almostEqual(s0) && $0.almostEqual(s1) }) {
continue
}
intersects.append((s0, s1))
}
}
}
}
return breakLoop(intersects, reference: reference)
}
func breakLoop(_ points: [(InterscetionTable.Split, InterscetionTable.Split)], reference: Double) -> [ShapeRegion.Solid] {
if points.isEmpty {
return ShapeRegion.Solid(segments: self.bezier, reference: reference).map { [$0] } ?? []
}
var result: [ShapeRegion.Solid] = []
var graph = Graph<Int, [(InterscetionTable.Split, InterscetionTable.Split)]>()
let _points = points.enumerated().flatMap { [($0, $1.0), ($0, $1.1)] }.sorted { $0.1 < $1.1 }
for (left, right) in _points.rotateZip() {
if left.0 == right.0 {
if let solid = ShapeRegion.Solid(segments: self.split_path(left.1, right.1).map { $0._round_to_float() }, reference: reference) {
result.append(solid)
}
} else {
graph[from: left.0, to: right.0, default: []].append((left.1, right.1))
}
}
while let graph_first = graph.first {
var path: [Int] = [graph_first.from, graph_first.to]
while let last = path.last, let node = graph.nodes(from: last).first?.0 {
if let i = path.firstIndex(where: { $0 == node }) {
let loop = path.suffix(from: i)
var segments: [ShapeRegion.Solid.Segment] = []
for (left, right) in loop.rotateZip() {
if let split = graph[from: left, to: right]?.last {
segments.append(contentsOf: self.split_path(split.0, split.1))
if var splits = graph[from: left, to: right], splits.count != 1 {
splits.removeLast()
graph[from: left, to: right] = splits
} else {
graph[from: left, to: right] = nil
}
}
}
if let solid = ShapeRegion.Solid(segments: segments.map { $0._round_to_float() }, reference: reference) {
result.append(solid)
}
if i == 0 {
break
}
path.removeSubrange(path.index(after: i)..<path.endIndex)
} else {
path.append(node)
}
}
}
return result
}
}
extension Shape {
func breakLoop() -> [ShapeRegion.Solid] {
let bound = self.boundary
let reference = bound.width * bound.height
var solids: [ShapeRegion.Solid] = []
for var item in self {
if !item.start.almostEqual(item.end) {
item.append(.line(item.start))
}
var path: [ShapeRegion.Solid.Segment] = []
for segment in item.bezier {
switch segment.segment {
case let .cubic(p1, p2, p3):
if segment.start.almostEqual(p3, reference: reference) {
if let loop = ShapeRegion.Solid(segments: CollectionOfOne(segment), reference: reference) {
solids.append(loop)
}
} else {
var segment = segment
if let (_a, _b) = CubicBezier(segment.start, p1, p2, p3).selfIntersect() {
let a = Swift.min(_a, _b)
let b = Swift.max(_a, _b)
let check_1 = a.almostZero()
let check_2 = !check_1 && a > 0
let check_3 = b.almostEqual(1)
let check_4 = !check_3 && b < 1
if check_1 && check_4 {
let split = segment.split(b)
let (s, t) = split.0.split(0.5)
if let loop = ShapeRegion.Solid(segments: [s, t], reference: reference) {
solids.append(loop)
}
segment = split.1
} else if check_2 && check_3 {
let split = segment.split(a)
let (s, t) = split.1.split(0.5)
if let loop = ShapeRegion.Solid(segments: [s, t], reference: reference) {
solids.append(loop)
}
segment = split.0
} else if check_2 && check_4 {
let split = segment.split([a, b])
let (s, t) = split[1].split(0.5)
if let loop = ShapeRegion.Solid(segments: [s, t], reference: reference) {
solids.append(loop)
}
path.append(split[0])
segment = split[2]
}
}
path.append(segment)
}
default: path.append(segment)
}
}
if !path.isEmpty {
if let solid = ShapeRegion.Solid(segments: path, reference: reference) {
solids.append(solid)
}
}
}
return solids.flatMap { $0.solid._round_to_float().breakLoop(reference: reference) }.makeContiguousBuffer()
}
}
| mit | f40afee252e44349f040fffeb8b201d0 | 43.813953 | 148 | 0.461079 | 4.641509 | false | false | false | false |
SusanDoggie/Doggie | Sources/DoggieGeometry/Bezier/CubicBezierTriangularPatch.swift | 1 | 5308 | //
// CubicBezierTriangularPatch.swift
//
// The MIT License
// Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
@frozen
public struct CubicBezierTriangularPatch<Element: ScalarMultiplicative>: Equatable where Element.Scalar == Double {
public var m300: Element
public var m210: Element
public var m120: Element
public var m030: Element
public var m201: Element
public var m111: Element
public var m021: Element
public var m102: Element
public var m012: Element
public var m003: Element
@inlinable
@inline(__always)
public init(_ m300: Element, _ m210: Element, _ m120: Element, _ m030: Element,
_ m201: Element, _ m111: Element, _ m021: Element,
_ m102: Element, _ m012: Element,
_ m003: Element) {
self.m300 = m300
self.m210 = m210
self.m120 = m120
self.m030 = m030
self.m201 = m201
self.m111 = m111
self.m021 = m021
self.m102 = m102
self.m012 = m012
self.m003 = m003
}
}
extension CubicBezierTriangularPatch: Hashable where Element: Hashable {
}
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
extension CubicBezierTriangularPatch: Sendable where Element: Sendable { }
extension CubicBezierTriangularPatch {
@inlinable
@inline(__always)
public func eval(_ u: Double, _ v: Double) -> Element {
let w = 1 - u - v
let u2 = u * u
let u3 = u2 * u
let v2 = v * v
let v3 = v2 * v
let w2 = w * w
let w3 = w2 * w
let n300 = u3 * m300
let n030 = v3 * m030
let n003 = w3 * m003
let n210 = 3 * u2 * v * m210
let n201 = 3 * u2 * w * m201
let n120 = 3 * u * v2 * m120
let n021 = 3 * v2 * w * m021
let n012 = 3 * v * w2 * m012
let n102 = 3 * u * w2 * m102
let n111 = 6 * u * v * w * m111
return n300 + n030 + n003 + n210 + n201 + n120 + n021 + n012 + n102 + n111
}
}
extension CubicBezierTriangularPatch where Element == Vector {
@inlinable
@inline(__always)
public func normal(_ u: Double, _ v: Double) -> Element {
let w = 1 - u - v
let u2 = 3 * u * u
let v2 = 3 * v * v
let w2 = 3 * w * w
let uv = 6 * u * v
let uw = 6 * u * w
let vw = 6 * v * w
let s0 = u2 * (m300 - m201)
let s1 = v2 * (m120 - m021)
let s2 = w2 * (m102 - m003)
let s3 = uv * (m210 - m111)
let s4 = uw * (m201 - m102)
let s5 = vw * (m111 - m012)
let t0 = u2 * (m210 - m201)
let t1 = v2 * (m030 - m021)
let t2 = w2 * (m012 - m003)
let t3 = uv * (m120 - m111)
let t4 = uw * (m111 - m102)
let t5 = vw * (m021 - m012)
let s = s0 + s1 + s2 + s3 + s4 + s5
let t = t0 + t1 + t2 + t3 + t4 + t5
return cross(s, t)
}
}
@inlinable
@inline(__always)
public func * (lhs: CubicBezierTriangularPatch<Point>, rhs: SDTransform) -> CubicBezierTriangularPatch<Point> {
return CubicBezierTriangularPatch(lhs.m300 * rhs, lhs.m210 * rhs, lhs.m120 * rhs, lhs.m030 * rhs,
lhs.m201 * rhs, lhs.m111 * rhs, lhs.m021 * rhs,
lhs.m102 * rhs, lhs.m012 * rhs,
lhs.m003 * rhs)
}
@inlinable
@inline(__always)
public func *= (lhs: inout CubicBezierTriangularPatch<Point>, rhs: SDTransform) {
lhs = lhs * rhs
}
@inlinable
@inline(__always)
public func * (lhs: CubicBezierTriangularPatch<Vector>, rhs: Matrix) -> CubicBezierTriangularPatch<Vector> {
return CubicBezierTriangularPatch(lhs.m300 * rhs, lhs.m210 * rhs, lhs.m120 * rhs, lhs.m030 * rhs,
lhs.m201 * rhs, lhs.m111 * rhs, lhs.m021 * rhs,
lhs.m102 * rhs, lhs.m012 * rhs,
lhs.m003 * rhs)
}
@inlinable
@inline(__always)
public func *= (lhs: inout CubicBezierTriangularPatch<Vector>, rhs: Matrix) {
lhs = lhs * rhs
}
| mit | c373d18c9e5c64838580beb3d38ef394 | 32.808917 | 115 | 0.570836 | 3.560027 | false | false | false | false |
pankcuf/DataContext | DataContext/Classes/TableDataSectionContext.swift | 1 | 930 | //
// TableDataSectionContext.swift
// DataContext
//
// Created by Vladimir Pirogov on 17/10/16.
// Copyright © 2016 Vladimir Pirogov. All rights reserved.
//
import Foundation
open class TableDataSectionContext: DataContext {
open var headerContext:TableDataHeaderContext?
open var footerContext:TableDataHeaderContext?
open var rowContext:[TableDataCellContext]
public init(rowContext:[TableDataCellContext]) {
self.rowContext = rowContext
super.init()
}
public init(headerContext:TableDataHeaderContext?, rowContext:[TableDataCellContext]) {
self.rowContext = rowContext
super.init()
self.headerContext = headerContext
}
public init(headerContext:TableDataHeaderContext?, footerContext:TableDataHeaderContext?, rowContext:[TableDataCellContext]) {
self.rowContext = rowContext
super.init()
self.headerContext = headerContext
self.footerContext = footerContext
}
}
| mit | ff24db9bd7b83783bc066095f25b2786 | 21.119048 | 127 | 0.764263 | 3.953191 | false | false | false | false |
sora0077/Nata | NataTests/XPathFunctionResultTests.swift | 1 | 1773 | //
// XPathFunctionResultTests.swift
// Nata
//
// Created by 林達也 on 2015/12/31.
// Copyright © 2015年 jp.sora0077. All rights reserved.
//
import XCTest
import Nata
class XPathFunctionResultTests: XCTestCase {
private var document: XMLDocument!
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
let filePath = NSBundle(forClass: self.dynamicType).pathForResource("atom", ofType: "xml")
document = try? XMLDocument(data: NSData(contentsOfFile: filePath!)!)
document.definePrefix("atom", forDefaultNamespace: "http://www.w3.org/2005/Atom")
XCTAssertNotNil(document, "Document should not be nil")
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testFunctionResultBoolVaule() {
let XPath = "starts-with('Ono','O')"
let result = document.rootElement.functionResultByEvaluatingXPath(XPath)
XCTAssertEqual(result?.boolValue, true, "Result boolVaule should be true")
}
func testFunctionResultNumericValue() {
let XPath = "count(./atom:link)"
let result = document.rootElement.functionResultByEvaluatingXPath(XPath)
XCTAssertEqual(result?.numericValue, 2, "Number of child links should be 2")
}
func testFunctionResultStringVaule() {
let XPath = "string(./atom:entry[1]/dc:language[1]/text())"
let result = document.rootElement.functionResultByEvaluatingXPath(XPath)
XCTAssertEqual(result?.stringValue, "en-us", "Result stringValue should be `en-us`")
}
}
| mit | 86f1427f46e4a7ee2045e56e9bb971a3 | 35 | 111 | 0.676871 | 4.38806 | false | true | false | false |
huyphams/Spread | Spread/Tasks/OtherTask.swift | 1 | 968 | //
// OtherTask.swift
// Spread
//
// Created by Huy Pham on 4/15/15.
// Copyright (c) 2015 Katana. All rights reserved.
//
import UIKit
class OtherTask: SRemoteTask {
var objectId: String!
var nameSpace: String!
init(objectId: String, nameSpace: String) {
super.init()
self.objectId = objectId
self.nameSpace = nameSpace
}
override func getRequestParameters() -> [AnyHashable: Any] {
return ["type": "block"]
}
override func getRequestUrl() -> String {
return "www.google.com"
}
override func dequeue(_ executingTask: SRemoteTask) -> Bool {
let task = executingTask as! OtherTask
if self.objectId != task.objectId {
return true
}
return false
}
override func enqueue(_ penddingTask: SRemoteTask) -> Bool {
let task = penddingTask as! OtherTask
if self.objectId == task.objectId
&& self.nameSpace == task.nameSpace {
return false
}
return true
}
}
| mit | 6ee51d3e302d83498d8ff4ad29bfe119 | 20.043478 | 63 | 0.639463 | 3.811024 | false | false | false | false |
erikmartens/NearbyWeather | NearbyWeather/Routing/Weather Map Flow/WeatherMapFlow.swift | 1 | 7970 | //
// MapFlow.swift
// NearbyWeather
//
// Created by Erik Maximilian Martens on 19.04.20.
// Copyright © 2020 Erik Maximilian Martens. All rights reserved.
//
import RxSwift
import RxFlow
import Swinject
// MARK: - Dependencies
extension WeatherMapFlow {
struct Dependencies {
let dependencyContainer: Container
}
}
// MARK: - Class Definition
final class WeatherMapFlow: Flow {
// MARK: - Assets
var root: Presentable {
rootViewController
}
private lazy var rootViewController = Factory.NavigationController.make(fromType: .standardTabbed(
tabTitle: R.string.localizable.tab_weatherMap(),
systemImageName: "map.fill"
))
// MARK: - Properties
let dependencies: Dependencies
// MARK: - Initialization
init(dependencies: Dependencies) {
self.dependencies = dependencies
}
deinit {
printDebugMessage(
domain: String(describing: self),
message: "was deinitialized",
type: .info
)
}
// MARK: - Functions
func navigate(to step: Step) -> FlowContributors { // swiftlint:disable:this cyclomatic_complexity
guard let step = transform(step: step) as? WeatherMapStep else {
return .none
}
switch step {
case .map:
return summonWeatherMapController()
case let .weatherDetails2(identity):
return summonWeatherDetailsController2(identity: identity)
case .changeMapTypeAlert:
return .none // will be handled via `func adapt(step:)`
case let .changeMapTypeAlertAdapted(selectionDelegate, currentSelectedOptionValue):
return summonChangeMapTypeAlert(selectionDelegate: selectionDelegate, currentSelectedOptionValue: currentSelectedOptionValue)
case .changeAmountOfResultsAlert:
return .none // will be handled via `func adapt(step:)`
case let .changeAmountOfResultsAlertAdapted(selectionDelegate, currentSelectedOptionValue):
return summonChangeAmountOfResultsAlert(selectionDelegate: selectionDelegate, currentSelectedOptionValue: currentSelectedOptionValue)
case .focusOnLocationAlert:
return .none // will be handled via `func adapt(step:)`
case let .focusOnLocationAlertAdapted(selectionDelegate, weatherStationDTOs):
return summonFocusOnLocationAlert(selectionDelegate: selectionDelegate, bookmarkedLocations: weatherStationDTOs)
case .dismiss:
return dismissPresentedViewController()
case .pop:
return popPushedViewController()
}
}
func adapt(step: Step) -> Single<Step> {
guard let step = step as? WeatherMapStep else {
return .just(step)
}
switch step {
case let .changeMapTypeAlert(selectionDelegate):
return Observable
.combineLatest(
Observable.just(selectionDelegate),
dependencies.dependencyContainer.resolve(PreferencesService.self)!.createGetMapTypeOptionObservable().map { $0.value }.take(1),
resultSelector: WeatherMapStep.changeMapTypeAlertAdapted
)
.take(1)
.asSingle()
case let .changeAmountOfResultsAlert(selectionDelegate):
return Observable
.combineLatest(
Observable.just(selectionDelegate),
dependencies.dependencyContainer.resolve(PreferencesService.self)!.createGetAmountOfNearbyResultsOptionObservable().map { $0.value }.take(1),
resultSelector: WeatherMapStep.changeAmountOfResultsAlertAdapted
)
.take(1)
.asSingle()
case let .focusOnLocationAlert(selectionDelegate):
return Observable
.combineLatest(
Observable.just(selectionDelegate),
dependencies.dependencyContainer.resolve(WeatherStationService.self)!.createGetBookmarkedStationsObservable().take(1),
resultSelector: WeatherMapStep.focusOnLocationAlertAdapted
)
.take(1)
.asSingle()
default:
return .just(step)
}
}
private func transform(step: Step) -> Step? {
guard let weatherDetailStep = step as? WeatherStationMeteorologyDetailsStep else {
return step
}
switch weatherDetailStep {
case .weatherStationMeteorologyDetails:
return nil
case .end:
return WeatherMapStep.dismiss
}
}
}
// MARK: - Summoning Functions
private extension WeatherMapFlow {
func summonWeatherMapController() -> FlowContributors {
let weatherMapViewController = WeatherMapViewController(dependencies: WeatherMapViewController.ViewModel.Dependencies(
weatherInformationService: dependencies.dependencyContainer.resolve(WeatherInformationService.self)!,
weatherStationService: dependencies.dependencyContainer.resolve(WeatherStationService.self)!,
userLocationService: dependencies.dependencyContainer.resolve(UserLocationService.self)!,
preferencesService: dependencies.dependencyContainer.resolve(PreferencesService.self)!,
apiKeyService: dependencies.dependencyContainer.resolve(ApiKeyService.self)!
))
rootViewController.setViewControllers([weatherMapViewController], animated: false)
return .one(flowContributor: .contribute(
withNextPresentable: weatherMapViewController,
withNextStepper: weatherMapViewController.viewModel,
allowStepWhenNotPresented: true
))
}
func summonWeatherDetailsController2(identity: PersistencyModelIdentity) -> FlowContributors {
let weatherDetailFlow = WeatherStationMeteorologyDetailsFlow(dependencies: WeatherStationMeteorologyDetailsFlow.Dependencies(
flowPresentationStyle: .presented,
endingStep: WeatherMapStep.dismiss,
weatherInformationIdentity: identity,
dependencyContainer: dependencies.dependencyContainer
))
let weatherDetailStepper = WeatherStationMeteorologyDetailsStepper()
Flows.use(weatherDetailFlow, when: .ready) { [unowned rootViewController] (weatherDetailRoot: UINavigationController) in
weatherDetailRoot.viewControllers.first?.addCloseButton {
weatherDetailStepper.steps.accept(WeatherStationMeteorologyDetailsStep.end)
}
rootViewController.present(weatherDetailRoot, animated: true)
}
return .one(flowContributor: .contribute(withNextPresentable: weatherDetailFlow, withNextStepper: weatherDetailStepper))
}
func summonChangeMapTypeAlert(selectionDelegate: MapTypeSelectionAlertDelegate, currentSelectedOptionValue: MapTypeOptionValue) -> FlowContributors {
let alert = MapTypeSelectionAlert(dependencies: MapTypeSelectionAlert.Dependencies(
selectionDelegate: selectionDelegate,
selectedOptionValue: currentSelectedOptionValue
))
rootViewController.present(alert.alertController, animated: true, completion: nil)
return .none
}
func summonChangeAmountOfResultsAlert(selectionDelegate: AmountOfResultsSelectionAlertDelegate, currentSelectedOptionValue: AmountOfResultsOptionValue) -> FlowContributors {
let alert = AmountOfNearbyResultsSelectionAlert(dependencies: AmountOfNearbyResultsSelectionAlert.Dependencies(
selectionDelegate: selectionDelegate,
selectedOptionValue: currentSelectedOptionValue
))
rootViewController.present(alert.alertController, animated: true, completion: nil)
return .none
}
func summonFocusOnLocationAlert(selectionDelegate: FocusOnLocationSelectionAlertDelegate, bookmarkedLocations: [WeatherStationDTO]) -> FlowContributors {
let alert = FocusOnLocationSelectionAlert(dependencies: FocusOnLocationSelectionAlert.Dependencies(
bookmarkedLocations: bookmarkedLocations,
selectionDelegate: selectionDelegate
))
rootViewController.present(alert.alertController, animated: true, completion: nil)
return .none
}
func dismissPresentedViewController() -> FlowContributors {
rootViewController.presentedViewController?.dismiss(animated: true, completion: nil)
return .none
}
func popPushedViewController() -> FlowContributors {
rootViewController.popViewController(animated: true)
return .none
}
}
| mit | 0778da0f8243a27c4997df44c9f2c69d | 36.947619 | 175 | 0.752792 | 5.08227 | false | false | false | false |
wibosco/WhiteBoardCodingChallenges | WhiteBoardCodingChallengesTests/TheatreGuestsTests.swift | 1 | 1660 | //
// TheatreGuestsTests.swift
// WhiteBoardCodingChallenges
//
// Created by William Boles on 18/07/2016.
// Copyright © 2016 Boles. All rights reserved.
//
import XCTest
@testable import WhiteBoardCodingChallenges
class TheatreGuestsTests: XCTestCase {
// MARK: Tests
func test_sortA() {
var guestsInSeats = ["A", "B", "C", "D", "A", "B", "C", "D"]
let expectedGuestsInSeats = ["A", "A", "C", "C", "B", "B", "D", "D"]
TheatreGuests.sortGuestsInSeats(guestsInSeats: &guestsInSeats)
XCTAssertEqual(guestsInSeats, expectedGuestsInSeats)
}
// MARK: Alt
func test_sortAltA() {
var guestsInSeats = ["A", "B", "C", "D", "A", "B", "C", "D"]
let expectedGuestsInSeats = ["A", "A", "C", "C", "B", "B", "D", "D"]
TheatreGuests.sortGuestsInSeats(guestsInSeats: &guestsInSeats)
XCTAssertEqual(guestsInSeats, expectedGuestsInSeats)
}
func test_sortAltB() {
var guestsInSeats = ["A", "B", "D", "C", "D", "B", "C", "A"]
let expectedGuestsInSeats = ["A", "A", "D", "D", "C", "C", "B", "B"]
TheatreGuests.sortGuestsInSeats(guestsInSeats: &guestsInSeats)
XCTAssertEqual(guestsInSeats, expectedGuestsInSeats)
}
func test_sortAltC() {
var guestsInSeats = ["A", "B", "E", "D", "D", "B", "C", "A", "E", "C"]
let expectedGuestsInSeats = ["A", "A", "E", "E", "D", "D", "C", "C", "B", "B"]
TheatreGuests.sortGuestsInSeats(guestsInSeats: &guestsInSeats)
XCTAssertEqual(guestsInSeats, expectedGuestsInSeats)
}
}
| mit | 10d982ae9f212d52a522e416fae2cb14 | 29.722222 | 86 | 0.555154 | 3.278656 | false | true | false | false |
getaaron/SirenUpdateButton | SirenUpdateButton/SirenUpdateButton.swift | 1 | 2134 | //
// SirenUpdateButton.swift
// SirenUpdateButton
//
// Created by Aaron on 1/10/15.
// Copyright (c) 2015 Aaron Brager. All rights reserved.
//
import UIKit
class SirenUpdateHandler : SirenDelegate {
var updateAvailable = false
var updateDetected : () -> ()
var updateLocalizedString : String {
// TODO: Localize this
return "Update Available"
}
init(updateDetected : () -> ()) {
self.updateDetected = updateDetected
Siren.sharedInstance.delegate = self
Siren.sharedInstance.checkVersion(.Immediately)
}
func sirenDidDetectNewVersionWithoutAlert(message: String) {
self.updateAvailable = true
updateDetected()
}
func launchAppStore () {
//TODO: Make siren's launchAppStore() method public, and call it here
println("[SirenUpdateButton] App Store Launched")
}
}
class SirenUpdateButton : UIButton {
var updateHandler : SirenUpdateHandler!
override func intrinsicContentSize() -> CGSize {
if self.updateHandler.updateAvailable == false {
return CGSizeZero
} else {
return super.intrinsicContentSize()
}
}
override init() {
super.init()
commonInit()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func commonInit() {
userInteractionEnabled = false
self.setTitle("", forState: .Normal)
updateHandler = SirenUpdateHandler { () -> () in
self.userInteractionEnabled = true
self.setTitle(self.updateHandler.updateLocalizedString, forState: .Normal)
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.superview?.layoutIfNeeded()
return
})
}
addTarget(updateHandler, action: "launchAppStore", forControlEvents: .TouchUpInside)
}
}
class SirenUpdateBarButton : UIBarButtonItem {
let updateHandler = SirenUpdateHandler { () -> () in
}
}
| mit | 1c465dee5c04887efd5bed476f173859 | 25.02439 | 92 | 0.601687 | 5.243243 | false | false | false | false |
FengDeng/RxGitHubAPI | RxGitHubAPI/RxGitHubAPI/RxGitHubAPI.swift | 1 | 3208 | //
// RxGitHubAPI.swift
// RxGitHubAPI
//
// Created by 邓锋 on 16/1/27.
// Copyright © 2016年 fengdeng. All rights reserved.
//
import Foundation
import Alamofire
import RxSwift
class RxGitHubAPI{
/**
Get a single user
- parameter username: username description
- returns: Requestable<YYUser>
*/
static func yy_user(username:String)->Requestable<YYUser>{
return Requestable(mothod: .GET, url: kUserURL(username))
}
/**
Get the authenticated user
- parameter username: username description
- parameter password: password description
- returns: Requestable<YYUser>
*/
static var yy_user : Requestable<YYUser>{
return Requestable(mothod: .GET, url: kUserURL(RxGitHubUserName),headers:AuthHeader)
}
/**
search repos
- parameter q: The search keywords, as well as any qualifiers.
- parameter language: language
- parameter sort: The sort field. One of stars, forks, or updated. Default: results are sorted by best match.
- parameter order: The sort order if sort parameter is provided. One of asc or desc. Default: desc
- returns: return value description
*/
static func searchRepos(q:String,page:Int = 0,per_page:Int = 30,language:String? = nil,sort:String? = nil,order:String? = nil)->Requestable<YYSearchRepos>{
var query = q
if let language = language{
query = query + "+language:\(language)"
}
var dic = ["q":query]
dic.union(["page":"\(page)","per_page":"\(per_page)"])
if let sort = sort{
dic = dic.union(["sort":sort])
}
if let order = order {
dic = dic.union(["order":order])
}
return Requestable(mothod: .GET, url: kSearchReposURL,parameters:dic)
}
/**
search users
- parameter q: The search terms.
- parameter sort: The sort field. Can be followers, repositories, or joined. Default: results are sorted by best match.
- parameter order: The sort order if sort parameter is provided. One of asc or desc. Default: desc
- returns: return value description
*/
static func searchUsers(q:String,page:Int = 0,per_page:Int = 30,sort:String? = nil,order:String? = nil)->Requestable<YYSearchUsers>{
var dic = ["q":q]
dic.union(["page":"\(page)","per_page":"\(per_page)"])
if let sort = sort{
dic = dic.union(["sort":sort])
}
if let order = order {
dic = dic.union(["order":order])
}
return Requestable(mothod: .GET, url: kSearchUsersURL,parameters:dic)
}
/**
trending repos
- parameter since: since description
- parameter language: language description
- returns: return value description
*/
static func trendRepos(since:YYSince,language:String)->Pageable<[YYRepository]>{
return Pageable(mothod: .GET, url: kTrendRepoURL(since, language: language))
}
} | apache-2.0 | a957710c59def760dc9a2e1c6f9e17bf | 27.336283 | 159 | 0.584505 | 4.378933 | false | false | false | false |
zmian/xcore.swift | Tests/XcoreTests/CollectionTests.swift | 1 | 598 | //
// Xcore
// Copyright © 2019 Xcore
// MIT license, see LICENSE file for details
//
import XCTest
@testable import Xcore
final class CollectionTests: TestCase {
func testRemovingAll() {
var numbers = [5, 6, 7, 8, 9, 10, 11]
let removedNumbers = numbers.removingAll { $0 % 2 == 1 }
XCTAssertEqual(numbers, [6, 8, 10])
XCTAssertEqual(removedNumbers, [5, 7, 9, 11])
}
func testCount() {
let cast = ["Vivien", "Marlon", "Kim", "Karl"]
let shortNamesCount = cast.count { $0.count < 5 }
XCTAssertEqual(shortNamesCount, 2)
}
}
| mit | 08fc70bed512125b6a057b04ca1842b4 | 24.956522 | 64 | 0.599665 | 3.708075 | false | true | false | false |
karmicDev/DKExtensionsSwift | DKExtensions.swift | 1 | 7087 | //
// DKExtensions.swift
// Kevin Delord
//
// Created by kevin delord on 24/09/14.
// Copyright (c) 2015 Kevin Delord. All rights reserved.
//
import Foundation
import CoreTelephony
import StoreKit
// MARK: - Debug
func DKLog(verbose: Bool, obj: AnyObject) {
#if DEBUG
if (verbose == true) {
print(obj)
}
#else
// do nothing
#endif
}
// MARK: - Classes
class PopToRootViewControllerSegue : UIStoryboardSegue {
override func perform() {
self.sourceViewController.navigationController?.popToRootViewControllerAnimated(true)
}
}
class PopViewControllerSegue : UIStoryboardSegue {
override func perform() {
self.sourceViewController.navigationController?.popViewControllerAnimated(true)
}
}
extension SKProduct {
@available(*, deprecated=0.9, renamed="localizedPrice")
func localisedPrice() -> String? {
return self.localizedPrice()
}
func localizedPrice() -> String? {
let numberFormatter = NSNumberFormatter()
numberFormatter.formatterBehavior = NSNumberFormatterBehavior.BehaviorDefault
numberFormatter.numberStyle = .CurrencyStyle
numberFormatter.locale = self.priceLocale
return numberFormatter.stringFromNumber(self.price)
}
}
// MARK: - Additions
func += <KeyType, ValueType> (inout left: Dictionary<KeyType, ValueType>, right: Dictionary<KeyType, ValueType>) {
for (k, v) in right {
left.updateValue(v, forKey: k)
}
}
func + <K,V>(left: Dictionary<K,V>, right: Dictionary<K,V>) -> Dictionary<K,V> {
var map = Dictionary<K,V>()
for (k, v) in left {
map[k] = v
}
for (k, v) in right {
map[k] = v
}
return map
}
// MARK: - Extensions
extension NSDate {
func isOlderOrEqualThan(year: Int) -> Bool {
//
// Check if the selected date is older or equal to the given parameter.
let bdate = self.midnightDate()
let dateComponent = NSDateComponents()
dateComponent.year = -(year)
let veryOldDate = NSCalendar.currentCalendar().dateByAddingComponents(dateComponent, toDate: NSDate.currentDayDate(), options: NSCalendarOptions())
return (bdate.compare(veryOldDate!) != NSComparisonResult.OrderedDescending)
}
}
extension NSError {
func log() {
print("Error: \(self) \(self.userInfo)")
}
}
extension UIView {
func roundRect(radius radius: CGFloat) {
self.layer.cornerRadius = radius
self.layer.masksToBounds = true
}
/**
* Creates gradient view of given size with given colors
* This function already exist in the DKHelper, but does not work in Swift.
* The start point has to be -1.0 instead of 0.0 in Obj-C.
*/
class func gradientLayer(rect: CGRect, topColor: UIColor, bottomColor: UIColor) -> UIView {
let gradientLayerView: UIView = UIView(frame: rect)
let gradient: CAGradientLayer = CAGradientLayer()
gradient.frame = gradientLayerView.bounds
gradient.colors = [topColor.CGColor, bottomColor.CGColor]
gradient.startPoint = CGPointMake(0, -1.0)
gradient.endPoint = CGPointMake(0, 1.0)
gradientLayerView.layer.insertSublayer(gradient, atIndex: 0)
return gradientLayerView
}
}
extension UIAlertView {
class func showErrorPopup(error: NSError!) {
// log error
error.log()
// find a valid message to display
var msg = ""
if let errorMessage : String = error.userInfo["error"] as? String {
msg = errorMessage
} else if let errorMessage = error.localizedFailureReason {
msg = errorMessage
} else if (error.localizedDescription.characters.count > 0) {
msg = error.localizedDescription
}
// show a popup
self.showErrorMessage(msg)
}
class func showErrorMessage(message: String) {
UIAlertView(title: "Error", message: message, delegate: nil, cancelButtonTitle: nil, otherButtonTitles: "ok").show()
}
class func showInfoMessage(title: String, message: String) {
UIAlertView(title: title, message: message, delegate: nil, cancelButtonTitle: nil, otherButtonTitles: "ok").show()
}
}
extension String {
func isUserName() -> Bool {
let regex = "[äÄüÜöÖßA-Z0-9a-z_\\s-]+"
let predicate = NSPredicate(format: "SELF MATCHES %@", regex)
return predicate.evaluateWithObject(self)
}
}
extension Array where Element: Equatable {
mutating func removeObject(item: Element) {
if let index = self.indexOf(item) {
self.removeAtIndex(index)
}
}
mutating func shuffle() {
if (self.count < 2) {
return
}
for i in 0..<(self.count - 1) {
let j = Int(arc4random_uniform(UInt32(self.count - i))) + i
swap(&self[i], &self[j])
}
}
}
extension UIImagePickerControllerSourceType {
func nameType() -> String {
switch self {
case .PhotoLibrary:
return "PhotoLibrary"
case .Camera:
return "Camera"
case .SavedPhotosAlbum:
return "SavedPhotosAlbum"
}
}
}
extension UILabel {
//
// calculating, if size to fit would expand or shrink the label
// returns true if the label Size is smaller then before
// will not change the label' Size
//
func textFitsWidth() -> Bool {
let actualSize = self.frame.size
self.sizeToFit()
if self.frame.size.width > actualSize.width {
self.frame.size = actualSize
return false
}
self.frame.size = actualSize
return true
}
}
extension UIDevice {
//
// To check if the current Device has a SimCard or not, we will read the Carrier informations
// if there are no carrier Informations, there is no sim and this function will return false
//
// For more informations read Apple Doc's for CTCarrier's mobileCountryCode:
// From this Doc (https://developer.apple.com/library/ios/documentation/NetworkingInternet/Reference/CTCarrier/index.html#//apple_ref/occ/instp/CTCarrier/mobileCountryCode):
//
// The value for this property is nil if any of the following apply:
// - There is no SIM card in the device. [...]
//
func hasSimCard() -> Bool {
return (CTTelephonyNetworkInfo().subscriberCellularProvider?.mobileCountryCode != nil)
}
}
extension NSNumber {
//
// will return a String with the currency for the given Location
// can be used to display a Pricetag for an in App Product.
// take SKProduct.price for self
// and SKProduct.priceLocale for locae.
func stringWithCurrencyForNumber(locale:NSLocale) -> String? {
let formatter = NSNumberFormatter()
formatter.locale = locale
formatter.maximumFractionDigits = 2
formatter.minimumFractionDigits = 2
formatter.alwaysShowsDecimalSeparator = true
formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
return formatter.stringFromNumber(self)
}
}
| mit | 4c0e0af6b3cb28603439a566afeaf4a6 | 29.25641 | 177 | 0.650989 | 4.397516 | false | false | false | false |
PrajeetShrestha/ioshubgsheetwrite | ioshubSheets/AddDonorDataController.swift | 1 | 2726 | //
// ViewController.swift
// ioshubSheets
//
// Created by Eeposit1 on 8/12/16.
// Copyright © 2016 eeposit. All rights reserved.
//
import GoogleAPIClient
import GTMOAuth2
import UIKit
class AddDonorDataController: UIViewController {
private let service = GlobalGTLService.sharedInstance.service
private var name:String!
private var bloodGroup: String!
private var contactInfo:String!
private var email:String!
@IBOutlet var indicator: UIActivityIndicatorView!
@IBOutlet var tfName: UITextField!
@IBOutlet var tfBloodGroup: TextDrop1Column!
@IBOutlet var tfContact: UITextField!
@IBOutlet var tfEmail: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
tfBloodGroup.pickerDataArray = ["A+", "A-","B+","B-","O+","O-","AB+","AB-"]
}
@IBAction func send(sender: AnyObject) {
if self.tfName.text?.characters.count == 0 ||
self.tfEmail.text?.characters.count == 0 ||
self.tfContact.text?.characters.count == 0 ||
self.tfEmail.text?.characters.count == 0 {
showAlert("Incomplete Form", message: "Please fill all the form fields!", controller: self)
} else {
self.name = self.tfName.text
self.contactInfo = self.tfContact.text
self.bloodGroup = self.tfBloodGroup.text
self.email = self.tfEmail.text
self.postData()
}
}
func clearData() {
self.tfName.text = ""
self.tfEmail.text = ""
self.tfContact.text = ""
self.tfBloodGroup.text = ""
}
func postData() {
let range = "Sheet1!A1:D1"
let url = String(format:"%@/%@/values/%@:append", kBaseUrl, kSheetID, range)
let params = ["valueInputOption" :"USER_ENTERED"]
let gValue:NSMutableDictionary =
[
"values":
[
[self.name, self.bloodGroup, self.contactInfo, self.email]
]
]
let gtlObject = GTLObject(JSON: gValue)
let fullUrl = GTLUtilities.URLWithString(url, queryParameters: params)
self.indicator.startAnimating()
service.fetchObjectByInsertingObject(gtlObject, forURL: fullUrl) {
(ticket, gObj, error) in
self.indicator.stopAnimating()
if let error = error {
showAlert("Failure", message: error.localizedDescription, controller: self)
return
} else {
showAlert("Success", message: "Successfully added new record", controller: self)
}
}
}
}
| apache-2.0 | a6ec7b35c8e8fef73e3ad108e67f74a3 | 31.058824 | 103 | 0.577615 | 4.346093 | false | false | false | false |
lucaslt89/simpsonizados | simpsonizados/Pods/AlamofireImage/Source/ImageDownloader.swift | 3 | 23849 | // ImageDownloader.swift
//
// Copyright (c) 2015-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// 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 Alamofire
import Foundation
#if os(iOS) || os(tvOS) || os(watchOS)
import UIKit
#elseif os(OSX)
import Cocoa
#endif
/// The `RequestReceipt` is an object vended by the `ImageDownloader` when starting a download request. It can be used
/// to cancel active requests running on the `ImageDownloader` session. As a general rule, image download requests
/// should be cancelled using the `RequestReceipt` instead of calling `cancel` directly on the `request` itself. The
/// `ImageDownloader` is optimized to handle duplicate request scenarios as well as pending versus active downloads.
public class RequestReceipt {
/// The download request created by the `ImageDownloader`.
public let request: Request
/// The unique identifier for the image filters and completion handlers when duplicate requests are made.
public let receiptID: String
init(request: Request, receiptID: String) {
self.request = request
self.receiptID = receiptID
}
}
/// The `ImageDownloader` class is responsible for downloading images in parallel on a prioritized queue. Incoming
/// downloads are added to the front or back of the queue depending on the download prioritization. Each downloaded
/// image is cached in the underlying `NSURLCache` as well as the in-memory image cache that supports image filters.
/// By default, any download request with a cached image equivalent in the image cache will automatically be served the
/// cached image representation. Additional advanced features include supporting multiple image filters and completion
/// handlers for a single request.
public class ImageDownloader {
/// The completion handler closure used when an image download completes.
public typealias CompletionHandler = Response<Image, NSError> -> Void
/**
Defines the order prioritization of incoming download requests being inserted into the queue.
- FIFO: All incoming downloads are added to the back of the queue.
- LIFO: All incoming downloads are added to the front of the queue.
*/
public enum DownloadPrioritization {
case FIFO, LIFO
}
class ResponseHandler {
let identifier: String
let request: Request
var operations: [(id: String, filter: ImageFilter?, completion: CompletionHandler?)]
init(request: Request, id: String, filter: ImageFilter?, completion: CompletionHandler?) {
self.request = request
self.identifier = ImageDownloader.identifierForURLRequest(request.request!)
self.operations = [(id: id, filter: filter, completion: completion)]
}
}
// MARK: - Properties
/// The image cache used to store all downloaded images in.
public let imageCache: ImageRequestCache?
/// The credential used for authenticating each download request.
public private(set) var credential: NSURLCredential?
/// The underlying Alamofire `Manager` instance used to handle all download requests.
public let sessionManager: Alamofire.Manager
let downloadPrioritization: DownloadPrioritization
let maximumActiveDownloads: Int
var activeRequestCount = 0
var queuedRequests: [Request] = []
var responseHandlers: [String: ResponseHandler] = [:]
private let synchronizationQueue: dispatch_queue_t = {
let name = String(format: "com.alamofire.imagedownloader.synchronizationqueue-%08%08", arc4random(), arc4random())
return dispatch_queue_create(name, DISPATCH_QUEUE_SERIAL)
}()
private let responseQueue: dispatch_queue_t = {
let name = String(format: "com.alamofire.imagedownloader.responsequeue-%08%08", arc4random(), arc4random())
return dispatch_queue_create(name, DISPATCH_QUEUE_CONCURRENT)
}()
// MARK: - Initialization
/// The default instance of `ImageDownloader` initialized with default values.
public static let defaultInstance = ImageDownloader()
/**
Creates a default `NSURLSessionConfiguration` with common usage parameter values.
- returns: The default `NSURLSessionConfiguration` instance.
*/
public class func defaultURLSessionConfiguration() -> NSURLSessionConfiguration {
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeaders
configuration.HTTPShouldSetCookies = true
configuration.HTTPShouldUsePipelining = false
configuration.requestCachePolicy = .UseProtocolCachePolicy
configuration.allowsCellularAccess = true
configuration.timeoutIntervalForRequest = 60
configuration.URLCache = ImageDownloader.defaultURLCache()
return configuration
}
/**
Creates a default `NSURLCache` with common usage parameter values.
- returns: The default `NSURLCache` instance.
*/
public class func defaultURLCache() -> NSURLCache {
return NSURLCache(
memoryCapacity: 20 * 1024 * 1024, // 20 MB
diskCapacity: 150 * 1024 * 1024, // 150 MB
diskPath: "com.alamofire.imagedownloader"
)
}
/**
Initializes the `ImageDownloader` instance with the given configuration, download prioritization, maximum active
download count and image cache.
- parameter configuration: The `NSURLSessionConfiguration` to use to create the underlying Alamofire
`Manager` instance.
- parameter downloadPrioritization: The download prioritization of the download queue. `.FIFO` by default.
- parameter maximumActiveDownloads: The maximum number of active downloads allowed at any given time.
- parameter imageCache: The image cache used to store all downloaded images in.
- returns: The new `ImageDownloader` instance.
*/
public init(
configuration: NSURLSessionConfiguration = ImageDownloader.defaultURLSessionConfiguration(),
downloadPrioritization: DownloadPrioritization = .FIFO,
maximumActiveDownloads: Int = 4,
imageCache: ImageRequestCache? = AutoPurgingImageCache())
{
self.sessionManager = Alamofire.Manager(configuration: configuration)
self.sessionManager.startRequestsImmediately = false
self.downloadPrioritization = downloadPrioritization
self.maximumActiveDownloads = maximumActiveDownloads
self.imageCache = imageCache
}
/**
Initializes the `ImageDownloader` instance with the given sesion manager, download prioritization, maximum
active download count and image cache.
- parameter sessionManager: The Alamofire `Manager` instance to handle all download requests.
- parameter downloadPrioritization: The download prioritization of the download queue. `.FIFO` by default.
- parameter maximumActiveDownloads: The maximum number of active downloads allowed at any given time.
- parameter imageCache: The image cache used to store all downloaded images in.
- returns: The new `ImageDownloader` instance.
*/
public init(
sessionManager: Manager,
downloadPrioritization: DownloadPrioritization = .FIFO,
maximumActiveDownloads: Int = 4,
imageCache: ImageRequestCache? = AutoPurgingImageCache())
{
self.sessionManager = sessionManager
self.sessionManager.startRequestsImmediately = false
self.downloadPrioritization = downloadPrioritization
self.maximumActiveDownloads = maximumActiveDownloads
self.imageCache = imageCache
}
// MARK: - Authentication
/**
Associates an HTTP Basic Auth credential with all future download requests.
- parameter user: The user.
- parameter password: The password.
- parameter persistence: The URL credential persistence. `.ForSession` by default.
*/
public func addAuthentication(
user user: String,
password: String,
persistence: NSURLCredentialPersistence = .ForSession)
{
let credential = NSURLCredential(user: user, password: password, persistence: persistence)
addAuthentication(usingCredential: credential)
}
/**
Associates the specified credential with all future download requests.
- parameter credential: The credential.
*/
public func addAuthentication(usingCredential credential: NSURLCredential) {
dispatch_sync(synchronizationQueue) {
self.credential = credential
}
}
// MARK: - Download
/**
Creates a download request using the internal Alamofire `Manager` instance for the specified URL request.
If the same download request is already in the queue or currently being downloaded, the completion handler is
appended to the already existing request. Once the request completes, all completion handlers attached to the
request are executed in the order they were added.
- parameter URLRequest: The URL request.
- parameter completion: The closure called when the download request is complete.
- returns: The request receipt for the download request if available. `nil` if the image is stored in the image
cache and the URL request cache policy allows the cache to be used.
*/
public func downloadImage(
URLRequest URLRequest: URLRequestConvertible,
completion: CompletionHandler?)
-> RequestReceipt?
{
return downloadImage(
URLRequest: URLRequest,
receiptID: NSUUID().UUIDString,
filter: nil,
completion: completion
)
}
/**
Creates a download request using the internal Alamofire `Manager` instance for the specified URL request.
If the same download request is already in the queue or currently being downloaded, the filter and completion
handler are appended to the already existing request. Once the request completes, all filters and completion
handlers attached to the request are executed in the order they were added. Additionally, any filters attached
to the request with the same identifiers are only executed once. The resulting image is then passed into each
completion handler paired with the filter.
You should not attempt to directly cancel the `request` inside the request receipt since other callers may be
relying on the completion of that request. Instead, you should call `cancelRequestForRequestReceipt` with the
returned request receipt to allow the `ImageDownloader` to optimize the cancellation on behalf of all active
callers.
- parameter URLRequest: The URL request.
- parameter filter The image filter to apply to the image after the download is complete.
- parameter completion: The closure called when the download request is complete.
- returns: The request receipt for the download request if available. `nil` if the image is stored in the image
cache and the URL request cache policy allows the cache to be used.
*/
public func downloadImage(
URLRequest URLRequest: URLRequestConvertible,
filter: ImageFilter?,
completion: CompletionHandler?)
-> RequestReceipt?
{
return downloadImage(
URLRequest: URLRequest,
receiptID: NSUUID().UUIDString,
filter: filter,
completion: completion
)
}
func downloadImage(
URLRequest URLRequest: URLRequestConvertible,
receiptID: String,
filter: ImageFilter?,
completion: CompletionHandler?)
-> RequestReceipt?
{
var request: Request!
dispatch_sync(synchronizationQueue) {
// 1) Append the filter and completion handler to a pre-existing request if it already exists
let identifier = ImageDownloader.identifierForURLRequest(URLRequest)
if let responseHandler = self.responseHandlers[identifier] {
responseHandler.operations.append(id: receiptID, filter: filter, completion: completion)
request = responseHandler.request
return
}
// 2) Attempt to load the image from the image cache if the cache policy allows it
switch URLRequest.URLRequest.cachePolicy {
case .UseProtocolCachePolicy, .ReturnCacheDataElseLoad, .ReturnCacheDataDontLoad:
if let image = self.imageCache?.imageForRequest(
URLRequest.URLRequest,
withAdditionalIdentifier: filter?.identifier)
{
dispatch_async(dispatch_get_main_queue()) {
let response = Response<Image, NSError>(
request: URLRequest.URLRequest,
response: nil,
data: nil,
result: .Success(image)
)
completion?(response)
}
return
}
default:
break
}
// 3) Create the request and set up authentication, validation and response serialization
request = self.sessionManager.request(URLRequest)
if let credential = self.credential {
request.authenticate(usingCredential: credential)
}
request.validate()
request.response(
queue: self.responseQueue,
responseSerializer: Request.imageResponseSerializer(),
completionHandler: { [weak self] response in
guard let strongSelf = self, let request = response.request else { return }
let responseHandler = strongSelf.safelyRemoveResponseHandlerWithIdentifier(identifier)
switch response.result {
case .Success(let image):
var filteredImages: [String: Image] = [:]
for (_, filter, completion) in responseHandler.operations {
var filteredImage: Image
if let filter = filter {
if let alreadyFilteredImage = filteredImages[filter.identifier] {
filteredImage = alreadyFilteredImage
} else {
filteredImage = filter.filter(image)
filteredImages[filter.identifier] = filteredImage
}
} else {
filteredImage = image
}
strongSelf.imageCache?.addImage(
filteredImage,
forRequest: request,
withAdditionalIdentifier: filter?.identifier
)
dispatch_async(dispatch_get_main_queue()) {
let response = Response<Image, NSError>(
request: response.request,
response: response.response,
data: response.data,
result: .Success(filteredImage)
)
completion?(response)
}
}
case .Failure:
for (_, _, completion) in responseHandler.operations {
dispatch_async(dispatch_get_main_queue()) { completion?(response) }
}
}
strongSelf.safelyDecrementActiveRequestCount()
strongSelf.safelyStartNextRequestIfNecessary()
}
)
// 4) Store the response handler for use when the request completes
let responseHandler = ResponseHandler(
request: request,
id: receiptID,
filter: filter,
completion: completion
)
self.responseHandlers[identifier] = responseHandler
// 5) Either start the request or enqueue it depending on the current active request count
if self.isActiveRequestCountBelowMaximumLimit() {
self.startRequest(request)
} else {
self.enqueueRequest(request)
}
}
if let request = request {
return RequestReceipt(request: request, receiptID: receiptID)
}
return nil
}
/**
Creates a download request using the internal Alamofire `Manager` instance for each specified URL request.
For each request, if the same download request is already in the queue or currently being downloaded, the
filter and completion handler are appended to the already existing request. Once the request completes, all
filters and completion handlers attached to the request are executed in the order they were added.
Additionally, any filters attached to the request with the same identifiers are only executed once. The
resulting image is then passed into each completion handler paired with the filter.
You should not attempt to directly cancel any of the `request`s inside the request receipts array since other
callers may be relying on the completion of that request. Instead, you should call
`cancelRequestForRequestReceipt` with the returned request receipt to allow the `ImageDownloader` to optimize
the cancellation on behalf of all active callers.
- parameter URLRequests: The URL requests.
- parameter filter The image filter to apply to the image after each download is complete.
- parameter completion: The closure called when each download request is complete.
- returns: The request receipts for the download requests if available. If an image is stored in the image
cache and the URL request cache policy allows the cache to be used, a receipt will not be returned
for that request.
*/
public func downloadImages(
URLRequests URLRequests: [URLRequestConvertible],
filter: ImageFilter? = nil,
completion: CompletionHandler? = nil)
-> [RequestReceipt]
{
return URLRequests.flatMap { downloadImage(URLRequest: $0, filter: filter, completion: completion) }
}
/**
Cancels the request in the receipt by removing the response handler and cancelling the request if necessary.
If the request is pending in the queue, it will be cancelled if no other response handlers are registered with
the request. If the request is currently executing or is already completed, the response handler is removed and
will not be called.
- parameter requestReceipt: The request receipt to cancel.
*/
public func cancelRequestForRequestReceipt(requestReceipt: RequestReceipt) {
dispatch_sync(synchronizationQueue) {
let identifier = ImageDownloader.identifierForURLRequest(requestReceipt.request.request!)
guard let responseHandler = self.responseHandlers[identifier] else { return }
if let index = responseHandler.operations.indexOf({ $0.id == requestReceipt.receiptID }) {
let operation = responseHandler.operations.removeAtIndex(index)
let response: Response<Image, NSError> = {
let URLRequest = requestReceipt.request.request!
let error: NSError = {
let failureReason = "ImageDownloader cancelled URL request: \(URLRequest.URLString)"
let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason]
return NSError(domain: Error.Domain, code: NSURLErrorCancelled, userInfo: userInfo)
}()
return Response(request: URLRequest, response: nil, data: nil, result: .Failure(error))
}()
dispatch_async(dispatch_get_main_queue()) { operation.completion?(response) }
}
if responseHandler.operations.isEmpty && requestReceipt.request.task.state == .Suspended {
requestReceipt.request.cancel()
}
}
}
// MARK: - Internal - Thread-Safe Request Methods
func safelyRemoveResponseHandlerWithIdentifier(identifier: String) -> ResponseHandler {
var responseHandler: ResponseHandler!
dispatch_sync(synchronizationQueue) {
responseHandler = self.responseHandlers.removeValueForKey(identifier)
}
return responseHandler
}
func safelyStartNextRequestIfNecessary() {
dispatch_sync(synchronizationQueue) {
guard self.isActiveRequestCountBelowMaximumLimit() else { return }
while (!self.queuedRequests.isEmpty) {
if let request = self.dequeueRequest() where request.task.state == .Suspended {
self.startRequest(request)
break
}
}
}
}
func safelyDecrementActiveRequestCount() {
dispatch_sync(self.synchronizationQueue) {
if self.activeRequestCount > 0 {
self.activeRequestCount -= 1
}
}
}
// MARK: - Internal - Non Thread-Safe Request Methods
func startRequest(request: Request) {
request.resume()
++activeRequestCount
}
func enqueueRequest(request: Request) {
switch downloadPrioritization {
case .FIFO:
queuedRequests.append(request)
case .LIFO:
queuedRequests.insert(request, atIndex: 0)
}
}
func dequeueRequest() -> Request? {
var request: Request?
if !queuedRequests.isEmpty {
request = queuedRequests.removeFirst()
}
return request
}
func isActiveRequestCountBelowMaximumLimit() -> Bool {
return activeRequestCount < maximumActiveDownloads
}
static func identifierForURLRequest(URLRequest: URLRequestConvertible) -> String {
return URLRequest.URLRequest.URLString
}
}
| mit | 7fb632b0b1006645363f2cd693a1f4bf | 41.971171 | 122 | 0.645268 | 6.042311 | false | false | false | false |
rshevchuk/Wallet | Example/Pods/DynamicColor/Sources/DynamicColor+Lab.swift | 1 | 3495 | /*
* DynamicColor
*
* Copyright 2015-present Yannick Loriot.
* http://yannickloriot.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#if os(iOS) || os(tvOS) || os(watchOS)
import UIKit
#elseif os(OSX)
import AppKit
#endif
// MARK: CIE L*a*b* Color Space
public extension DynamicColor {
/**
Initializes and returns a color object using CIE XYZ color space component values with an observer at 2° and a D65 illuminant.
Notes that values out of range are clipped.
- parameter L: The lightness, specified as a value from 0 to 100.0.
- parameter a: The red-green axis, specified as a value from -128.0 to 127.0.
- parameter b: The yellow-blue axis, specified as a value from -128.0 to 127.0.
- parameter alpha: The opacity value of the color object, specified as a value from 0.0 to 1.0. Default to 1.0.
*/
convenience init(L: CGFloat, a: CGFloat, b: CGFloat, alpha: CGFloat = 1) {
let clippedL = clip(L, 0, 100)
let clippedA = clip(a, -128, 127)
let clippedB = clip(b, -128, 127)
let normalized = { (c: CGFloat) -> CGFloat in
pow(c, 3) > 0.008856 ? pow(c, 3) : (c - 16 / 116) / 7.787
}
let preY = (clippedL + 16) / 116
let preX = clippedA / 500 + preY
let preZ = preY - clippedB / 200
let X = 95.05 * normalized(preX)
let Y = 100 * normalized(preY)
let Z = 108.9 * normalized(preZ)
self.init(X: X, Y: Y, Z: Z, alpha: alpha)
}
// MARK: - Getting the L*a*b* Components
/**
Returns the Lab (lightness, red-green axis, yellow-blue axis) components.
It is based on the CIE XYZ color space with an observer at 2° and a D65 illuminant.
Notes that L values are between 0 to 100.0, a values are between -128 to 127.0 and b values are between -128 to 127.0.
- returns: The L*a*b* components as a tuple (L, a, b).
*/
final func toLabComponents() -> (L: CGFloat, a: CGFloat, b: CGFloat) {
let normalized = { (c: CGFloat) -> CGFloat in
c > 0.008856 ? pow(c, 1.0 / 3) : 7.787 * c + 16.0 / 116
}
let xyz = toXYZComponents()
let normalizedX = normalized(xyz.X / 95.05)
let normalizedY = normalized(xyz.Y / 100)
let normalizedZ = normalized(xyz.Z / 108.9)
let L = roundDecimal(116 * normalizedY - 16, precision: 1000)
let a = roundDecimal(500 * (normalizedX - normalizedY), precision: 1000)
let b = roundDecimal(200 * (normalizedY - normalizedZ), precision: 1000)
return (L: L, a: a, b: b)
}
}
| mit | 439ae5fda2794909c006cdb5c98d5d3b | 36.967391 | 129 | 0.677355 | 3.593621 | false | false | false | false |
matoushybl/iKGK-ios | iKGK/MainButton.swift | 1 | 1845 | //
// MainButton.swift
// iKGK
//
// Created by Matouš Hýbl on 17/04/15.
// Copyright (c) 2015 KGK. All rights reserved.
//
import UIKit
import SwiftKit
@objc(MainButton)
class MainButton: UIView {
private var imageView: UIImageView!
private var label: UILabel!
private var overlayButton: UIButton!
private var separator: UIView!
var title: String! {
didSet {
label.text = title
}
}
var onClick: Event<UIControl, UIEvent> {
return overlayButton.touchUpInside
}
required convenience init(coder aDecoder: NSCoder) {
self.init(frame: CGRectZero)
}
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
private func setupViews() {
imageView => self
label => self
separator => self
overlayButton => self
// Wow. very name. such originality
imageView.image = UIImage(named: "Image")
setNeedsUpdateConstraints()
}
override func updateConstraints() {
super.updateConstraints()
label.snp_remakeConstraints { make in
make.height.equalTo(self)
make.leading.equalTo(self).offset(20)
make.centerY.equalTo(self)
}
imageView.snp_remakeConstraints { make in
make.centerY.equalTo(self)
make.trailing.equalTo(self).offset(-10)
make.height.equalTo(20)
make.width.equalTo(20)
}
overlayButton.snp_remakeConstraints { make in
make.edges.equalTo(self)
}
separator.snp_remakeConstraints { make in
make.top.equalTo(self.snp_bottom).offset(-1)
make.leading.trailing.equalTo(self)
make.height.equalTo(1)
}
}
}
| mit | b45d534c11cd5a1fe6cdc353bec15287 | 24.246575 | 56 | 0.582746 | 4.473301 | false | false | false | false |
Pacific3/PNetworkKit | PNetworkKit/Operations/Generics/DownloadJSONByPollingOperation.swift | 1 | 4057 |
public class DownloadJSONByPollingOperation<T: Pollable, P: DownloadJSONOperation where P: Clonable>: GroupOperation {
// MARK: - Private Properties
private var hasProducedAlert = false
private var pollToURL: NSURL?
private var pollState: PollStatusProtocol
private var model: T?
// MARK: - Public Properties
public var initialDownloadOperation: DownloadJSONOperation
public var pollingDownloadOperation: P
public var parsedJSON: T?
public var completionHandler: (T -> Void)?
public var errorHandler: (NSError -> Void)?
// MARK: - Public Initialisers
public init(
initialDownload: DownloadJSONOperation,
pollOperation: P,
completion: (T -> Void)? = nil,
error: (NSError -> Void)? = nil,
initialPollState: PollStatusProtocol
) {
completionHandler = completion
errorHandler = error
pollState = initialPollState
initialDownloadOperation = initialDownload
pollingDownloadOperation = pollOperation
super.init(operations: nil)
name = "\(self.dynamicType)"
addSubOperations()
}
// WARNING: Something crashes after the response is delivered back to the caller
// MARK: - Overrides
public override func finish(errors: [NSError]) {
if pollState.hasFinished() {
if let _m = model {
parsedJSON = _m
completionHandler?(_m)
}
super.finish(errors)
} else {
internalQueue.suspended = false
}
}
public override func operationDidFinish(
operation: NSOperation,
withErrors errors: [NSError]
) {
let initial = initialDownloadOperation
let polling = pollingDownloadOperation
if let firstError = errors.first where (operation.name == initial.name || operation.name == polling.name) {
produceAlert(
firstError,
hasProducedAlert: &hasProducedAlert) { generatedOperation in
self.produceOperation(generatedOperation)
}
finish([firstError])
return
}
if let operation = operation as? DownloadJSONOperation where (operation.name == pollingDownloadOperation.name || operation.name == initialDownloadOperation.name) {
guard
let json = operation.downloadedJSON,
result = json["result"] as? [String:AnyObject]
else {
return
}
model = T.withData(result)
guard let _m = model else {
return
}
pollState = _m.state
if pollState.isPending() {
pollToURL = NSURL(string: _m.poll_to)
self.addSubOperations()
}
else if pollState.hasFinished() {
finish(errors)
}
}
}
}
// MARK: - Private Methods
extension DownloadJSONByPollingOperation {
private func addSubOperations() {
let completion = NSBlockOperation(block: {})
completion.name = "Completion Block"
var _do: DownloadJSONOperation?
if !pollState.hasStarted() {
_do = initialDownloadOperation
}
else if pollState.isPending() {
guard let clone = pollingDownloadOperation.clone() else {
return
}
_do = clone
_do?.url = pollToURL
}
guard let op = _do else {
return
}
completion.addDependency(op)
addOperations([op, completion])
}
} | mit | 79a517199e0625a6b404b3860fa05f93 | 30.703125 | 175 | 0.52354 | 5.738331 | false | false | false | false |
stripe/stripe-ios | StripePaymentSheet/StripePaymentSheet/PaymentSheet/Views/CircularButton.swift | 1 | 4698 | //
// CircularButton.swift
// StripePaymentSheet
//
// Created by Cameron Sabol on 2/17/21.
// Copyright © 2021 Stripe, Inc. All rights reserved.
//
import UIKit
@_spi(STP) import StripeCore
@_spi(STP) import StripeUICore
/// For internal SDK use only
@objc(STP_Internal_CircularButton)
class CircularButton: UIControl {
private let radius: CGFloat = 10
private let shadowOpacity: Float = 0.5
private let style: Style
var iconColor: UIColor {
didSet {
updateColor()
}
}
private lazy var imageView = UIImageView()
override var isEnabled: Bool {
didSet {
updateColor()
}
}
enum Style {
case back
case close
case remove
}
required init(style: Style, iconColor: UIColor = .secondaryLabel, dangerColor: UIColor = .systemRed) {
self.style = style
self.iconColor = iconColor
super.init(frame: .zero)
backgroundColor = UIColor.dynamic(
light: .systemBackground, dark: .systemGray2)
layer.cornerRadius = radius
layer.masksToBounds = false
isAccessibilityElement = true
accessibilityTraits = [.button]
layer.shadowOffset = CGSize(width: 0, height: 1)
layer.shadowRadius = 1.5
layer.shadowColor = UIColor.systemGray2.cgColor
layer.shadowOpacity = shadowOpacity
let path = UIBezierPath(
arcCenter: CGPoint(x: radius, y: radius), radius: radius,
startAngle: 0,
endAngle: CGFloat.pi * 2,
clockwise: true)
layer.shadowPath = path.cgPath
addSubview(imageView)
switch style {
case .back:
imageView.image = Image.icon_chevron_left.makeImage(template: true)
accessibilityLabel = String.Localized.back
accessibilityIdentifier = "CircularButton.Back"
case .close:
imageView.image = Image.icon_x.makeImage(template: true)
if style == .remove {
imageView.tintColor = dangerColor
}
accessibilityLabel = String.Localized.close
accessibilityIdentifier = "CircularButton.Close"
case .remove:
backgroundColor = UIColor.dynamic(
light: .systemBackground,
dark: UIColor(red: 43.0 / 255.0, green: 43.0 / 255.0, blue: 47.0 / 255.0, alpha: 1))
imageView.image = Image.icon_x.makeImage(template: true)
imageView.tintColor = dangerColor
accessibilityLabel = String.Localized.remove
accessibilityIdentifier = "CircularButton.Remove"
}
imageView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
imageView.centerXAnchor.constraint(
equalTo: centerXAnchor, constant: style == .back ? -0.5 : 0),
imageView.centerYAnchor.constraint(equalTo: centerYAnchor),
])
updateShadow()
updateColor()
}
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
let newArea = bounds.insetBy(
dx: -(PaymentSheetUI.minimumTapSize.width - bounds.width) / 2,
dy: -(PaymentSheetUI.minimumTapSize.height - bounds.height) / 2)
return newArea.contains(point)
}
func handleEvent(_ event: STPEvent) {
switch event {
case .shouldEnableUserInteraction:
backgroundColor = .systemGray2
case .shouldDisableUserInteraction:
backgroundColor = .systemIndigo
}
}
func updateShadow() {
// Turn off shadows in dark mode
if traitCollection.userInterfaceStyle == .dark {
layer.shadowOpacity = 0
} else {
layer.shadowOpacity = shadowOpacity
}
}
private func updateColor() {
imageView.tintColor = isEnabled ? iconColor : .tertiaryLabel
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
updateShadow()
if style == .remove {
if traitCollection.userInterfaceStyle == .dark {
layer.borderWidth = 1
layer.borderColor = UIColor.systemGray2.withAlphaComponent(0.3).cgColor
} else {
layer.borderWidth = 0
layer.borderColor = nil
}
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var intrinsicContentSize: CGSize {
return CGSize(width: radius * 2, height: radius * 2)
}
}
| mit | 9443a8ace9abdb90f3c4dcd77a3af77a | 31.393103 | 106 | 0.608686 | 5.066882 | false | false | false | false |
sauvikatinnofied/SwiftAutolayout | Autolayout/Autolayout/ViewController.swift | 1 | 1758 | //
// ViewController.swift
// Autolayout
//
// Created by Sauvik Dolui on 24/03/17.
// Copyright © 2017 Sauvik Dolui. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
drawMyCountryFlag()
}
func drawMyCountryFlag() {
view.backgroundColor = .black
let centerView = UIView.autolayoutView()
view.addSubview(centerView)
centerView._layoutInSuper(percentage: 90.0)
let orangeView = UIView.autolayoutView()
orangeView.backgroundColor = .orange
centerView.addSubview(orangeView)
let whiteView = UIView.autolayoutView()
whiteView.backgroundColor = .white
centerView.addSubview(whiteView)
let greenView = UIView.autolayoutView()
greenView.backgroundColor = .green
centerView.addSubview(greenView)
orangeView._setWidth(sidePadding: 0.0) // Width, X set
orangeView._setHeight(height: 50.0) // Height Set
orangeView._setTop(topPadding: 50) // Top Padding
// Adding the white view
whiteView._setSizeEqualTo(view: orangeView) // Size Fixed
whiteView._setLeftAlignWith(view: orangeView) // X Set
whiteView._setTopFromBottomEdgeOf(view: orangeView, offset: 3.0) // Y Set
// Adding the green view
greenView._setSizeEqualTo(view: orangeView) // Size Fixed
greenView._setLeftAlignWith(view: orangeView) // X Set
greenView._setTopFromBottomEdgeOf(view: whiteView, offset: 3.0) // Y Set
}
}
| mit | 305d9304c6d63234ef6c82a098036802 | 28.779661 | 81 | 0.622083 | 4.774457 | false | false | false | false |
NoryCao/zhuishushenqi | zhuishushenqi/NewVersion/Mine/ZSRegularVerifyViewController.swift | 1 | 6050 | //
// ZSRegularVerifyViewController.swift
// zhuishushenqi
//
// Created by yung on 2020/12/18.
// Copyright © 2020 QS. All rights reserved.
//
import UIKit
import SnapKit
class ZSRegularVerifyViewController: BaseViewController {
private let htmlTextPlaceHolder = "请输入html文本"
private let resultTextPlaceHolder = "测试结果:"
override func viewDidLoad() {
super.viewDidLoad()
title = "规则验证"
view.addSubview(typeSelect)
view.addSubview(htmlTextTV)
view.addSubview(regularTF)
view.addSubview(parseBT)
view.addSubview(resultLabel)
typeSelect.snp.makeConstraints { (make) in
make.left.equalToSuperview().offset(20)
make.right.equalToSuperview().offset(-20)
make.height.equalTo(40)
make.top.equalToSuperview().offset(kNavgationBarHeight + 20)
}
htmlTextTV.snp.makeConstraints { [unowned self] (make) in
make.top.equalTo(self.typeSelect.snp_bottomMargin).offset(20)
make.left.equalToSuperview().offset(20)
make.right.equalToSuperview().offset(-20)
make.height.equalTo(200)
}
regularTF.snp.makeConstraints { [unowned self] (make) in
make.top.equalTo(self.htmlTextTV.snp_bottomMargin).offset(20)
make.left.equalToSuperview().offset(20)
make.right.equalToSuperview().offset(-20)
make.height.equalTo(44)
}
parseBT.snp.makeConstraints { [unowned self](make) in
make.top.equalTo(self.regularTF.snp_bottomMargin).offset(20)
make.left.equalToSuperview().offset(20)
make.right.equalToSuperview().offset(-20)
make.height.equalTo(44)
}
resultLabel.snp.makeConstraints { [unowned self](make) in
make.top.equalTo(self.parseBT.snp_bottomMargin).offset(20)
make.left.equalToSuperview().offset(20)
make.right.equalToSuperview().offset(-20)
make.height.equalTo(200)
}
htmlTextTV.text = htmlTextPlaceHolder
resultLabel.loadHTMLString(resultTextPlaceHolder, baseURL: nil)
}
@objc
private func parseAction(btn:UIButton) {
let htmlText = htmlTextTV.text ?? ""
let regularText = regularTF.text ?? ""
let typeSelectedIndex = typeSelect.selectedSegmentIndex
if let document = OCGumboDocument(htmlString: htmlText) {
let parse = AikanHtmlParser()
switch typeSelectedIndex {
case 0:
let elements = parse.elementArray(with: document, withRegexString: regularText)
var resultText = ""
elements.enumerateObjects { (node, idx, stop) in
guard let element = node as? OCGumboNode else { return }
resultText.append("\(element.html() ?? "")<br/>")
}
// let htmlData = NSString(string: resultText).data(using: String.Encoding.unicode.rawValue)
// let options = [NSAttributedString.DocumentReadingOptionKey.documentType:
// NSAttributedString.DocumentType.html]
// let attributedString = try? NSMutableAttributedString(data: htmlData ?? Data(),
// options: options,
// documentAttributes: nil)
resultLabel.loadHTMLString(resultText, baseURL: nil)
break
case 1:
let objs = parse.string(withGumboNode: document, withAikanString: regularText, withText: true)
resultLabel.loadHTMLString("\(objs)", baseURL: nil)
break
case 2:
let attr = ZSReaderDownloader.share.contentReplace(string: htmlText, reg: regularText)
resultLabel.loadHTMLString("\(attr)", baseURL: nil)
break
default:
break
}
}
}
// MARK: - lazy
lazy var typeSelect: UISegmentedControl = {
let seg = UISegmentedControl(items: ["array", "string", "contentReplace"])
seg.tintColor = UIColor.red
if #available(iOS 13.0, *) {
seg.selectedSegmentTintColor = UIColor.white
} else {
// Fallback on earlier versions
}
seg.selectedSegmentIndex = 1
return seg
}()
lazy var htmlTextTV: UITextView = {
let tv = UITextView()
tv.font = UIFont.systemFont(ofSize: 13)
tv.textColor = UIColor.gray
tv.layer.cornerRadius = 5
tv.layer.masksToBounds = true
tv.delegate = self
return tv
}()
lazy var regularTF: UITextField = {
let tf = UITextField()
tf.placeholder = "请输入规则"
tf.backgroundColor = UIColor.white
tf.layer.cornerRadius = 5
tf.layer.masksToBounds = true
return tf
}()
lazy var parseBT: UIButton = {
let bt = UIButton(type: .custom)
bt.setTitle("开始测试", for: .normal)
bt.setTitleColor(UIColor.white, for: .normal)
bt.backgroundColor = UIColor.red
bt.layer.cornerRadius = 5
bt.layer.masksToBounds = true
bt.addTarget(self, action: #selector(parseAction(btn:)), for: .touchUpInside)
return bt
}()
lazy var resultLabel: UIWebView = {
let lb = UIWebView()
lb.layer.cornerRadius = 5
lb.layer.masksToBounds = true
return lb
}()
}
extension ZSRegularVerifyViewController:UITextViewDelegate {
func textViewShouldEndEditing(_ textView: UITextView) -> Bool {
if textView.text.count == 0 {
htmlTextTV.text = htmlTextPlaceHolder
}
return true
}
func textViewDidBeginEditing(_ textView: UITextView) {
if textView.text == htmlTextPlaceHolder {
textView.text = ""
}
}
}
| mit | 0f329011a419b42971e028848c684e10 | 35.381818 | 110 | 0.586707 | 4.85287 | false | false | false | false |
timrwood/SVGPath | SVGPathTests/QuadCurveToTests.swift | 1 | 5096 | //
// QuadCurveToTests.swift
// SVGPath
//
// Created by Tim Wood on 1/23/15.
// Copyright (c) 2015 Tim Wood. All rights reserved.
//
import XCTest
import SVGPath
class QuadCurveToTests: XCTestCase {
func testSingleAbsoluteCurveTo() {
let actual:[SVGCommand] = SVGPath("Q1 2 3 4").commands
let expect:[SVGCommand] = [
SVGCommand(1.0, 2.0, 3.0, 4.0)
]
assertCommandsEqual(actual, expect)
}
func testMultipleAbsoluteCurveTo() {
let actual:[SVGCommand] = SVGPath("Q1 2 3 4 5 6 7 8Q1 2 3 4").commands
let expect:[SVGCommand] = [
SVGCommand(1.0, 2.0, 3.0, 4.0),
SVGCommand(5.0, 6.0, 7.0, 8.0),
SVGCommand(1.0, 2.0, 3.0, 4.0)
]
assertCommandsEqual(actual, expect)
}
func testSingleRelativeCurveTo() {
let actual:[SVGCommand] = SVGPath("M8 6q1 2 3 4").commands
let expect:[SVGCommand] = [
SVGCommand(8.0, 6.0, type: .move),
SVGCommand(9.0, 8.0, 11.0, 10.0)
]
assertCommandsEqual(actual, expect)
}
func testMultipleRelativeCurveTo() {
let actual:[SVGCommand] = SVGPath("M1 2q3 4 5 6 7 8 9 10q1 2 3 4").commands
let expect:[SVGCommand] = [
SVGCommand(
1.0, 2.0, type: .move),
SVGCommand(
1.0 + 3.0, 2.0 + 4.0,
1.0 + 5.0, 2.0 + 6.0),
SVGCommand(
1.0 + 5.0 + 7.0, 2.0 + 6.0 + 8.0,
1.0 + 5.0 + 9.0, 2.0 + 6.0 + 10.0),
SVGCommand(
1.0 + 5.0 + 9.0 + 1.0, 2.0 + 6.0 + 10.0 + 2.0,
1.0 + 5.0 + 9.0 + 3.0, 2.0 + 6.0 + 10.0 + 4.0)
]
assertCommandsEqual(actual, expect)
}
func testSingleAbsoluteSmoothCurveTo() {
let actual:[SVGCommand] = SVGPath("Q1 2 3 4T7 8").commands
let expect:[SVGCommand] = [
SVGCommand(1.0, 2.0, 3.0, 4.0),
SVGCommand(5.0, 6.0, 7.0, 8.0)
]
assertCommandsEqual(actual, expect)
}
func testMultipleAbsoluteSmoothCurveTo() {
let actual:[SVGCommand] = SVGPath("Q1 2 3 4T1 2 3 4").commands
let expect:[SVGCommand] = [
SVGCommand( 1.0, 2.0, 3.0, 4.0),
SVGCommand( 5.0, 6.0, 1.0, 2.0),
SVGCommand(-3.0, -2.0, 3.0, 4.0)
]
assertCommandsEqual(actual, expect)
}
func testSingleRelativeSmoothCurveTo() {
let actual:[SVGCommand] = SVGPath("Q1 2 3 4t7 8").commands
let expect:[SVGCommand] = [
SVGCommand(1.0, 2.0, 3.0, 4.0),
SVGCommand(5.0, 6.0, 10.0, 12.0)
]
assertCommandsEqual(actual, expect)
}
func testMultipleRelativeSmoothCurveTo() {
let actual:[SVGCommand] = SVGPath("Q1 2 3 4t2 1 3 4").commands
let expect:[SVGCommand] = [
SVGCommand(1.0, 2.0, 3.0, 4.0),
SVGCommand(5.0, 6.0, 5.0, 5.0),
SVGCommand(5.0, 4.0, 8.0, 9.0)
]
assertCommandsEqual(actual, expect)
}
func testAbsoluteSmoothToAfterMoveTo() {
let actual:[SVGCommand] = SVGPath("M1 2T3 4").commands
let expect:[SVGCommand] = [
SVGCommand(1.0, 2.0, type: .move),
SVGCommand(1.0, 2.0, 3.0, 4.0)
]
assertCommandsEqual(actual, expect)
}
func testAbsoluteSmoothToAfterLineTo() {
let actual:[SVGCommand] = SVGPath("L1 2T3 4").commands
let expect:[SVGCommand] = [
SVGCommand(1.0, 2.0, type: .line),
SVGCommand(1.0, 2.0, 3.0, 4.0)
]
assertCommandsEqual(actual, expect)
}
func testAbsoluteSmoothToAfterCubicCurveTo() {
let actual:[SVGCommand] = SVGPath("C1 2 3 4 5 6T7 8").commands
let expect:[SVGCommand] = [
SVGCommand(1.0, 2.0, 3.0, 4.0, 5.0, 6.0),
SVGCommand(5.0, 6.0, 7.0, 8.0)
]
assertCommandsEqual(actual, expect)
}
func testRelativeSmoothToAfterMoveTo() {
let actual:[SVGCommand] = SVGPath("M1 2t3 4").commands
let expect:[SVGCommand] = [
SVGCommand(1.0, 2.0, type: .move),
SVGCommand(1.0, 2.0, 4.0, 6.0)
]
assertCommandsEqual(actual, expect)
}
func testRelativeSmoothToAfterLineTo() {
let actual:[SVGCommand] = SVGPath("L1 2t3 4").commands
let expect:[SVGCommand] = [
SVGCommand(1.0, 2.0, type: .line),
SVGCommand(1.0, 2.0, 4.0, 6.0)
]
assertCommandsEqual(actual, expect)
}
func testRelativeSmoothToAfterCubicCurveTo() {
let actual:[SVGCommand] = SVGPath("C1 2 3 4 5 6t7 8").commands
let expect:[SVGCommand] = [
SVGCommand(1.0, 2.0, 3.0, 4.0, 5.0, 6.0),
SVGCommand(5.0, 6.0, 12.0, 14.0)
]
assertCommandsEqual(actual, expect)
}
} | mit | db540bcbc78b8bbe6200212881023833 | 30.269939 | 83 | 0.509615 | 3.556176 | false | true | false | false |
cprovatas/PPProfileManager | PPProfileManager/PPUser.swift | 1 | 1669 | //
// PPUser.swift
// PPProfileManager
//
// Created by Charlton Provatas on 5/24/17.
// Copyright © 2017 Charlton Provatas. All rights reserved.
//
import Foundation
import UIKit
/**
Summary: Primary model for PPProfileManager.
*/
public struct PPUser {
/// Unique identifier
public var id : String!
/// Background color
/// male - blue
/// female - green
/// can be updated by the user in ProfileView
public var backgroundColor : UIColor?
/// Only male or female.
/// see enum below
/// Will default to male if unsucessful retrieval from the server
public var gender : PPUserGender!
public var name : String!
public var age : Int!
public var profileImageURL : URL!
public lazy var hobbies : [String] = []
/// helper computed property that will return the age as a formatted string
public var ageFormattedString : String! {
if age == nil {
return "Age Unknown"
}
if age == 1 {
return "1 year old"
}
return "\(age!) years old"
}
}
/**
Summary: Gender type for our user. Only male or female.
*/
public enum PPUserGender : Int {
case male, female
/// Returns the default color based on the gender type
public var color : UIColor {
switch self {
case .male: return PPGlobals.defaultBlue
case .female: return PPGlobals.defaultGreen
}
}
/// Returns the case as a string
public var string : String {
switch self {
case .male: return "Male"
case .female: return "Female"
}
}
}
| mit | 82da849a4d44a1758d25e4198dd7250a | 21.849315 | 79 | 0.592326 | 4.377953 | false | false | false | false |
dalbin/Eureka | Example/Example/CustomCells.swift | 1 | 21581 | // CustomCells.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2015 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import UIKit
import MapKit
import Eureka
//MARK: WeeklyDayCell
public enum WeekDay {
case Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
}
public class WeekDayCell : Cell<Set<WeekDay>>, CellType {
@IBOutlet var sundayButton: UIButton!
@IBOutlet var mondayButton: UIButton!
@IBOutlet var tuesdayButton: UIButton!
@IBOutlet var wednesdayButton: UIButton!
@IBOutlet var thursdayButton: UIButton!
@IBOutlet var fridayButton: UIButton!
@IBOutlet var saturdayButton: UIButton!
public override func setup() {
height = { 60 }
row.title = nil
super.setup()
selectionStyle = .None
for subview in contentView.subviews {
if let button = subview as? UIButton {
button.setImage(UIImage(named: "checkedDay"), forState: UIControlState.Selected)
button.setImage(UIImage(named: "uncheckedDay"), forState: UIControlState.Normal)
button.adjustsImageWhenHighlighted = false
imageTopTitleBottom(button)
}
}
}
public override func update() {
row.title = nil
super.update()
let value = row.value
mondayButton.selected = value?.contains(.Monday) ?? false
tuesdayButton.selected = value?.contains(.Tuesday) ?? false
wednesdayButton.selected = value?.contains(.Wednesday) ?? false
thursdayButton.selected = value?.contains(.Thursday) ?? false
fridayButton.selected = value?.contains(.Friday) ?? false
saturdayButton.selected = value?.contains(.Saturday) ?? false
sundayButton.selected = value?.contains(.Sunday) ?? false
mondayButton.alpha = row.isDisabled ? 0.6 : 1.0
tuesdayButton.alpha = mondayButton.alpha
wednesdayButton.alpha = mondayButton.alpha
thursdayButton.alpha = mondayButton.alpha
fridayButton.alpha = mondayButton.alpha
saturdayButton.alpha = mondayButton.alpha
sundayButton.alpha = mondayButton.alpha
}
@IBAction func dayTapped(sender: UIButton) {
dayTapped(sender, day: getDayFromButton(sender))
}
private func getDayFromButton(button: UIButton) -> WeekDay{
switch button{
case sundayButton:
return .Sunday
case mondayButton:
return .Monday
case tuesdayButton:
return .Tuesday
case wednesdayButton:
return .Wednesday
case thursdayButton:
return .Thursday
case fridayButton:
return .Friday
default:
return .Saturday
}
}
private func dayTapped(button: UIButton, day: WeekDay){
button.selected = !button.selected
if button.selected{
row.value?.insert(day)
}
else{
row.value?.remove(day)
}
}
private func imageTopTitleBottom(button : UIButton){
guard let imageSize = button.imageView?.image?.size else { return }
let spacing : CGFloat = 3.0
button.titleEdgeInsets = UIEdgeInsetsMake(0.0, -imageSize.width, -(imageSize.height + spacing), 0.0)
guard let titleLabel = button.titleLabel, let title = titleLabel.text else { return }
let titleSize = title.sizeWithAttributes([NSFontAttributeName: titleLabel.font])
button.imageEdgeInsets = UIEdgeInsetsMake(-(titleSize.height + spacing), 0, 0, -titleSize.width)
}
}
//MARK: WeekDayRow
public final class WeekDayRow: Row<Set<WeekDay>, WeekDayCell>, RowType {
required public init(tag: String?) {
super.init(tag: tag)
displayValueFor = nil
cellProvider = CellProvider<WeekDayCell>(nibName: "WeekDaysCell")
}
}
//MARK: FloatLabelCell
public class _FloatLabelCell<T where T: Equatable, T: InputTypeInitiable>: Cell<T>, UITextFieldDelegate, TextFieldCell {
public var textField : UITextField { return floatLabelTextField }
required public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
lazy public var floatLabelTextField: FloatLabelTextField = { [unowned self] in
let floatTextField = FloatLabelTextField()
floatTextField.translatesAutoresizingMaskIntoConstraints = false
floatTextField.font = .preferredFontForTextStyle(UIFontTextStyleBody)
floatTextField.titleFont = .boldSystemFontOfSize(11.0)
floatTextField.clearButtonMode = .WhileEditing
return floatTextField
}()
public override func setup() {
super.setup()
height = { 55 }
selectionStyle = .None
contentView.addSubview(floatLabelTextField)
floatLabelTextField.delegate = self
floatLabelTextField.addTarget(self, action: "textFieldDidChange:", forControlEvents: .EditingChanged)
contentView.addConstraints(layoutConstraints())
}
public override func update() {
super.update()
textLabel?.text = nil
detailTextLabel?.text = nil
floatLabelTextField.attributedPlaceholder = NSAttributedString(string: row.title ?? "", attributes: [NSForegroundColorAttributeName: UIColor.lightGrayColor()])
floatLabelTextField.text = row.displayValueFor?(row.value)
floatLabelTextField.enabled = !row.isDisabled
floatLabelTextField.titleTextColour = .lightGrayColor()
floatLabelTextField.alpha = row.isDisabled ? 0.6 : 1
}
public override func cellCanBecomeFirstResponder() -> Bool {
return !row.isDisabled && floatLabelTextField.canBecomeFirstResponder()
}
public override func cellBecomeFirstResponder() -> Bool {
return floatLabelTextField.becomeFirstResponder()
}
public override func cellResignFirstResponder() -> Bool {
return floatLabelTextField.resignFirstResponder()
}
private func layoutConstraints() -> [NSLayoutConstraint] {
let views = ["floatLabeledTextField": floatLabelTextField]
let metrics = ["vMargin":8.0]
return NSLayoutConstraint.constraintsWithVisualFormat("H:|-[floatLabeledTextField]-|", options: .AlignAllBaseline, metrics: metrics, views: views) + NSLayoutConstraint.constraintsWithVisualFormat("V:|-(vMargin)-[floatLabeledTextField]-(vMargin)-|", options: .AlignAllBaseline, metrics: metrics, views: views)
}
public func textFieldDidChange(textField : UITextField){
guard let textValue = textField.text else {
row.value = nil
return
}
if let fieldRow = row as? FormatterConformance, let formatter = fieldRow.formatter where fieldRow.useFormatterDuringInput {
let value: AutoreleasingUnsafeMutablePointer<AnyObject?> = AutoreleasingUnsafeMutablePointer<AnyObject?>.init(UnsafeMutablePointer<T>.alloc(1))
let errorDesc: AutoreleasingUnsafeMutablePointer<NSString?> = nil
if formatter.getObjectValue(value, forString: textValue, errorDescription: errorDesc) {
row.value = value.memory as? T
if var selStartPos = textField.selectedTextRange?.start {
let oldVal = textField.text
textField.text = row.displayValueFor?(row.value)
if let f = formatter as? FormatterProtocol {
selStartPos = f.getNewPosition(forPosition: selStartPos, inTextInput: textField, oldValue: oldVal, newValue: textField.text)
}
textField.selectedTextRange = textField.textRangeFromPosition(selStartPos, toPosition: selStartPos)
}
return
}
}
guard !textValue.isEmpty else {
row.value = nil
return
}
guard let newValue = T.init(string: textValue) else {
row.updateCell()
return
}
row.value = newValue
}
//MARK: TextFieldDelegate
public func textFieldDidBeginEditing(textField: UITextField) {
formViewController()?.beginEditing(self)
}
public func textFieldDidEndEditing(textField: UITextField) {
formViewController()?.endEditing(self)
}
}
public class TextFloatLabelCell : _FloatLabelCell<String>, CellType {
required public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
public override func setup() {
super.setup()
textField.autocorrectionType = .Default
textField.autocapitalizationType = .Sentences
textField.keyboardType = .Default
}
}
public class IntFloatLabelCell : _FloatLabelCell<Int>, CellType {
required public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
public override func setup() {
super.setup()
textField.autocorrectionType = .Default
textField.autocapitalizationType = .None
textField.keyboardType = .NumberPad
}
}
public class PhoneFloatLabelCell : _FloatLabelCell<String>, CellType {
required public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
public override func setup() {
super.setup()
textField.keyboardType = .PhonePad
}
}
public class NameFloatLabelCell : _FloatLabelCell<String>, CellType {
required public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
public override func setup() {
super.setup()
textField.autocorrectionType = .No
textField.autocapitalizationType = .Words
textField.keyboardType = .NamePhonePad
}
}
public class EmailFloatLabelCell : _FloatLabelCell<String>, CellType {
required public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
public override func setup() {
super.setup()
textField.autocorrectionType = .No
textField.autocapitalizationType = .None
textField.keyboardType = .EmailAddress
}
}
public class PasswordFloatLabelCell : _FloatLabelCell<String>, CellType {
required public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
public override func setup() {
super.setup()
textField.autocorrectionType = .No
textField.autocapitalizationType = .None
textField.keyboardType = .ASCIICapable
textField.secureTextEntry = true
}
}
public class DecimalFloatLabelCell : _FloatLabelCell<Float>, CellType {
required public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
public override func setup() {
super.setup()
textField.keyboardType = .DecimalPad
}
}
public class URLFloatLabelCell : _FloatLabelCell<NSURL>, CellType {
required public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
public override func setup() {
super.setup()
textField.keyboardType = .URL
}
}
public class TwitterFloatLabelCell : _FloatLabelCell<String>, CellType {
required public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
public override func setup() {
super.setup()
textField.autocorrectionType = .No
textField.autocapitalizationType = .None
textField.keyboardType = .Twitter
}
}
public class AccountFloatLabelCell : _FloatLabelCell<String>, CellType {
required public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
public override func setup() {
super.setup()
textField.autocorrectionType = .No
textField.autocapitalizationType = .None
textField.keyboardType = .ASCIICapable
}
}
//MARK: FloatLabelRow
public class FloatFieldRow<T: Any, Cell: CellType where Cell: BaseCell, Cell: TextFieldCell, Cell.Value == T>: Row<T, Cell> {
public var formatter: NSFormatter?
public var useFormatterDuringInput: Bool
public required init(tag: String?) {
useFormatterDuringInput = false
super.init(tag: tag)
self.displayValueFor = { [unowned self] value in
guard let v = value else {
return nil
}
if let formatter = self.formatter {
if self.cell.textField.isFirstResponder() {
if self.useFormatterDuringInput {
return formatter.editingStringForObjectValue(v as! AnyObject)
}
else {
return String(v)
}
}
return formatter.stringForObjectValue(v as! AnyObject)
}
else{
return String(v)
}
}
}
}
public final class TextFloatLabelRow: FloatFieldRow<String, TextFloatLabelCell>, RowType {}
public final class IntFloatLabelRow: FloatFieldRow<Int, IntFloatLabelCell>, RowType {}
public final class DecimalFloatLabelRow: FloatFieldRow<Float, DecimalFloatLabelCell>, RowType {}
public final class URLFloatLabelRow: FloatFieldRow<NSURL, URLFloatLabelCell>, RowType {}
public final class TwitterFloatLabelRow: FloatFieldRow<String, TwitterFloatLabelCell>, RowType {}
public final class AccountFloatLabelRow: FloatFieldRow<String, AccountFloatLabelCell>, RowType {}
public final class PasswordFloatLabelRow: FloatFieldRow<String, PasswordFloatLabelCell>, RowType {}
public final class NameFloatLabelRow: FloatFieldRow<String, NameFloatLabelCell>, RowType {}
public final class EmailFloatLabelRow: FloatFieldRow<String, EmailFloatLabelCell>, RowType {}
//MARK: LocationRow
public final class LocationRow : SelectorRow<CLLocation, MapViewController>, RowType {
public required init(tag: String?) {
super.init(tag: tag)
presentationMode = .Show(controllerProvider: ControllerProvider.Callback { return MapViewController(){ _ in } }, completionCallback: { vc in vc.navigationController?.popViewControllerAnimated(true) })
displayValueFor = {
guard let location = $0 else { return "" }
let fmt = NSNumberFormatter()
fmt.maximumFractionDigits = 4
fmt.minimumFractionDigits = 4
let latitude = fmt.stringFromNumber(location.coordinate.latitude)!
let longitude = fmt.stringFromNumber(location.coordinate.longitude)!
return "\(latitude), \(longitude)"
}
}
}
public class MapViewController : UIViewController, TypedRowControllerType, MKMapViewDelegate {
public var row: RowOf<CLLocation>!
public var completionCallback : ((UIViewController) -> ())?
lazy var mapView : MKMapView = { [unowned self] in
let v = MKMapView(frame: self.view.bounds)
v.autoresizingMask = UIViewAutoresizing.FlexibleWidth.union(UIViewAutoresizing.FlexibleHeight)
return v
}()
lazy var pinView: UIImageView = { [unowned self] in
let v = UIImageView(frame: CGRectMake(0, 0, 50, 50))
v.image = UIImage(named: "map_pin", inBundle: NSBundle(forClass: MapViewController.self), compatibleWithTraitCollection: nil)
v.image = v.image?.imageWithRenderingMode(.AlwaysTemplate)
v.tintColor = self.view.tintColor
v.backgroundColor = .clearColor()
v.clipsToBounds = true
v.contentMode = .ScaleAspectFit
v.userInteractionEnabled = false
return v
}()
let width: CGFloat = 10.0
let height: CGFloat = 5.0
lazy var ellipse: UIBezierPath = { [unowned self] in
let ellipse = UIBezierPath(ovalInRect: CGRectMake(0 , 0, self.width, self.height))
return ellipse
}()
lazy var ellipsisLayer: CAShapeLayer = { [unowned self] in
let layer = CAShapeLayer()
layer.bounds = CGRectMake(0, 0, self.width, self.height)
layer.path = self.ellipse.CGPath
layer.fillColor = UIColor.grayColor().CGColor
layer.fillRule = kCAFillRuleNonZero
layer.lineCap = kCALineCapButt
layer.lineDashPattern = nil
layer.lineDashPhase = 0.0
layer.lineJoin = kCALineJoinMiter
layer.lineWidth = 1.0
layer.miterLimit = 10.0
layer.strokeColor = UIColor.grayColor().CGColor
return layer
}()
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nil, bundle: nil)
}
convenience public init(_ callback: (UIViewController) -> ()){
self.init(nibName: nil, bundle: nil)
completionCallback = callback
}
public override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(mapView)
mapView.delegate = self
mapView.addSubview(pinView)
mapView.layer.insertSublayer(ellipsisLayer, below: pinView.layer)
let button = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: "tappedDone:")
button.title = "Done"
navigationItem.rightBarButtonItem = button
if let value = row.value {
let region = MKCoordinateRegionMakeWithDistance(value.coordinate, 400, 400)
mapView.setRegion(region, animated: true)
}
else{
mapView.showsUserLocation = true
}
updateTitle()
}
public override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
let center = mapView.convertCoordinate(mapView.centerCoordinate, toPointToView: pinView)
pinView.center = CGPointMake(center.x, center.y - (CGRectGetHeight(pinView.bounds)/2))
ellipsisLayer.position = center
}
func tappedDone(sender: UIBarButtonItem){
let target = mapView.convertPoint(ellipsisLayer.position, toCoordinateFromView: mapView)
row.value? = CLLocation(latitude: target.latitude, longitude: target.longitude)
completionCallback?(self)
}
func updateTitle(){
let fmt = NSNumberFormatter()
fmt.maximumFractionDigits = 4
fmt.minimumFractionDigits = 4
let latitude = fmt.stringFromNumber(mapView.centerCoordinate.latitude)!
let longitude = fmt.stringFromNumber(mapView.centerCoordinate.longitude)!
title = "\(latitude), \(longitude)"
}
public func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
let pinAnnotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "annotation")
pinAnnotationView.pinColor = MKPinAnnotationColor.Red
pinAnnotationView.draggable = false
pinAnnotationView.animatesDrop = true
return pinAnnotationView
}
public func mapView(mapView: MKMapView, regionWillChangeAnimated animated: Bool) {
ellipsisLayer.transform = CATransform3DMakeScale(0.5, 0.5, 1)
UIView.animateWithDuration(0.2, animations: { [weak self] in
self?.pinView.center = CGPointMake(self!.pinView.center.x, self!.pinView.center.y - 10)
})
}
public func mapView(mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
ellipsisLayer.transform = CATransform3DIdentity
UIView.animateWithDuration(0.2, animations: { [weak self] in
self?.pinView.center = CGPointMake(self!.pinView.center.x, self!.pinView.center.y + 10)
})
updateTitle()
}
}
| mit | 5f1faae1e8c9cbb1d4f509fbb8e153bc | 36.597561 | 316 | 0.665029 | 5.225424 | false | false | false | false |
hollance/swift-algorithm-club | Queue/Queue-Optimized.swift | 2 | 1096 | /*
First-in first-out queue (FIFO)
New elements are added to the end of the queue. Dequeuing pulls elements from
the front of the queue.
Enqueuing and dequeuing are O(1) operations.
*/
public struct Queue<T> {
fileprivate var array = [T?]()
fileprivate var head = 0
public var isEmpty: Bool {
return count == 0
}
public var count: Int {
return array.count - head
}
public mutating func enqueue(_ element: T) {
array.append(element)
}
public mutating func dequeue() -> T? {
guard let element = array[guarded: head] else { return nil }
array[head] = nil
head += 1
let percentage = Double(head)/Double(array.count)
if array.count > 50 && percentage > 0.25 {
array.removeFirst(head)
head = 0
}
return element
}
public var front: T? {
if isEmpty {
return nil
} else {
return array[head]
}
}
}
extension Array {
subscript(guarded idx: Int) -> Element? {
guard (startIndex..<endIndex).contains(idx) else {
return nil
}
return self[idx]
}
}
| mit | ff17a6c4047a89ad11984809be080157 | 18.571429 | 79 | 0.605839 | 3.872792 | false | false | false | false |
raymondshadow/SwiftDemo | SwiftApp/Pods/RxSwift/RxSwift/Subjects/BehaviorSubject.swift | 5 | 5013 | //
// BehaviorSubject.swift
// RxSwift
//
// Created by Krunoslav Zaher on 5/23/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
/// Represents a value that changes over time.
///
/// Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications.
public final class BehaviorSubject<Element>
: Observable<Element>
, SubjectType
, ObserverType
, SynchronizedUnsubscribeType
, Cancelable {
public typealias SubjectObserverType = BehaviorSubject<Element>
typealias Observers = AnyObserver<Element>.s
typealias DisposeKey = Observers.KeyType
/// Indicates whether the subject has any observers
public var hasObservers: Bool {
self._lock.lock()
let value = self._observers.count > 0
self._lock.unlock()
return value
}
let _lock = RecursiveLock()
// state
private var _isDisposed = false
private var _element: Element
private var _observers = Observers()
private var _stoppedEvent: Event<Element>?
#if DEBUG
fileprivate let _synchronizationTracker = SynchronizationTracker()
#endif
/// Indicates whether the subject has been disposed.
public var isDisposed: Bool {
return self._isDisposed
}
/// Initializes a new instance of the subject that caches its last value and starts with the specified value.
///
/// - parameter value: Initial value sent to observers when no other value has been received by the subject yet.
public init(value: Element) {
self._element = value
#if TRACE_RESOURCES
_ = Resources.incrementTotal()
#endif
}
/// Gets the current value or throws an error.
///
/// - returns: Latest value.
public func value() throws -> Element {
self._lock.lock(); defer { self._lock.unlock() } // {
if self._isDisposed {
throw RxError.disposed(object: self)
}
if let error = self._stoppedEvent?.error {
// intentionally throw exception
throw error
}
else {
return self._element
}
//}
}
/// Notifies all subscribed observers about next event.
///
/// - parameter event: Event to send to the observers.
public func on(_ event: Event<E>) {
#if DEBUG
self._synchronizationTracker.register(synchronizationErrorMessage: .default)
defer { self._synchronizationTracker.unregister() }
#endif
dispatch(self._synchronized_on(event), event)
}
func _synchronized_on(_ event: Event<E>) -> Observers {
self._lock.lock(); defer { self._lock.unlock() }
if self._stoppedEvent != nil || self._isDisposed {
return Observers()
}
switch event {
case .next(let element):
self._element = element
case .error, .completed:
self._stoppedEvent = event
}
return self._observers
}
/// Subscribes an observer to the subject.
///
/// - parameter observer: Observer to subscribe to the subject.
/// - returns: Disposable object that can be used to unsubscribe the observer from the subject.
public override func subscribe<O: ObserverType>(_ observer: O) -> Disposable where O.E == Element {
self._lock.lock()
let subscription = self._synchronized_subscribe(observer)
self._lock.unlock()
return subscription
}
func _synchronized_subscribe<O: ObserverType>(_ observer: O) -> Disposable where O.E == E {
if self._isDisposed {
observer.on(.error(RxError.disposed(object: self)))
return Disposables.create()
}
if let stoppedEvent = self._stoppedEvent {
observer.on(stoppedEvent)
return Disposables.create()
}
let key = self._observers.insert(observer.on)
observer.on(.next(self._element))
return SubscriptionDisposable(owner: self, key: key)
}
func synchronizedUnsubscribe(_ disposeKey: DisposeKey) {
self._lock.lock()
self._synchronized_unsubscribe(disposeKey)
self._lock.unlock()
}
func _synchronized_unsubscribe(_ disposeKey: DisposeKey) {
if self._isDisposed {
return
}
_ = self._observers.removeKey(disposeKey)
}
/// Returns observer interface for subject.
public func asObserver() -> BehaviorSubject<Element> {
return self
}
/// Unsubscribe all observers and release resources.
public func dispose() {
self._lock.lock()
self._isDisposed = true
self._observers.removeAll()
self._stoppedEvent = nil
self._lock.unlock()
}
#if TRACE_RESOURCES
deinit {
_ = Resources.decrementTotal()
}
#endif
}
| apache-2.0 | c115ab919af482deccabd1dea3fae6d1 | 29.192771 | 116 | 0.601556 | 5.042254 | false | false | false | false |
flipacholas/RCActionView | RCActionView/Classes/RCSheetMenu.swift | 1 | 7003 | //
// RCSheetMenu.swift
// Pods
//
// Created by Rodrigo on 10/06/2016.
//
//
import Foundation
class RCSheetMenu : RCBaseMenu, UITableViewDataSource, UITableViewDelegate {
var titleLabel: UILabel
var tableView: UITableView!
var items: [String]
var subItems: [String]
var actionHandle: RCMenuActionHandler?
var selectedItemIndex: Int
let kMAX_SHEET_TABLE_HEIGHT = CGFloat(400)
override init(frame: CGRect) {
self.titleLabel = UILabel(frame: CGRect.zero)
self.items = []
self.subItems = []
self.selectedItemIndex = NSIntegerMax
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
convenience init(title: String, itemTitles: [String], style: RCActionViewStyle) {
self.init(frame: UIScreen.main.bounds)
self.tableView = UITableView(frame: self.bounds, style: .plain)
self.tableView.isUserInteractionEnabled = true
self.tableView.backgroundColor = UIColor.clear
self.tableView.backgroundView = nil
self.tableView.separatorStyle = .singleLine
self.tableView.delegate = self
self.tableView.dataSource = self
self.style = style
self.backgroundColor = RCBaseMenu.BaseMenuBackgroundColor(self.style)
self.titleLabel.backgroundColor = UIColor.clear
self.titleLabel.font = UIFont.boldSystemFont(ofSize: 17)
self.titleLabel.textAlignment = .center
self.titleLabel.textColor = RCBaseMenu.BaseMenuTextColor(self.style)
self.addSubview(titleLabel)
self.addSubview(tableView)
self.setupWithTitle(title, items: itemTitles, subItems: nil)
}
convenience init(title: String, itemTitles: [String], subTitles: [String], style: RCActionViewStyle) {
self.init(frame: UIScreen.main.bounds)
self.tableView = UITableView(frame: self.bounds, style: .plain)
self.tableView.backgroundColor = UIColor.clear
self.tableView.backgroundView = nil
self.tableView.separatorStyle = .singleLine
self.tableView.delegate = self
self.tableView.dataSource = self
self.tableView.isUserInteractionEnabled = true
self.style = style
self.backgroundColor = RCBaseMenu.BaseMenuBackgroundColor(self.style)
self.titleLabel.backgroundColor = UIColor.clear
self.titleLabel.font = UIFont.boldSystemFont(ofSize: 17)
self.titleLabel.textAlignment = .center
self.titleLabel.textColor = RCBaseMenu.BaseMenuTextColor(self.style)
self.addSubview(titleLabel)
self.addSubview(tableView)
self.setupWithTitle(title, items: itemTitles, subItems: subTitles)
}
func setupWithTitle(_ title: String, items: [String], subItems: [String]?) {
self.titleLabel.text = title
self.items = items
if let _ = subItems {
self.subItems = subItems! }
}
override func layoutSubviews() {
super.layoutSubviews()
var height: CGFloat = 0
let table_top_margin: CGFloat = 0
let table_bottom_margin: CGFloat = 10
self.titleLabel.frame = CGRect(origin: CGPoint.zero, size: CGSize(width: self.bounds.size.width, height: 40))
height += self.titleLabel.bounds.size.height
height += table_top_margin
self.tableView.reloadData()
self.tableView.layoutIfNeeded()
var contentHeight: CGFloat = self.tableView.contentSize.height
if contentHeight > kMAX_SHEET_TABLE_HEIGHT {
contentHeight = kMAX_SHEET_TABLE_HEIGHT
self.tableView.isScrollEnabled = true
}
else {
self.tableView.isScrollEnabled = false
}
self.tableView.allowsSelection = true
self.tableView.frame = CGRect(x: self.bounds.size.width * 0.05, y: height, width: self.bounds.size.width * 0.9, height: contentHeight)
height += self.tableView.bounds.size.height
height += table_bottom_margin
self.bounds = CGRect(origin: CGPoint.zero, size: CGSize(width: self.bounds.size.width, height: height))
}
func triggerSelectedAction(_ actionHandle: @escaping (NSInteger) -> Void) {
self.actionHandle = actionHandle
}
func numberOfSections(in tableView: UITableView!) -> Int {
return 1
}
func tableView(_ tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
return self.items.count
}
func tableView(_ tableView: UITableView!, heightForRowAt indexPath: IndexPath) -> CGFloat {
if self.subItems.count > 0 {
return 55
}
else {
return 44
}
}
func tableView(_ tableView: UITableView!, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cellId: String = "cellId"
var cell: UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: cellId)
if let _ = cell { } else {
cell = UITableViewCell(style: .subtitle, reuseIdentifier: cellId)
cell!.backgroundColor = UIColor.clear
cell!.textLabel!.backgroundColor = UIColor.clear
cell!.detailTextLabel!.backgroundColor = UIColor.clear
cell!.selectionStyle = .none
cell!.textLabel!.font = UIFont.systemFont(ofSize: 16)
cell!.detailTextLabel!.font = UIFont.systemFont(ofSize: 14)
cell!.textLabel!.textColor = RCBaseMenu.BaseMenuTextColor(self.style)
cell!.detailTextLabel!.textColor = RCBaseMenu.BaseMenuTextColor(self.style)
}
cell!.textLabel!.text = self.items[(indexPath as NSIndexPath).row]
if self.subItems.count > (indexPath as NSIndexPath).row {
var subTitle: String = self.subItems[(indexPath as NSIndexPath).row]
if !subTitle.isEqual(NSNull()) {
cell!.detailTextLabel!.text = subTitle
}
}
if self.selectedItemIndex == (indexPath as NSIndexPath).row {
cell!.accessoryType = .checkmark
}
else {
cell!.accessoryType = .none
}
return cell!
}
func tableView(_ tableView: UITableView!, didSelectRowAt indexPath: IndexPath) {
if self.selectedItemIndex != (indexPath as NSIndexPath).row {
self.selectedItemIndex = (indexPath as NSIndexPath).row
tableView.reloadData()
}
if (self.actionHandle != nil) {
let delayInSeconds: Double = 0.15
let popTime: DispatchTime = DispatchTime.now() + Double(Int64(delayInSeconds * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: popTime, execute: {() -> Void in
self.actionHandle!((indexPath as NSIndexPath).row)
})
}
}
}
| mit | b01c9ed52fcfbe7a862e692560a38d0f | 37.690608 | 142 | 0.634157 | 4.763946 | false | false | false | false |
jamalping/XPUtil | XPUtil/Optional+Extension.swift | 1 | 1532 | //
// Optional+Extension.swift
// XPUtilExample
//
// Created by Apple on 2019/6/27.
// Copyright © 2019 xyj. All rights reserved.
//
public extension Optional {
/// 是否是空
var isNone: Bool {
switch self {
case .none:
return true
case .some:
return false
}
}
/// 是否有值
var isSome: Bool {
return !self.isNone
}
/// 返回可选值或默认值
/// - Parameter default: 如果可选值为空,将会默认值
func or(_ default: Wrapped) -> Wrapped {
return self ?? `default`
}
func or(else: () -> Wrapped) -> Wrapped {
return self ?? `else`()
}
/// 当可选值不为空时,执行 `some` 闭包
func on(some: () throws -> Void) rethrows {
if self != nil { try some() }
}
/// 当可选值为空时,执行 `none` 闭包
func on(none: () throws -> Void) rethrows {
if self == nil { try none() }
}
/// 可选值不为空且可选值满足 `predicate` 条件才返回,否则返回 `nil`
///
/// 仅会影响 id < 1000 的用户
/// 正常写法
/// if let aUser = user, user.id < 1000 { aUser.upgradeToPremium() }
/// 使用 `filter`
/// user.filter({ $0.id < 1000 })?.upgradeToPremium()
func filter(_ predicate: (Wrapped) -> Bool) -> Wrapped? {
guard let unwrapped = self,
predicate(unwrapped) else { return nil }
return self
}
}
| mit | cdeb513d401ebbc90e55dcd060321a64 | 20.790323 | 72 | 0.506292 | 3.732044 | false | false | false | false |
Norod/Filterpedia | Filterpedia/components/VectorSlider.swift | 1 | 3856 | //
// VectorSlider.swift
// Filterpedia
//
// Created by Simon Gladman on 29/12/2015.
// Copyright © 2015 Simon Gladman. All rights reserved.
//
// 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
class VectorSlider: UIControl
{
var maximumValue: CGFloat?
let stackView: UIStackView =
{
let stackView = UIStackView()
stackView.distribution = UIStackViewDistribution.fillEqually
stackView.axis = UILayoutConstraintAxis.horizontal
return stackView
}()
override init(frame: CGRect)
{
super.init(frame: frame)
addSubview(stackView)
}
required init?(coder aDecoder: NSCoder)
{
fatalError("init(coder:) has not been implemented")
}
var vectorWithMaximumValue: (vector: CIVector?, maximumValue: CGFloat?)?
{
didSet
{
maximumValue = vectorWithMaximumValue?.maximumValue
vector = vectorWithMaximumValue?.vector
}
}
private(set) var vector: CIVector?
{
didSet
{
if (vector?.count ?? 0) != oldValue?.count
{
rebuildUI()
}
guard let vector = vector else
{
return
}
for (index, slider) in stackView.arrangedSubviews.enumerated() where slider is UISlider
{
if let slider = slider as? UISlider
{
slider.value = Float(vector.value(at: index))
}
}
}
}
func rebuildUI()
{
stackView.arrangedSubviews.forEach
{
$0.removeFromSuperview()
}
guard let vector = vector else
{
return
}
let sliderMax = maximumValue ?? vector.sliderMax
for _ in 0 ..< vector.count
{
let slider = UISlider()
slider.maximumValue = Float(sliderMax)
slider.addTarget(self, action: #selector(VectorSlider.sliderChangeHandler), for: UIControlEvents.valueChanged)
stackView.addArrangedSubview(slider)
}
}
func sliderChangeHandler()
{
let values = stackView.arrangedSubviews
.filter({ $0 is UISlider })
.map({ CGFloat(($0 as! UISlider).value) })
vector = CIVector(values: values,
count: values.count)
sendActions(for: UIControlEvents.valueChanged)
}
override func layoutSubviews()
{
stackView.frame = bounds
stackView.spacing = 5
}
}
extension CIVector
{
/// If the maximum of any of the vector's values is greater than one,
/// return double that, otherwise, return 1.
///
/// `CIVector(x: 10, y: 12, z: 9, w: 11).sliderMax` = 24
/// `CIVector(x: 0, y: 1, z: 1, w: 0).sliderMax` = 1
var sliderMax: CGFloat
{
var maxValue: CGFloat = 1
for i in 0 ..< self.count
{
maxValue = max(maxValue,
self.value(at: i) > 1 ? self.value(at: i) * 2 : 1)
}
return maxValue
}
}
| gpl-3.0 | 4b056af9df1006da8cf6d0d1f736aa7a | 25.22449 | 122 | 0.560052 | 4.782878 | false | false | false | false |
apple/swift | test/IRGen/virtual-function-elimination-two-modules.swift | 9 | 2642 | // Tests that under -enable-llvm-vfe + -internalize-at-link, cross-module
// virtual calls are done via thunks and LLVM GlobalDCE is able to remove unused
// virtual methods from a library based on a list of used symbols by a client.
// RUN: %empty-directory(%t)
// (1) Build library swiftmodule
// RUN: %target-build-swift -parse-as-library -Xfrontend -enable-llvm-vfe \
// RUN: %s -DLIBRARY -module-name Library \
// RUN: -emit-module -o %t/Library.swiftmodule \
// RUN: -emit-tbd -emit-tbd-path %t/libLibrary.tbd -Xfrontend -tbd-install_name=%t/libLibrary.dylib
// (2) Build client
// RUN: %target-build-swift -parse-as-library -Xfrontend -enable-llvm-vfe \
// RUN: %s -DCLIENT -module-name Main -I%t -L%t -lLibrary -o %t/main
// (3) Extract a list of used symbols by client from library
// RUN: %llvm-nm --undefined-only -m %t/main | grep 'from libLibrary' | awk '{print $3}' > %t/used-symbols
// (4) Now produce the .dylib with just the symbols needed by the client
// RUN: %target-build-swift -parse-as-library -Xfrontend -enable-llvm-vfe -Xfrontend -internalize-at-link \
// RUN: %s -DLIBRARY -lto=llvm-full %lto_flags -module-name Library \
// RUN: -emit-library -o %t/libLibrary.dylib \
// RUN: -Xlinker -exported_symbols_list -Xlinker %t/used-symbols -Xlinker -dead_strip
// (5) Check list of symbols in library
// RUN: %llvm-nm --defined-only %t/libLibrary.dylib | %FileCheck %s --check-prefix=NM
// (6) Execution test
// RUN: %target-run %t/main | %FileCheck %s
// REQUIRES: executable_test
// FIXME(mracek): More work needed to get this to work on non-Apple platforms.
// REQUIRES: VENDOR=apple
// For LTO, the linker dlopen()'s the libLTO library, which is a scenario that
// ASan cannot work in ("Interceptors are not working, AddressSanitizer is
// loaded too late").
// REQUIRES: no_asan
// Remote test execution does not support dynamically loaded libraries.
// UNSUPPORTED: remote_run
#if LIBRARY
public class MyClass {
public init() {}
public func foo() { print("MyClass.foo") }
public func bar() { print("MyClass.bar") }
}
public class MyDerivedClass: MyClass {
override public func foo() { print("MyDerivedClass.foo") }
override public func bar() { print("MyDerivedClass.bar") }
}
// NM-NOT: $s7Library14MyDerivedClassC3baryyF
// NM: $s7Library14MyDerivedClassC3fooyyF
// NM-NOT: $s7Library7MyClassC3baryyF
// NM: $s7Library7MyClassC3fooyyF
#endif
#if CLIENT
import Library
@_cdecl("main")
func main() -> Int32 {
let o: MyClass = MyDerivedClass()
o.foo()
print("Done")
// CHECK: MyDerivedClass.foo
// CHECK-NEXT: Done
return 0
}
#endif
| apache-2.0 | 2ae149f5adcb7db03e873a98608bca05 | 32.443038 | 107 | 0.695307 | 3.206311 | false | true | false | false |
fouquet/MonthlySales | MonthlySales/Shared/ApiMethods.swift | 1 | 8237 | //
// ApiMethods.swift
// MonthlySales
//
// Created by René Fouquet on 11.06.17.
// Copyright © 2017 René Fouquet. All rights reserved.
//
import Foundation
enum ApiError: Error {
case emptyResult
case noInternetConnection
case timeout
}
extension ApiError {
func errorMessage() -> String {
switch self {
case .emptyResult: return "The server returned with an empty response."
case .noInternetConnection: return "There is no Internet connection."
case .timeout: return "Timeout while waiting for a server response."
}
}
}
protocol ApiMethodsProtocol {
func getSalesDataFor(startDate: Date, endDate: Date, completion: @escaping (Data?) -> Void) throws
func fetchUserInfo(completion: @escaping ((user: String?, currencySymbol: String?)) -> Void) throws
init(formatters: FormattersProtocol)
}
protocol ApiParserProtocol {
func parseSalesData(_ data: Data) throws -> [Sale]
init(formatters: FormattersProtocol)
}
protocol URLQueryParameterStringConvertible {
var queryParameters: String { get }
}
final class ApiMethods: ApiMethodsProtocol {
private let apiBaseURL = "https://api.appfigures.com"
/*
Get the clientKey on the AppFigures key manager: https://appfigures.com/developers/keys
*/
private let clientKey = ""
/*
The authorizationKey must be base64 encoded in the format USERNAME:PASSWORD.
Open Terminal and type (with *your* username/password, duh):
echo -n 'USERNAME:PASSWORD' | base64
This will return the base64 encoded string you need to paste here.
*/
private let authorizationKey = ""
/*
Account Email. Required to fetch the currency.
*/
private let userEmail = ""
private let formatters: FormattersProtocol
private func APIRequest(with method: String, url: URL) -> URLRequest {
var request = URLRequest(url: url)
request.httpMethod = method
request.addValue(clientKey, forHTTPHeaderField: "X-Client-Key")
request.addValue("Basic \(authorizationKey)", forHTTPHeaderField: "Authorization")
return request
}
init(formatters: FormattersProtocol) {
self.formatters = formatters
if clientKey.isEmpty || authorizationKey.isEmpty || userEmail.isEmpty {
fatalError("clientKey, authorizationKey or userEmail is empty")
}
}
func getSalesDataFor(startDate: Date, endDate: Date, completion: @escaping (Data?) -> Void) throws {
let session = URLSession(configuration: URLSessionConfiguration.default, delegate: nil, delegateQueue: nil)
guard var URL = URL(string: apiBaseURL + "/v2/reports/sales") else { return }
let URLParams = ["start_date": formatters.fromDate(startDate),
"end_date": formatters.fromDate(endDate),
"include_inapps": "true",
"group_by": "dates"]
URL = URL.appendingQueryParameters(URLParams)
let request = APIRequest(with: "GET", url: URL)
session.dataTask(with: request, completionHandler: { (data: Data?, _, error: Error?) -> Void in
if error == nil {
completion(data)
} else {
print("URL Session Task Failed: %@", error!.localizedDescription)
completion(nil)
}
}).resume()
session.finishTasksAndInvalidate()
}
private func getUserInfo(completion: @escaping (User?) -> Void) {
let session = URLSession(configuration: URLSessionConfiguration.default, delegate: nil, delegateQueue: nil)
guard let URL = URL(string: apiBaseURL + "/v2/users/\(userEmail)") else { return }
let request = APIRequest(with: "GET", url: URL)
session.dataTask(with: request, completionHandler: { (data: Data?, _, error: Error?) -> Void in
if error == nil {
guard let data = data else { return }
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
guard let object = json as? [String: Any] else { return }
let user = try User(json: object)
completion(user)
} catch let error {
print(error)
completion(nil)
}
} else {
print("URL Session Task Failed: %@", error!.localizedDescription)
completion(nil)
}
}).resume()
session.finishTasksAndInvalidate()
}
private func getCurrencySymbol(iso: String, completion: @escaping (String?) -> Void) {
let session = URLSession(configuration: URLSessionConfiguration.default, delegate: nil, delegateQueue: nil)
guard let URL = URL(string: apiBaseURL + "/v2/data/currencies") else { return }
let request = APIRequest(with: "GET", url: URL)
session.dataTask(with: request, completionHandler: { (data: Data?, _, error: Error?) -> Void in
if error == nil {
guard let data = data else { return }
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
guard let array = json as? [[String: Any]] else { return }
var currencies = [Currency]()
try array.forEach({
currencies.append(try Currency(json: $0))
})
completion(Currency.symbolForISO(iso, currencies: currencies))
} catch let error {
print(error)
completion(nil)
}
} else {
print("URL Session Task Failed: %@", error!.localizedDescription)
completion(nil)
}
}).resume()
session.finishTasksAndInvalidate()
}
func fetchUserInfo(completion: @escaping ((user: String?, currencySymbol: String?)) -> Void) {
getUserInfo { [weak self] (user: User?) in
if let iso = user?.currency {
self?.getCurrencySymbol(iso: iso, completion: { (symbol: String?) in
completion((user: user?.name, currencySymbol: symbol))
})
} else {
completion((user: user?.name, currencySymbol: nil))
}
}
}
}
final class ApiParser: ApiParserProtocol {
private let formatters: FormattersProtocol
init(formatters: FormattersProtocol) {
self.formatters = formatters
}
func parseSalesData(_ data: Data) -> [Sale] {
var returnArray = [Sale]()
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
guard let array = json as? [String: [String: Any]] else { return returnArray }
for (_, obj) in array {
let sale = try Sale(json: obj, formatters: formatters)
if sale.date < formatters.today() && !formatters.isDateToday(sale.date) {
returnArray.append(sale)
}
returnArray = returnArray.sorted(by: { $0.date > $1.date })
}
} catch let error {
print(error)
}
return returnArray
}
}
extension Dictionary : URLQueryParameterStringConvertible {
var queryParameters: String {
var parts: [String] = []
for (key, value) in self {
let part = String(format: "%@=%@",
String(describing: key).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!,
String(describing: value).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
parts.append(part as String)
}
return parts.joined(separator: "&")
}
}
extension URL {
func appendingQueryParameters(_ parametersDictionary: Dictionary<String, String>) -> URL {
let URLString: String = String(format: "%@?%@", self.absoluteString, parametersDictionary.queryParameters)
return URL(string: URLString)!
}
}
| mit | e234468366ae5f53feb359279ac1870a | 35.433628 | 120 | 0.585013 | 4.954272 | false | false | false | false |
alex-heritier/jury_app | jury-ios/Jury/LoginViewController.swift | 1 | 1497 | //
// LoginViewController.swift
// Jury
//
// Created by Keegan Papakipos on 1/29/16.
// Copyright © 2016 kpapakipos. All rights reserved.
//
import UIKit
class LoginViewController: UIViewController {
let myAppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
@IBOutlet weak var usernameField: UITextField!
@IBOutlet weak var passwordField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func submit(sender: UIButton) {
myAppDelegate.networkingController.sendLoginCredentials(usernameField.text!, passwordText: passwordField.text!)
let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
dispatch_async(dispatch_get_global_queue(priority, 0)) {
while !self.myAppDelegate.appModel.canLogin {
NSThread.sleepForTimeInterval(1/100)
}
dispatch_async(dispatch_get_main_queue(),{
self.performSegueWithIdentifier("loginSuccessSegue", sender: self)
})
}
}
@IBAction func logout(segue: UIStoryboardSegue) {
usernameField.text = ""
passwordField.text = ""
self.myAppDelegate.appModel.canLogin = false
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
}
}
| mit | 39739f5d5514cf5ea4a3b000aac1642a | 28.333333 | 119 | 0.659091 | 4.9701 | false | false | false | false |
jfrowies/iEMI | iEMI/ParkingTime.swift | 1 | 1992 | //
// ParkingTime.swift
// iEMI
//
// Created by Fer Rowies on 8/22/15.
// Copyright © 2015 Rowies. All rights reserved.
//
import UIKit
enum ParkingStatus {
case Closed
case Parked
}
class ParkingTime: Parking {
private let kParkingEndTimeEmpty: String = "0000-00-00T00:00:00"
var date: String?
var startTimeStamp: String?
var endTimeStamp: String?
var maxEndTimeStamp: String?
var parkingDuration: String?
var parkingStatus : ParkingStatus!
var startTime: String {
get {
guard let timeStamp = startTimeStamp else {
return ""
}
let range = timeStamp.startIndex.advancedBy(11) ..< timeStamp.endIndex.advancedBy(-3)
return timeStamp.substringWithRange(range)
// return timeStamp.substringWithRange(Range<String.Index>(start: timeStamp.startIndex.advancedBy(11), end: timeStamp.endIndex.advancedBy(-3)))
}
}
var endTime: String {
get {
guard let timeStamp = endTimeStamp else {
return ""
}
let range = timeStamp.startIndex.advancedBy(11) ..< timeStamp.endIndex.advancedBy(-3)
return timeStamp.substringWithRange(range)
// return timeStamp.substringWithRange(Range<String.Index>(start: timeStamp.startIndex.advancedBy(11), end: timeStamp.endIndex.advancedBy(-3)))
}
}
override init(json:[String:AnyObject]) {
super.init(json: json)
date = json["TarFecha"]?.description
startTimeStamp = json["TarHoraIni"]?.description
endTimeStamp = json["TarHoraFin"]?.description
maxEndTimeStamp = json["TarFinMax"]?.description
parkingDuration = json["TarTiempo"]?.description
parkingStatus = endTimeStamp == kParkingEndTimeEmpty ? ParkingStatus.Parked : ParkingStatus.Closed
}
}
| apache-2.0 | 47e5bf1e378f57bf8c7e7f1f4855332b | 28.279412 | 154 | 0.608237 | 4.718009 | false | false | false | false |
KosyanMedia/Aviasales-iOS-SDK | AviasalesSDKTemplate/Source/HotelsSource/HotelDetails/HLHotelCardView.swift | 1 | 5746 |
class HLHotelCardView: UIView {
@IBOutlet fileprivate weak var hotelInfoView: HLHotelInfoView!
@IBOutlet fileprivate(set) weak var photoScrollView: HLPhotoScrollView!
@IBOutlet fileprivate(set) weak var bottomGradientView: UIView!
@IBOutlet weak var badgesContainerView: UIView!
let infoViewLogic = HotelInfoViewLogic()
private let controlsAnimationDuration: TimeInterval = 0.15
fileprivate var showControlsTimer: Timer?
var photoIndexChangeHandler: ((_ index: Int) -> Void)?
var selectPhotoHandler: ((_ index: Int) -> Void)?
var currentPhotoIndex: Int {
get {
return self.photoScrollView.currentPhotoIndex
}
set(newValue) {
self.photoScrollView.scrollToPhotoIndex(newValue, animated: false)
}
}
private(set) var hotel: HDKHotel! {
didSet {
if !(oldValue?.isValid() ?? false) || !hotel.isEqual(oldValue) {
hotelInfoView.hotel = hotel
updatePhotosContent()
}
}
}
func update(withVariant variant: HLResultVariant, shouldDrawBadges: Bool) {
hotel = variant.hotel
if shouldDrawBadges {
drawBadges(variant: variant)
}
}
func drawBadges(variant: HLResultVariant) {
let badges = variant.badges as? [HLPopularHotelBadge] ?? []
let badgesContainerSize = badgesContainerView.bounds.size
let badgeViews = badgesContainerView.drawTextBadges(badges, forVariant: variant, startX: 15, bottomY: badgesContainerSize.height - 15, widthLimit: badgesContainerSize.width - 15 * 2)
for badgeView in badgeViews {
badgeView.autoSetDimensions(to: badgeView.bounds.size)
badgeView.autoPinEdge(toSuperviewEdge: .leading, withInset: badgeView.frame.origin.x)
badgeView.autoPinEdge(toSuperviewEdge: .bottom, withInset: badgesContainerView.bounds.size.height - (badgeView.frame.origin.y + badgeView.frame.height))
}
}
var contentTransform: CATransform3D = CATransform3DIdentity {
didSet {
if let cell = self.photoScrollView.visibleCell {
cell.layer.transform = self.contentTransform
}
}
}
var hideInfoControls: Bool = false {
didSet {
self.hotelInfoView.isHidden = self.hideInfoControls
}
}
// MARK: - Override methods
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
self.initialize()
}
override var bounds: CGRect {
didSet {
if !self.bounds.size.equalTo(oldValue.size) {
self.photoScrollView.relayoutContent()
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
self.initialize()
}
// MARK: - Internal Methods
func showGradients(animated: Bool) {
let duration = animated ? self.controlsAnimationDuration : 0.0
UIView.animate(withDuration: duration,
animations: { () -> Void in
self.bottomGradientView.alpha = 1.0
}, completion: nil)
}
func hideGradients(animated: Bool) {
let duration = animated ? self.controlsAnimationDuration : 0.0
UIView.animate(withDuration: duration,
animations: { () -> Void in
self.bottomGradientView.alpha = 0.0
}, completion: nil)
}
func showInfoControls(animated: Bool) {
self.hotelInfoView.showInfoControls(animated: animated)
}
func hideInfoControls(animated: Bool) {
self.hotelInfoView.hideInfoControls(animated: animated)
}
// MARK: - Private methods
private func initialize() {
if let view = loadViewFromNib("HLHotelCardView", self) {
view.frame = self.bounds
view.clipsToBounds = true
view.translatesAutoresizingMaskIntoConstraints = false
addSubview(view)
view.autoPinEdgesToSuperviewEdges()
setNeedsLayout()
}
photoScrollView.backgroundColor = JRColorScheme.hotelBackgroundColor()
photoScrollView.placeholderImage = UIImage.photoPlaceholder
}
fileprivate func updatePhotosContent() {
self.photoScrollView.delegate = self
self.photoScrollView.updateDataSource(withHotel: self.hotel, imageSize: HLPhotoManager.defaultHotelPhotoSize)
self.photoScrollView.scrollToPhotoIndex(self.currentPhotoIndex, animated: false)
}
@objc fileprivate func showControlsAfterTimeout() {
self.showControlsTimer?.invalidate()
self.showControlsTimer = nil
self.hotelInfoView.showInfoControls(animated: true)
}
}
extension HLHotelCardView: HLPhotoScrollViewDelegate {
func photoCollectionViewImageContentMode() -> UIView.ContentMode {
return self.hotel.photosIds.count == 0 ? UIView.ContentMode.center : UIView.ContentMode.scaleAspectFill
}
func photoScrollPhotoIndexChanged(_ index: Int) {
self.photoIndexChangeHandler?(index)
}
func photoScrollWillBeginDragging() {
self.showControlsTimer?.invalidate()
self.showControlsTimer = nil
self.hotelInfoView.hideInfoControls(animated: true)
}
func photoScrollDidEndDragging() {
self.showControlsTimer = Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(HLHotelCardView.showControlsAfterTimeout), userInfo: nil, repeats: false)
}
func photoCollectionViewDidSelectPhotoAtIndex(_ index: Int) {
if self.hotel.photosIds.count > 0 {
self.selectPhotoHandler?(index)
}
}
}
| mit | 458fa4a203dbe45e13e1513544fd2787 | 30.398907 | 190 | 0.654368 | 4.844857 | false | false | false | false |
coderwjq/swiftweibo | SwiftWeibo/SwiftWeibo/Classes/Compose/Emoticon/Emoticon.swift | 1 | 1823 | //
// Emoticon.swift
// SwiftWeibo
//
// Created by mzzdxt on 2016/11/10.
// Copyright © 2016年 wjq. All rights reserved.
//
import UIKit
class Emoticon: NSObject {
// MARK:- 定义属性
/// emoji的code
var code: String? {
didSet {
guard let code = code else {
return
}
/* 将emoji对应的代码转为字符串显示 */
// 1.创建扫描器
let scanner = Scanner(string: code)
// 2.调用方法,扫描出code中的值
var value: UInt32 = 0
scanner.scanHexInt32(&value)
// 3.将value转成字符
let c = Character(UnicodeScalar(value)!)
// 4.将字符转成字符串
emojiCode = String(c)
}
}
/// 普通表情对应的图片名称
var png: String? {
didSet {
guard let png = png else {
return
}
pngPath = Bundle.main.bundlePath + "/Emoticons.bundle/" + png
}
}
/// 普通表情对应的文字
var chs: String?
// MARK:- 数据处理
var pngPath: String?
var emojiCode: String?
var isRemove: Bool = false
var isEmpty: Bool = false
// MARK:- 自定义构造函数
init(dict: [String : String]) {
super.init()
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {
}
init(isEmpty: Bool) {
self.isEmpty = true
}
init(isRemove: Bool) {
self.isRemove = true
}
override var description: String {
return dictionaryWithValues(forKeys: ["emojiCode", "pngPath", "chs"]).description
}
}
| apache-2.0 | bcae95d8e60c745030a52cc24f8c66bf | 20.358974 | 89 | 0.488595 | 4.419098 | false | false | false | false |
gu704823/huobanyun | huobanyun/Spring/DesignableTabBarController.swift | 14 | 4843 | // The MIT License (MIT)
//
// Copyright (c) 2015 Meng To ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
@IBDesignable class DesignableTabBarController: UITabBarController {
@IBInspectable var normalTint: UIColor = UIColor.clear {
didSet {
UITabBar.appearance().tintColor = normalTint
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: normalTint], for: UIControlState())
}
}
@IBInspectable var selectedTint: UIColor = UIColor.clear {
didSet {
UITabBar.appearance().tintColor = selectedTint
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: selectedTint], for:UIControlState.selected)
}
}
@IBInspectable var fontName: String = "" {
didSet {
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: normalTint, NSFontAttributeName: UIFont(name: fontName, size: 11)!], for: UIControlState())
}
}
@IBInspectable var firstSelectedImage: UIImage? {
didSet {
if let image = firstSelectedImage {
var tabBarItems = self.tabBar.items as [UITabBarItem]!
tabBarItems?[0].selectedImage = image.withRenderingMode(UIImageRenderingMode.alwaysTemplate)
}
}
}
@IBInspectable var secondSelectedImage: UIImage? {
didSet {
if let image = secondSelectedImage {
var tabBarItems = self.tabBar.items as [UITabBarItem]!
tabBarItems?[1].selectedImage = image.withRenderingMode(UIImageRenderingMode.alwaysTemplate)
}
}
}
@IBInspectable var thirdSelectedImage: UIImage? {
didSet {
if let image = thirdSelectedImage {
var tabBarItems = self.tabBar.items as [UITabBarItem]!
tabBarItems?[2].selectedImage = image.withRenderingMode(UIImageRenderingMode.alwaysTemplate)
}
}
}
@IBInspectable var fourthSelectedImage: UIImage? {
didSet {
if let image = fourthSelectedImage {
var tabBarItems = self.tabBar.items as [UITabBarItem]!
tabBarItems?[3].selectedImage = image.withRenderingMode(UIImageRenderingMode.alwaysTemplate)
}
}
}
@IBInspectable var fifthSelectedImage: UIImage? {
didSet {
if let image = fifthSelectedImage {
var tabBarItems = self.tabBar.items as [UITabBarItem]!
tabBarItems?[4].selectedImage = image.withRenderingMode(UIImageRenderingMode.alwaysTemplate)
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
for item in self.tabBar.items as [UITabBarItem]! {
if let image = item.image {
item.image = image.imageWithColor(tintColor: self.normalTint).withRenderingMode(UIImageRenderingMode.alwaysOriginal)
}
}
}
}
extension UIImage {
func imageWithColor(tintColor: UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
let context = UIGraphicsGetCurrentContext()
context!.translateBy(x: 0, y: self.size.height)
context!.scaleBy(x: 1.0, y: -1.0);
context!.setBlendMode(CGBlendMode.normal)
let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)
context?.clip(to: rect, mask: self.cgImage!)
tintColor.setFill()
context!.fill(rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()! as UIImage
UIGraphicsEndImageContext()
return newImage
}
}
| mit | ef39964e5fe95993724e159d79397fa6 | 38.696721 | 185 | 0.657031 | 5.381111 | false | false | false | false |
edx/edx-app-ios | Test/OEXConfig+URLCredentialProviderTests.swift | 2 | 1253 | //
// OEXConfig+URLCredentialProviderTests.swift
// edX
//
// Created by Akiva Leffert on 11/9/15.
// Copyright © 2015 edX. All rights reserved.
//
import XCTest
class OEXConfig_URLCredentialProviderTests: XCTestCase {
static let credentials = [
[
"HOST" : "https://somehost.com",
"USERNAME" : "someuser",
"PASSWORD" : "abc123"
],
[
"HOST" : "https://otherhost.com",
"USERNAME" : "meeee",
"PASSWORD" : "miiiine",
]
]
let config = OEXConfig(dictionary:["BASIC_AUTH_CREDENTIALS" : credentials])
func testHit() {
for group in Swift.type(of: self).credentials {
let host = URL(string:group["HOST"]!)!.host!
let credential = config.URLCredentialForHost(host as NSString)
XCTAssertNotNil(credential)
XCTAssertEqual(credential!.user, group["USERNAME"]!)
XCTAssertEqual(credential!.password, group["PASSWORD"]!)
XCTAssertEqual(credential!.persistence, URLCredential.Persistence.forSession)
}
}
func testMiss() {
let credential = config.URLCredentialForHost("unknown")
XCTAssertNil(credential)
}
}
| apache-2.0 | 8ef2682d20929eff0a82188befe17287 | 27.454545 | 89 | 0.585463 | 4.569343 | false | true | false | false |
edx/edx-app-ios | Source/FCMListener.swift | 1 | 1136 | //
// FCMListener.swift
// edX
//
// Created by Salman on 07/11/2019.
// Copyright © 2019 edX. All rights reserved.
//
import UIKit
@objc class FCMListener: NSObject, OEXPushListener {
typealias Environment = OEXSessionProvider & OEXRouterProvider & OEXConfigProvider
var environment: Environment
@objc init(environment: Environment){
self.environment = environment
}
func didReceiveLocalNotification(userInfo: [AnyHashable : Any] = [:]) {
//Implementation for local Notification
}
func didReceiveRemoteNotification(userInfo: [AnyHashable : Any] = [:]) {
guard let dictionary = userInfo as? [String: Any], isFCMNotification(userInfo: userInfo) else { return }
let link = PushLink(dictionary: dictionary)
DeepLinkManager.sharedInstance.processNotification(with: link, environment: environment)
Messaging.messaging().appDidReceiveMessage(userInfo)
}
private func isFCMNotification(userInfo: [AnyHashable : Any]) -> Bool {
if let _ = userInfo["gcm.message_id"] {
return true
}
return false
}
}
| apache-2.0 | 4d05e7896109596727f8ccecd2a5dbbd | 28.868421 | 112 | 0.673128 | 4.670782 | false | false | false | false |
wireapp/wire-ios-data-model | Tests/Source/Model/Conversation/ZMConversationTests+PrepareToSend.swift | 1 | 2259 | //
// Wire
// Copyright (C) 2017 Wire Swiss GmbH
//
// 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 Foundation
@testable import WireDataModel
class ZMConversationPrepareToSendTests: ZMConversationTestsBase {
func testThatMessagesAddedToDegradedConversationAreExpiredAndFlaggedAsCauseDegradation() {
// GIVEN
let conversation = ZMConversation.insertNewObject(in: self.uiMOC)
conversation.securityLevel = .secureWithIgnored
// WHEN
let message = try! conversation.appendText(content: "Foo") as! ZMMessage
self.uiMOC.saveOrRollback()
// THEN
self.syncMOC.performGroupedBlockAndWait {
let message = self.syncMOC.object(with: message.objectID) as! ZMMessage
XCTAssertTrue(message.isExpired)
XCTAssertTrue(message.causedSecurityLevelDegradation)
}
}
func testThatMessagesResentToDegradedConversationAreExpiredAndFlaggedAsCauseDegradation() {
// GIVEN
let conversation = ZMConversation.insertNewObject(in: self.uiMOC)
conversation.securityLevel = .secure
let message = try! conversation.appendText(content: "Foo") as! ZMMessage
message.expire()
self.uiMOC.saveOrRollback()
// WHEN
conversation.securityLevel = .secureWithIgnored
message.resend()
self.uiMOC.saveOrRollback()
// THEN
self.syncMOC.performGroupedBlockAndWait {
let message = self.syncMOC.object(with: message.objectID) as! ZMMessage
XCTAssertTrue(message.isExpired)
XCTAssertTrue(message.causedSecurityLevelDegradation)
}
}
}
| gpl-3.0 | 9f80357a7d306657d6de1271280ce173 | 35.435484 | 95 | 0.706065 | 4.837259 | false | true | false | false |
lorentey/swift | stdlib/public/core/Filter.swift | 4 | 11233 | //===--- Filter.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 sequence whose elements consist of the elements of some base
/// sequence that also satisfy a given predicate.
///
/// - Note: `s.lazy.filter { ... }`, for an arbitrary sequence `s`,
/// is a `LazyFilterSequence`.
@frozen // lazy-performance
public struct LazyFilterSequence<Base: Sequence> {
@usableFromInline // lazy-performance
internal var _base: Base
/// The predicate used to determine which elements produced by
/// `base` are also produced by `self`.
@usableFromInline // lazy-performance
internal let _predicate: (Base.Element) -> Bool
/// Creates an instance consisting of the elements `x` of `base` for
/// which `isIncluded(x) == true`.
@inlinable // lazy-performance
public // @testable
init(_base base: Base, _ isIncluded: @escaping (Base.Element) -> Bool) {
self._base = base
self._predicate = isIncluded
}
}
extension LazyFilterSequence {
/// An iterator over the elements traversed by some base iterator that also
/// satisfy a given predicate.
///
/// - Note: This is the associated `Iterator` of `LazyFilterSequence`
/// and `LazyFilterCollection`.
@frozen // lazy-performance
public struct Iterator {
/// The underlying iterator whose elements are being filtered.
public var base: Base.Iterator { return _base }
@usableFromInline // lazy-performance
internal var _base: Base.Iterator
@usableFromInline // lazy-performance
internal let _predicate: (Base.Element) -> Bool
/// Creates an instance that produces the elements `x` of `base`
/// for which `isIncluded(x) == true`.
@inlinable // lazy-performance
internal init(_base: Base.Iterator, _ isIncluded: @escaping (Base.Element) -> Bool) {
self._base = _base
self._predicate = isIncluded
}
}
}
extension LazyFilterSequence.Iterator: IteratorProtocol, Sequence {
public typealias Element = Base.Element
/// Advances to the next element and returns it, or `nil` if no next element
/// exists.
///
/// Once `nil` has been returned, all subsequent calls return `nil`.
///
/// - Precondition: `next()` has not been applied to a copy of `self`
/// since the copy was made.
@inlinable // lazy-performance
public mutating func next() -> Element? {
while let n = _base.next() {
if _predicate(n) {
return n
}
}
return nil
}
}
extension LazyFilterSequence: Sequence {
public typealias Element = Base.Element
/// Returns an iterator over the elements of this sequence.
///
/// - Complexity: O(1).
@inlinable // lazy-performance
public __consuming func makeIterator() -> Iterator {
return Iterator(_base: _base.makeIterator(), _predicate)
}
@inlinable
public func _customContainsEquatableElement(_ element: Element) -> Bool? {
// optimization to check the element first matches the predicate
guard _predicate(element) else { return false }
return _base._customContainsEquatableElement(element)
}
}
extension LazyFilterSequence: LazySequenceProtocol { }
/// A lazy `Collection` wrapper that includes the elements of an
/// underlying collection that satisfy a predicate.
///
/// - Note: The performance of accessing `startIndex`, `first`, any methods
/// that depend on `startIndex`, or of advancing an index depends
/// on how sparsely the filtering predicate is satisfied, and may not offer
/// the usual performance given by `Collection`. Be aware, therefore, that
/// general operations on `LazyFilterCollection` instances may not have the
/// documented complexity.
public typealias LazyFilterCollection<T: Collection> = LazyFilterSequence<T>
extension LazyFilterCollection: Collection {
public typealias SubSequence = LazyFilterCollection<Base.SubSequence>
// Any estimate of the number of elements that pass `_predicate` requires
// iterating the collection and evaluating each element, which can be costly,
// is unexpected, and usually doesn't pay for itself in saving time through
// preventing intermediate reallocations. (SR-4164)
@inlinable // lazy-performance
public var underestimatedCount: Int { return 0 }
/// A type that represents a valid position in the collection.
///
/// Valid indices consist of the position of every element and a
/// "past the end" position that's not valid for use as a subscript.
public typealias Index = Base.Index
/// The position of the first element in a non-empty collection.
///
/// In an empty collection, `startIndex == endIndex`.
///
/// - Complexity: O(*n*), where *n* is the ratio between unfiltered and
/// filtered collection counts.
@inlinable // lazy-performance
public var startIndex: Index {
var index = _base.startIndex
while index != _base.endIndex && !_predicate(_base[index]) {
_base.formIndex(after: &index)
}
return index
}
/// The collection's "past the end" position---that is, the position one
/// greater than the last valid subscript argument.
///
/// `endIndex` is always reachable from `startIndex` by zero or more
/// applications of `index(after:)`.
@inlinable // lazy-performance
public var endIndex: Index {
return _base.endIndex
}
// TODO: swift-3-indexing-model - add docs
@inlinable // lazy-performance
public func index(after i: Index) -> Index {
var i = i
formIndex(after: &i)
return i
}
@inlinable // lazy-performance
public func formIndex(after i: inout Index) {
// TODO: swift-3-indexing-model: _failEarlyRangeCheck i?
var index = i
_precondition(index != _base.endIndex, "Can't advance past endIndex")
repeat {
_base.formIndex(after: &index)
} while index != _base.endIndex && !_predicate(_base[index])
i = index
}
@inline(__always)
@inlinable // lazy-performance
internal func _advanceIndex(_ i: inout Index, step: Int) {
repeat {
_base.formIndex(&i, offsetBy: step)
} while i != _base.endIndex && !_predicate(_base[i])
}
@inline(__always)
@inlinable // lazy-performance
internal func _ensureBidirectional(step: Int) {
// FIXME: This seems to be the best way of checking whether _base is
// forward only without adding an extra protocol requirement.
// index(_:offsetBy:limitedBy:) is chosen becuase it is supposed to return
// nil when the resulting index lands outside the collection boundaries,
// and therefore likely does not trap in these cases.
if step < 0 {
_ = _base.index(
_base.endIndex, offsetBy: step, limitedBy: _base.startIndex)
}
}
@inlinable // lazy-performance
public func distance(from start: Index, to end: Index) -> Int {
// The following line makes sure that distance(from:to:) is invoked on the
// _base at least once, to trigger a _precondition in forward only
// collections.
_ = _base.distance(from: start, to: end)
var _start: Index
let _end: Index
let step: Int
if start > end {
_start = end
_end = start
step = -1
}
else {
_start = start
_end = end
step = 1
}
var count = 0
while _start != _end {
count += step
formIndex(after: &_start)
}
return count
}
@inlinable // lazy-performance
public func index(_ i: Index, offsetBy n: Int) -> Index {
var i = i
let step = n.signum()
// The following line makes sure that index(_:offsetBy:) is invoked on the
// _base at least once, to trigger a _precondition in forward only
// collections.
_ensureBidirectional(step: step)
for _ in 0 ..< abs(numericCast(n)) {
_advanceIndex(&i, step: step)
}
return i
}
@inlinable // lazy-performance
public func formIndex(_ i: inout Index, offsetBy n: Int) {
i = index(i, offsetBy: n)
}
@inlinable // lazy-performance
public func index(
_ i: Index, offsetBy n: Int, limitedBy limit: Index
) -> Index? {
var i = i
let step = n.signum()
// The following line makes sure that index(_:offsetBy:limitedBy:) is
// invoked on the _base at least once, to trigger a _precondition in
// forward only collections.
_ensureBidirectional(step: step)
for _ in 0 ..< abs(numericCast(n)) {
if i == limit {
return nil
}
_advanceIndex(&i, step: step)
}
return i
}
@inlinable // lazy-performance
public func formIndex(
_ i: inout Index, offsetBy n: Int, limitedBy limit: Index
) -> Bool {
if let advancedIndex = index(i, offsetBy: n, limitedBy: limit) {
i = advancedIndex
return true
}
i = limit
return false
}
/// Accesses the element at `position`.
///
/// - Precondition: `position` is a valid position in `self` and
/// `position != endIndex`.
@inlinable // lazy-performance
public subscript(position: Index) -> Element {
return _base[position]
}
@inlinable // lazy-performance
public subscript(bounds: Range<Index>) -> SubSequence {
return SubSequence(_base: _base[bounds], _predicate)
}
@inlinable
public func _customLastIndexOfEquatableElement(_ element: Element) -> Index?? {
guard _predicate(element) else { return .some(nil) }
return _base._customLastIndexOfEquatableElement(element)
}
}
extension LazyFilterCollection: LazyCollectionProtocol { }
extension LazyFilterCollection: BidirectionalCollection
where Base: BidirectionalCollection {
@inlinable // lazy-performance
public func index(before i: Index) -> Index {
var i = i
formIndex(before: &i)
return i
}
@inlinable // lazy-performance
public func formIndex(before i: inout Index) {
// TODO: swift-3-indexing-model: _failEarlyRangeCheck i?
var index = i
_precondition(index != _base.startIndex, "Can't retreat before startIndex")
repeat {
_base.formIndex(before: &index)
} while !_predicate(_base[index])
i = index
}
}
extension LazySequenceProtocol {
/// Returns the elements of `self` that satisfy `isIncluded`.
///
/// - Note: The elements of the result are computed on-demand, as
/// the result is used. No buffering storage is allocated and each
/// traversal step invokes `predicate` on one or more underlying
/// elements.
@inlinable // lazy-performance
public __consuming func filter(
_ isIncluded: @escaping (Elements.Element) -> Bool
) -> LazyFilterSequence<Self.Elements> {
return LazyFilterSequence(_base: self.elements, isIncluded)
}
}
extension LazyFilterSequence {
@available(swift, introduced: 5)
public __consuming func filter(
_ isIncluded: @escaping (Element) -> Bool
) -> LazyFilterSequence<Base> {
return LazyFilterSequence(_base: _base) {
self._predicate($0) && isIncluded($0)
}
}
}
| apache-2.0 | bd49fee542281b859fa5684cc00e293f | 31.55942 | 89 | 0.66367 | 4.308784 | false | false | false | false |
garricn/secret | Pods/Bond/Bond/Core/ObservableArrayEvent.swift | 4 | 13105 | //
// The MIT License (MIT)
//
// Copyright (c) 2015 Srdan Rasic (@srdanrasic)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
/// Abstraction over an event type generated by a ObservableArray.
/// ObservableArray event encapsulates current state of the array, as well
/// as the operation that has triggered an event.
public protocol ObservableArrayEventType {
associatedtype ObservableArrayEventSequenceType: SequenceType
var sequence: ObservableArrayEventSequenceType { get }
var operation: ObservableArrayOperation<ObservableArrayEventSequenceType.Generator.Element> { get }
}
/// A concrete array event type.
public struct ObservableArrayEvent<ObservableArrayEventSequenceType: SequenceType>: ObservableArrayEventType {
public let sequence: ObservableArrayEventSequenceType
public let operation: ObservableArrayOperation<ObservableArrayEventSequenceType.Generator.Element>
}
/// Represents an operation that can be applied to a ObservableArray.
/// Note: Nesting of the .Batch operations is not supported at the moment.
public indirect enum ObservableArrayOperation<ElementType> {
case Insert(elements: [ElementType], fromIndex: Int)
case Update(elements: [ElementType], fromIndex: Int)
case Remove(range: Range<Int>)
case Reset(array: [ElementType])
case Batch([ObservableArrayOperation<ElementType>])
}
/// A array event change set represents a description of the change that
/// the array event operation does to a array in a way suited for application
/// to the UIKit collection views like UITableView or UICollectionView
public enum ObservableArrayEventChangeSet {
case Inserts(Set<Int>)
case Updates(Set<Int>)
case Deletes(Set<Int>)
}
public func ==(lhs: ObservableArrayEventChangeSet, rhs: ObservableArrayEventChangeSet) -> Bool {
switch (lhs, rhs) {
case (.Inserts(let l), .Inserts(let r)):
return l == r
case (.Updates(let l), .Updates(let r)):
return l == r
case (.Deletes(let l), .Deletes(let r)):
return l == r
default:
return false
}
}
public extension ObservableArrayOperation {
/// Maps elements encapsulated in the operation.
public func map<X>(transform: ElementType -> X) -> ObservableArrayOperation<X> {
switch self {
case .Reset(let array):
return .Reset(array: array.map(transform))
case .Insert(let elements, let fromIndex):
return .Insert(elements: elements.map(transform), fromIndex: fromIndex)
case .Update(let elements, let fromIndex):
return .Update(elements: elements.map(transform), fromIndex: fromIndex)
case .Remove(let range):
return .Remove(range: range)
case .Batch(let operations):
return .Batch(operations.map{ $0.map(transform) })
}
}
public func filter(includeElement: ElementType -> Bool, inout pointers: [Int]) -> ObservableArrayOperation<ElementType>? {
switch self {
case .Insert(let elements, let fromIndex):
for (index, element) in pointers.enumerate() {
if element >= fromIndex {
pointers[index] = element + elements.count
}
}
var insertedIndices: [Int] = []
var insertedElements: [ElementType] = []
for (index, element) in elements.enumerate() {
if includeElement(element) {
insertedIndices.append(fromIndex + index)
insertedElements.append(element)
}
}
if insertedIndices.count > 0 {
let insertionPoint = startingIndexForIndex(fromIndex, forPointers: pointers)
pointers.insertContentsOf(insertedIndices, at: insertionPoint)
return .Insert(elements: insertedElements, fromIndex: insertionPoint)
}
case .Update(let elements, let fromIndex):
var operations: [ObservableArrayOperation<ElementType>] = []
for (index, element) in elements.enumerate() {
let realIndex = fromIndex + index
// if element on this index is currently included in filtered array
if let location = pointers.indexOf(realIndex) {
if includeElement(element) {
// update
operations.append(.Update(elements: [element], fromIndex: location))
} else {
// remove
pointers.removeAtIndex(location)
operations.append(.Remove(range: location..<location+1))
}
} else { // element in this index is currently NOT included
if includeElement(element) {
// insert
let insertionPoint = startingIndexForIndex(realIndex, forPointers: pointers)
pointers.insert(realIndex, atIndex: insertionPoint)
operations.append(.Insert(elements: [element], fromIndex: insertionPoint))
} else {
// not contained, not inserted - do nothing
}
}
}
if operations.count == 1 {
return operations.first!
} else if operations.count > 1 {
return .Batch(operations)
}
case .Remove(let range):
var startIndex = -1
var endIndex = -1
for (index, element) in pointers.enumerate() {
if element >= range.startIndex {
if element < range.endIndex {
if startIndex < 0 {
startIndex = index
endIndex = index + 1
} else {
endIndex = index + 1
}
}
pointers[index] = element - range.count
}
}
if startIndex >= 0 {
let removedRange = Range(startIndex..<endIndex)
pointers.removeRange(removedRange)
return .Remove(range: removedRange)
}
case .Reset(let array):
pointers = pointersFromSequence(array, includeElement: includeElement)
return .Reset(array: array.filter(includeElement))
case .Batch(let operations):
var filteredOperations: [ObservableArrayOperation<ElementType>] = []
for operation in operations {
if let filtered = operation.filter(includeElement, pointers: &pointers) {
filteredOperations.append(filtered)
}
}
if filteredOperations.count == 1 {
return filteredOperations.first!
} else if filteredOperations.count > 0 {
return .Batch(filteredOperations)
}
}
return nil
}
/// Generates the `ObservableArrayEventChangeSet` representation of the operation.
public func changeSet() -> ObservableArrayEventChangeSet {
switch self {
case .Insert(let elements, let fromIndex):
return .Inserts(Set(fromIndex..<fromIndex+elements.count))
case .Update(let elements, let fromIndex):
return .Updates(Set(fromIndex..<fromIndex+elements.count))
case .Remove(let range):
return .Deletes(Set(range))
case .Reset:
fallthrough
case .Batch:
fatalError("Dear Sir/Madam, I cannot generate changeset for \(self) operation.")
}
}
}
internal func pointersFromSequence<S: SequenceType>(sequence: S, includeElement: S.Generator.Element -> Bool) -> [Int] {
var pointers: [Int] = []
for (index, element) in sequence.enumerate() {
if includeElement(element) {
pointers.append(index)
}
}
return pointers
}
internal func startingIndexForIndex(x: Int, forPointers pointers: [Int]) -> Int {
var idx: Int = -1
for (index, element) in pointers.enumerate() {
if element < x {
idx = index
} else {
break
}
}
return idx + 1
}
public func operationOffset<T>(operation: ObservableArrayOperation<T>) -> Int {
switch operation {
case .Insert(let elements, _):
return elements.count
case .Remove(let range):
return -range.count
default:
return 0
}
}
public func operationStartIndex<T>(operation: ObservableArrayOperation<T>) -> Int {
switch operation {
case .Insert(_, let fromIndex):
return fromIndex
case .Remove(let range):
return range.startIndex
default:
return 0
}
}
/// This function is used by UICollectionView and UITableView bindings. Batch operations are expected to be sequentially
/// applied to the array/array, which is not what those views do. The function converts operations into a "diff" discribing
/// elements at what indices changed and in what way.
///
/// Expected order: .Deletes, .Inserts, .Updates
///
/// Deletes are always indexed in the index-space of the original array
/// -> Deletes are shifted by preceding inserts and deletes at lower indices
/// Deletes of updated items are substracted from updates set
/// Deletes of inserted items are substracted from inserts set
/// Deletes shift preceding inserts at higher indices
///
/// Inserts are always indexed in the index-space of the final array
/// -> Inserts shift preceding inserts at higher indices
///
/// Updates are always indexed in the index-space of the original array
/// -> Updates are shifted by preceding inserts and deletes at lower indices
/// Updates of inserted items are annihilated
///
public func changeSetsFromBatchOperations<T>(operations: [ObservableArrayOperation<T>]) -> [ObservableArrayEventChangeSet] {
var inserts = Set<Int>()
var updates = Set<Int>()
var deletes = Set<Int>()
for (operationIndex, operation) in operations.enumerate() {
switch operation {
case .Insert(let elements, let fromIndex):
// Inserts are always indexed in the index-space of the array as it will look like when all operations are applies
// Inserts shift preceding inserts at higher indices
inserts = Set(inserts.map { $0 >= fromIndex ? $0 + elements.count : $0 })
inserts.unionInPlace(fromIndex..<fromIndex+elements.count)
case .Update(let elements, let fromIndex):
// Updates are always indexed in the index-space of the array before any operation is applied
// Updates done to the elements that were inserted in this batch must be discared
var newUpdates = Array(Set(fromIndex..<fromIndex+elements.count).subtract(inserts))
// Any prior insertion or deletion shifts our indices
for insert in inserts {
newUpdates = newUpdates.map { $0 >= insert ? $0 - 1 : $0 }
}
for delete in deletes {
newUpdates = newUpdates.map { $0 >= delete ? $0 + 1 : $0 }
}
updates.unionInPlace(newUpdates)
case .Remove(let range):
// Deletes are always indexed in the index-space of the array before any operation is applied
let possibleNewDeletes = Set(range)
// Elements that were inserted and then removed in this batch must be discared
let annihilated = inserts.intersect(possibleNewDeletes)
inserts.subtractInPlace(annihilated)
let actualNewDeletes = possibleNewDeletes.subtract(annihilated)
// Deletes are shifted by preceding inserts and deletes at lower indices
var correctionOffset = 0
for operation in operations.prefixUpTo(operationIndex) {
if range.startIndex >= operationStartIndex(operation) {
correctionOffset -= operationOffset(operation)
}
}
let newDeletes = actualNewDeletes.map { $0 + correctionOffset }
deletes.unionInPlace(newDeletes)
// Elements that were updated and then removed in this batch must be discared
updates.subtractInPlace(newDeletes)
// Deletes shift preceding inserts at higher indices
inserts = Set(inserts.map { $0 >= range.startIndex ? $0 - range.count : $0 })
case .Reset:
fatalError("Dear Sir/Madam, the .Reset operation within the .Batch is not supported at the moment!")
case .Batch:
fatalError("Dear Sir/Madam, nesting the .Batch operations is not supported at the moment!")
}
}
var changeSets: [ObservableArrayEventChangeSet] = []
if deletes.count > 0 {
changeSets.append(.Deletes(deletes))
}
if inserts.count > 0 {
changeSets.append(.Inserts(inserts))
}
if updates.count > 0 {
changeSets.append(.Updates(updates))
}
return changeSets
}
| mit | 4cdf40cd8ef802e52a93b29acf0d96d2 | 34.90411 | 124 | 0.674628 | 4.700502 | false | false | false | false |
lieonCX/Uber | UberRider/UberRider/View/Chat/ChatVC.swift | 1 | 7748 | //
// ChatVC.swift
// UberRider
//
// Created by lieon on 2017/4/1.
// Copyright © 2017年 ChangHongCloudTechService. All rights reserved.
//
import UIKit
import JSQMessagesViewController
import MobileCoreServices
import AVKit
import Kingfisher
class ChatVC: JSQMessagesViewController {
var tofriendName: String?
var tofriendID: String?
fileprivate var chatVM: ChatViewModel = ChatViewModel()
fileprivate lazy var messages: [JSQMessage] = [JSQMessage]()
fileprivate var picker: UIImagePickerController = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
loadData()
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return messages.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = super.collectionView(collectionView, cellForItemAt: indexPath) as? JSQMessagesCollectionViewCell else { return UICollectionViewCell() }
return cell
}
override func collectionView(_ collectionView: JSQMessagesCollectionView!, messageDataForItemAt indexPath: IndexPath!) -> JSQMessageData! {
return messages[indexPath.item]
}
override func didPressSend(_ button: UIButton!, withMessageText text: String!, senderId: String!, senderDisplayName: String!, date: Date!) {
chatVM.sendMessage(senderID: senderId, senderName: senderDisplayName, text: text)
finishSendingMessage()
}
override func collectionView(_ collectionView: JSQMessagesCollectionView!, messageBubbleImageDataForItemAt indexPath: IndexPath!) -> JSQMessageBubbleImageDataSource! {
let bubbleFactory = JSQMessagesBubbleImageFactory()
let message = messages[indexPath.item]
print(message.senderId)
if message.senderId == self.senderId {
return bubbleFactory?.outgoingMessagesBubbleImage(with: UIColor.blue)
} else {
return bubbleFactory?.incomingMessagesBubbleImage(with: UIColor.blue)
}
}
override func collectionView(_ collectionView: JSQMessagesCollectionView!, avatarImageDataForItemAt indexPath: IndexPath!) -> JSQMessageAvatarImageDataSource! {
return JSQMessagesAvatarImageFactory.avatarImage(with: UIImage(named: "sender_Icon"), diameter: 30)
}
override func didPressAccessoryButton(_ sender: UIButton!) {
let actionsheetVC = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
let imageAction = UIAlertAction(title: "Photo", style: .default) { _ in
self.openMedia(mediaType: kUTTypeImage)
}
let carmeraAction = UIAlertAction(title: "Carmera", style: .default) { _ in
self.openMedia(mediaType: kUTTypeVideo)
}
let cancleAction = UIAlertAction(title: "Cancle", style: .cancel, handler: nil)
actionsheetVC.addAction(imageAction)
actionsheetVC.addAction(carmeraAction)
actionsheetVC.addAction(cancleAction)
present(actionsheetVC, animated: true, completion: nil)
}
override func collectionView(_ collectionView: JSQMessagesCollectionView!, didTapMessageBubbleAt indexPath: IndexPath!) {
let message = messages[indexPath.item]
if message.isMediaMessage, let videoMedia = message.media as? JSQVideoMediaItem {
let playerVC = AVPlayerViewController()
playerVC.player = AVPlayer(url: videoMedia.fileURL)
present(playerVC, animated: true, completion: nil)
}
}
private func openMedia(mediaType: CFString) {
picker.sourceType = .photoLibrary
guard let type = UIImagePickerController.availableMediaTypes(for: .photoLibrary) else { return }
picker.mediaTypes = type
present(picker, animated: true, completion: nil)
}
}
extension ChatVC: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage, let imageData = UIImageJPEGRepresentation(image, 0.01), let _ = JSQPhotoMediaItem(image: image) {
chatVM.sendMediaMessage(senderID: senderId, senderName: senderDisplayName, image: imageData, video: nil)
}
if let videoUrl = info[UIImagePickerControllerMediaURL] as? URL, let _ = JSQVideoMediaItem(fileURL: videoUrl, isReadyToPlay: true){
chatVM.sendMediaMessage(senderID: senderId, senderName: senderDisplayName, image: nil, video: videoUrl)
}
picker.dismiss(animated: true, completion: nil)
collectionView.reloadData()
}
}
extension ChatVC {
fileprivate func setupUI() {
picker.delegate = self
senderId = UserInfo.shared.uid
senderDisplayName = UserInfo.shared.userName
}
fileprivate func loadData() {
chatVM.observeTextMessage { message in
guard let senderID = message[Constants.senderID] as? String, let senderDisplayName = message[Constants.senderName] as? String, let text = message[Constants.text] as? String else { return }
if senderID == self.senderId || senderID == self.tofriendID {
self.messages.append(JSQMessage(senderId: senderID, displayName: senderDisplayName, text: text))
self.collectionView.reloadData()
}
}
chatVM.oberserMediaMessage { message in
guard let senderID = message[Constants.senderID] as? String, let senderDisplayName = message[Constants.senderName] as? String, let urlStr = message[Constants.URL] as? String, let url = URL(string: urlStr) else { return }
if senderID == self.senderId || senderID == self.tofriendID {
do {
let data = try Data(contentsOf: url)
if let _ = UIImage(data: data) {
KingfisherManager.shared.downloader.downloadImage(with: url, options: nil, progressBlock: nil, completionHandler: { (image, error, _, _) in
if let image = image, let photo = JSQPhotoMediaItem(image: image), let message = JSQMessage(senderId: senderID, displayName: senderDisplayName, media: photo) {
if self.senderId == senderID {
photo.appliesMediaViewMaskAsOutgoing = true
} else {
photo.appliesMediaViewMaskAsOutgoing = false
}
self.messages.append(message)
}
self.collectionView.reloadData()
})
} else {
guard let video = JSQVideoMediaItem(fileURL: url, isReadyToPlay: true), let message = JSQMessage(senderId: senderID, displayName: senderDisplayName, media: video) else { return }
if self.senderId == senderID {
video.appliesMediaViewMaskAsOutgoing = true
} else {
video.appliesMediaViewMaskAsOutgoing = false
}
self.messages.append(message)
}
} catch {
print(error)
}
}
}
}
}
| mit | 495c046ca70addf0096c2cc83246894c | 47.710692 | 232 | 0.634087 | 5.596098 | false | false | false | false |
ResearchSuite/ResearchSuiteExtensions-iOS | Example/Pods/ResearchSuiteTaskBuilder/ResearchSuiteTaskBuilder/Classes/Step Providers/Descriptors/RSTBChoiceItemDescriptor.swift | 1 | 776 | //
// RSTBChoiceItemDescriptor.swift
// Pods
//
// Created by James Kizer on 4/8/17.
//
//
import UIKit
import Gloss
open class RSTBChoiceItemDescriptor: Gloss.Decodable {
public let text: String
public let detailText: String?
public let value: NSCoding & NSCopying & NSObjectProtocol
public let exclusive: Bool
public required init?(json: JSON) {
guard let prompt: String = "prompt" <~~ json,
let value: NSCoding & NSCopying & NSObjectProtocol = "value" <~~ json
else {
return nil
}
self.text = prompt
self.value = value
self.detailText = "detailText" <~~ json
self.exclusive = "exclusive" <~~ json ?? false
}
}
| apache-2.0 | 987aedd1271cda6451c53b1c18b34819 | 21.823529 | 81 | 0.574742 | 4.619048 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/UserInterface/Conversation Options/UINavigationController+CloseButton.swift | 1 | 1251 | //
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// 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 Foundation
import UIKit
extension UINavigationController {
func closeItem() -> UIBarButtonItem {
let item = UIBarButtonItem.createCloseItem()
item.target = self
item.action = #selector(closeTapped)
return item
}
func updatedCloseItem() -> UIBarButtonItem {
let item = UIBarButtonItem.createUpdatedCloseItem()
item.target = self
item.action = #selector(closeTapped)
return item
}
@objc
private func closeTapped() {
dismiss(animated: true)
}
}
| gpl-3.0 | 883315a5013ab912c37e5a36f10a0fcc | 28.785714 | 71 | 0.695444 | 4.516245 | false | false | false | false |
Handbid/Handbid-Swift | HandbidTests/HandbidEventTests.swift | 1 | 4305 | //
// HandbidTests.swift
// HandbidTests
//
// Created by Jon Hemstreet on 10/31/14.
// Copyright (c) 2014 Handbid. All rights reserved.
//
import UIKit
import XCTest
class Nerd : NSObject {
var triggered = false
func callback(event : HandbidEvent) {
self.triggered = true
}
}
class HandbidEventTests: XCTestCase {
var testEventEmissionOnTargetFlag = false
let options = [
"url" : "http://taysmacbookpro.local:6789"
]
func testInstantiatingEvent() {
let event = HandbidEvent(name: "test-event", data: ["foo" : "bar"])
}
func testGetterAndSetterOnEvent() {
// get
let event = HandbidEvent(name: "test-event", data: ["foo" : "bar"])
let bar = event.get("foo", defaultValue: nil) as String
XCTAssert(bar == "bar", "Getter did not return bar.")
// get default value nil
let event2 = HandbidEvent(name: "test-event", data: ["foo" : "bar"])
let optional = event2.get("foo3", defaultValue: nil) as String?
XCTAssert(optional == nil, "Defualt value failed.")
// get default value foobar
let event3 = HandbidEvent(name: "test-event", data : ["foo2" : "bar"])
let optional2 = event3.get("test-event", defaultValue: "foobar") as String?
XCTAssert(optional2! == "foobar", "Default value failed.")
// set
let event4 = HandbidEvent(name: "test-event", data : ["foo3" : "bar"])
event4.set("foo2", value: "bar2")
let optional3 = event4.get("foo2", defaultValue: nil) as String
XCTAssert(optional3 == "bar2", "Did not set.")
}
func testEventEmissionWithCallback() {
let emitter = HandbidEventEmitter()
emitter.on("handbid-event") { (event : HandbidEvent) -> Void in
let foo = event.get("foo", defaultValue: nil) as String
XCTAssert(foo == "bar", "Event emitted with proper value.")
}
emitter.emit("handbid-event", data: ["foo" : "bar"])
}
func testEventEmissionWithTarget() {
let emitter = HandbidEventEmitter()
let dummy = Nerd()
emitter.on("test-event", target: dummy, action: "callback:")
emitter.emit("test-event", data: ["foo" : "bar"])
XCTAssert(dummy.triggered, "target flag failed to set")
}
func testEventOffByTarget() {
let emitter = HandbidEventEmitter()
let dummy = Nerd()
emitter.on("test-event", target: dummy, action: "callback:")
emitter.emit("test-event", data: ["foo": "bar"])
XCTAssert(dummy.triggered, "initial trigger not set")
dummy.triggered = false;
emitter.off("test-event", target: dummy)
emitter.emit("test-event", data: ["foo": "bar"])
XCTAssertFalse(dummy.triggered, "trigger set when it should not have been")
}
func testOffByEvent() {
let emitter = HandbidEventEmitter()
let dummy = Nerd()
emitter.on("test-event", target: dummy, action: "callback:")
emitter.emit("test-event", data: ["foo": "bar"])
XCTAssert(dummy.triggered, "initial trigger not set")
dummy.triggered = false;
emitter.off("test-event")
emitter.emit("test-event", data: ["foo": "bar"])
XCTAssertFalse(dummy.triggered, "trigger set when it should not have been")
}
func testOffByTargetAndAction() {
let emitter = HandbidEventEmitter()
let dummy = Nerd()
emitter.on("test-event", target: dummy, action: "callback:")
emitter.emit("test-event", data: ["foo": "bar"])
XCTAssert(dummy.triggered, "initial trigger not set")
dummy.triggered = false;
emitter.off("test-event", target: dummy, action: "callback:")
emitter.emit("test-event", data: ["foo": "bar"])
XCTAssertFalse(dummy.triggered, "trigger set when it should not have been")
}
}
| mit | 47301fc9ae6e48f4d4b50ce5a7301e9d | 26.596154 | 83 | 0.548897 | 4.330986 | false | true | false | false |
red3/3DTouchDemo | swift/3DTouchDemo/3DTouchDemo/MainViewController+UIViewControllerPreviewing.swift | 1 | 1786 | //
// MainViewController+UIViewControllerPreviewing.swift
// 3DTouchDemo
//
// Created by Herui on 15/10/9.
// Copyright © 2015年 harry. All rights reserved.
//
import UIKit
extension MainViewController: UIViewControllerPreviewingDelegate {
// MARK: UIViewControllerPreviewingDelegate
/// Create a previewing view controller to be shown at "Peek".
func previewingContext(previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
// Obtain the index path and the cell that was pressed.
guard let indexPath = tableView.indexPathForRowAtPoint(location),
cell = tableView.cellForRowAtIndexPath(indexPath) else { return nil }
// Create a detail view controller and set its properties.
let detail = DetailViewController()
let previewDetail = sampleData[indexPath.row]
detail.previewingTitle = previewDetail.title
/*
Set the height of the preview by setting the preferred content size of the detail view controller.
Width should be zero, because it's not used in portrait.
*/
detail.preferredContentSize = CGSize(width: 0.0, height: previewDetail.preferredHeight)
// Set the source rect to the cell frame, so surrounding elements are blurred.
previewingContext.sourceRect = cell.frame
return detail
}
/// Present the view controller for the "Pop" action.
func previewingContext(previewingContext: UIViewControllerPreviewing, commitViewController viewControllerToCommit: UIViewController) {
// Reuse the "Peek" view controller for presentation.
showViewController(viewControllerToCommit, sender: self)
}
}
| apache-2.0 | 83988f8c8818f66e8cec51de33d110ac | 40.465116 | 141 | 0.705552 | 5.660317 | false | false | false | false |
Roommate-App/roomy | roomy/Pods/IBAnimatable/Sources/Controllers/AnimatableModalViewController.swift | 3 | 5318 | //
// Created by Tom Baranes on 16/07/16.
// Copyright © 2016 Jake Lin. All rights reserved.
//
import UIKit
/// `AnimatableModalViewController` is a customised modal view controller used as the `presentedViewController` for `UIPresentationController`. We can use it in Interface Builder to style the modal view and dimming view. Also configure the presentation and dismissal animations.
open class AnimatableModalViewController: UIViewController, PresentationDesignable {
// MARK: - AnimatablePresentationController
public var contextFrameForPresentation: CGRect? {
didSet {
presenter?.presentationConfiguration?.contextFrameForPresentation = contextFrameForPresentation
}
}
@IBInspectable var _presentationAnimationType: String? {
didSet {
if let animationType = PresentationAnimationType(string: _presentationAnimationType) {
presentationAnimationType = animationType
}
}
}
public var presentationAnimationType: PresentationAnimationType = .cover(from: .bottom) {
didSet {
if oldValue.stringValue != presentationAnimationType.stringValue {
configurePresenter()
}
}
}
@IBInspectable var _dismissalAnimationType: String? {
didSet {
if let animationType = PresentationAnimationType(string: _presentationAnimationType) {
dismissalAnimationType = animationType
}
}
}
public var dismissalAnimationType: PresentationAnimationType = .cover(from: .bottom) {
didSet {
if oldValue.stringValue != dismissalAnimationType.stringValue {
configurePresenter()
}
}
}
@IBInspectable public var transitionDuration: Double = .nan {
didSet {
presenter?.transitionDuration = transitionDuration
}
}
@IBInspectable var _modalPosition: String? {
didSet {
modalPosition = PresentationModalPosition(string: _modalPosition ?? "")
}
}
public var modalPosition: PresentationModalPosition = .center {
didSet {
presenter?.presentationConfiguration?.modalPosition = modalPosition
}
}
@IBInspectable var _modalWidth: String? {
didSet {
let modalWidth = PresentationModalSize(string: _modalWidth) ?? .half
modalSize = (modalWidth, modalSize.height)
}
}
@IBInspectable var _modalHeight: String? {
didSet {
let modalHeight = PresentationModalSize(string: _modalHeight) ?? .half
modalSize = (modalSize.width, modalHeight)
}
}
public var modalSize: ModalSize = (.half, .half) {
didSet {
presenter?.presentationConfiguration?.modalSize = modalSize
}
}
@IBInspectable public var cornerRadius: CGFloat = .nan {
didSet {
presenter?.presentationConfiguration?.cornerRadius = cornerRadius
}
}
@IBInspectable public var dismissOnTap: Bool = true {
didSet {
presenter?.presentationConfiguration?.dismissOnTap = dismissOnTap
}
}
@IBInspectable public var backgroundColor: UIColor = .black {
didSet {
presenter?.presentationConfiguration?.backgroundColor = backgroundColor
}
}
@IBInspectable public var opacity: CGFloat = 0.7 {
didSet {
presenter?.presentationConfiguration?.opacity = opacity
}
}
/// The blur effect style of the dimming view. If use this property, `backgroundColor` and `opacity` are ignored.
open var blurEffectStyle: UIBlurEffectStyle? {
didSet {
presenter?.presentationConfiguration?.blurEffectStyle = blurEffectStyle
}
}
@IBInspectable var _blurEffectStyle: String? {
didSet {
blurEffectStyle = UIBlurEffectStyle(string: _blurEffectStyle)
}
}
@IBInspectable public var blurOpacity: CGFloat = .nan {
didSet {
presenter?.presentationConfiguration?.blurOpacity = blurOpacity
}
}
@IBInspectable public var shadowColor: UIColor? {
didSet {
presenter?.presentationConfiguration?.shadowColor = shadowColor
}
}
@IBInspectable public var shadowRadius: CGFloat = 0.7 {
didSet {
presenter?.presentationConfiguration?.shadowRadius = shadowRadius
}
}
@IBInspectable public var shadowOpacity: CGFloat = CGFloat.nan {
didSet {
presenter?.presentationConfiguration?.shadowOpacity = shadowOpacity
}
}
@IBInspectable public var shadowOffset: CGPoint = .zero {
didSet {
presenter?.presentationConfiguration?.shadowOffset = shadowOffset
}
}
@IBInspectable var _keyboardTranslation: String = "" {
didSet {
keyboardTranslation = ModalKeyboardTranslation(string: _keyboardTranslation) ?? .none
}
}
public var keyboardTranslation: ModalKeyboardTranslation = .none {
didSet {
presenter?.presentationConfiguration?.keyboardTranslation = keyboardTranslation
}
}
public var presenter: PresentationPresenter?
// MARK: Life cycle
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
configurePresenter()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configurePresenter()
}
// MARK: Life cycle
override open func viewDidLoad() {
super.viewDidLoad()
}
open override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
configureDismissalTransition()
}
}
| mit | ce75f0dc24d29350fd10428d30ed55cd | 28.214286 | 278 | 0.709611 | 5.097795 | false | true | false | false |
IGRSoft/IGRPhotoTweaks | IGRPhotoTweaks/Constants/IGRPhotoTweakConstants.swift | 1 | 724 | //
// IGRPhotoTweakConstants.swift
// IGRPhotoTweaks
//
// Created by Vitalii Parovishnyk on 2/6/17.
// Copyright © 2017 IGR Software. All rights reserved.
//
import UIKit
enum CropCornerType : Int {
case upperLeft
case upperRight
case lowerRight
case lowerLeft
}
let kCropLinesCount: Int = 2
let kGridLinesCount: Int = 8
let kCropViewHotArea: CGFloat = 40.0
let kMaximumCanvasWidthRatio: CGFloat = 0.9
let kMaximumCanvasHeightRatio: CGFloat = 0.8
let kCanvasHeaderHeigth: CGFloat = 100.0
let kCropViewLineWidth: CGFloat = 2.0
let kCropViewCornerWidth: CGFloat = 2.0
let kCropViewCornerLength: CGFloat = 22.0
let kAnimationDuration: TimeInterval = 0.25
| mit | 7c908b195c76791fdef22eef2644b2a6 | 21.59375 | 55 | 0.70816 | 3.509709 | false | false | false | false |
zmian/xcore.swift | Sources/Xcore/Cocoa/Components/HUD/HUD.swift | 1 | 15646 | //
// Xcore
// Copyright © 2019 Xcore
// MIT license, see LICENSE file for details
//
import UIKit
/// A base class to create a HUD that sets up blank canvas that can be
/// customized by subclasses to show anything in a fullscreen window.
open class HUD: Appliable {
public private(set) var isHidden = true
private var isTemporarilySuppressed = false
private let window: UIWindow
private lazy var viewController = ViewController().apply {
$0.backgroundColor = appearance?.backgroundColor ?? backgroundColor
}
public var view: UIView {
viewController.view
}
/// The default value is `.white`.
open var backgroundColor: UIColor = .white {
didSet {
viewController.backgroundColor = backgroundColor
}
}
/// The default value is `.normal`.
open var duration: Duration = .default
/// The position of the window in the z-axis.
///
/// Window levels provide a relative grouping of windows along the z-axis. All
/// windows assigned to the same window level appear in front of (or behind) all
/// windows assigned to a different window level. The ordering of windows within
/// a given window level is not guaranteed.
///
/// The default value is `.top`.
open var windowLevel: UIWindow.Level {
get { window.windowLevel }
set { setWindowLevel(newValue, animated: false) }
}
/// A succinct label that identifies the HUD window.
open var windowLabel: String? {
get { window.accessibilityLabel }
set { window.accessibilityLabel = newValue }
}
public convenience init() {
self.init(frame: nil)
}
public init(frame: CGRect? = nil) {
if let frame = frame {
window = .init(frame: frame)
} else if let windowScene = UIApplication.sharedOrNil?.firstWindowScene {
window = .init(windowScene: windowScene)
} else {
window = .init(frame: UIScreen.main.bounds)
}
commonInit()
}
private func commonInit() {
window.accessibilityLabel = "HUD"
window.backgroundColor = .clear
window.rootViewController = viewController
window.accessibilityViewIsModal = true
}
private func setDefaultWindowLevel() {
windowLevel = .topMost
appearance?.adjustWindowAttributes?(window)
}
private lazy var adjustWindowAttributes: ((_ window: UIWindow) -> Void)? = { [weak self] _ in
self?.setDefaultWindowLevel()
}
open func setWindowLevel(_ level: UIWindow.Level, animated: Bool) {
guard animated, window.windowLevel != level else {
window.windowLevel = level
return
}
UIView.animate(withDuration: duration.hide) {
self.view.alpha = 0
} completion: { _ in
self.window.windowLevel = level
self.view.alpha = 1
}
}
/// A closure to adjust window attributes (e.g., level or make it key) so this
/// closure is displayed appropriately.
///
/// For example, you can adjust the window level so this HUD is always shown
/// behind the passcode screen to ensure that this HUD is not shown before user
/// is fully authorized.
///
/// - Note: By default, window level is set so it appears on the top of the
/// currently visible window.
open func adjustWindowAttributes(_ callback: @escaping (_ window: UIWindow) -> Void) {
adjustWindowAttributes = { [weak self] window in
self?.setDefaultWindowLevel()
callback(window)
}
}
private func setNeedsStatusBarAppearanceUpdate() {
switch preferredStatusBarStyle {
case let .style(value):
viewController.statusBarStyle = value
case .inherit:
let value = UIApplication.sharedOrNil?.firstSceneKeyWindow?.topViewController?.preferredStatusBarStyle
viewController.statusBarStyle = value ?? .default
}
}
/// A property to set status bar style when HUD is displayed.
///
/// The default value is `.default`.
open var preferredStatusBarStyle: StatusBarAppearance = .default
/// Adds a view to the end of the receiver’s list of subviews.
///
/// This method establishes a strong reference to view and sets its next
/// responder to the receiver, which is its new `superview`.
///
/// Views can have only one `superview`. If view already has a `superview` and
/// that view is not the receiver, this method removes the previous `superview`
/// before making the receiver its new `superview`.
///
/// - Parameter view: The view to be added. After being added, this view appears
/// on top of any other subviews.
open func add(_ view: UIView) {
self.view.addSubview(view)
}
/// This method creates a parent-child relationship between the hud view
/// controller and the object in the `viewController` parameter. This
/// relationship is necessary when embedding the child view controller’s view
/// into the current view controller’s content. If the new child view controller
/// is already the child of a container view controller, it is removed from that
/// container before being added.
///
/// This method is only intended to be called by an implementation of a custom
/// container view controller. If you override this method, you must call super
/// in your implementation.
///
/// - Parameter viewController: The view controller to be added as a child.
open func add(_ viewController: UIViewController) {
self.viewController.addViewController(viewController, enableConstraints: true)
}
/// Presents a view controller modally.
///
/// In a horizontally regular environment, the view controller is presented in
/// the style specified by the `modalPresentationStyle` property. In a
/// horizontally compact environment, the view controller is presented full
/// screen by default. If you associate an adaptive delegate with the
/// presentation controller associated with the object in
/// `viewControllerToPresent`, you can modify the presentation style
/// dynamically.
///
/// The object on which you call this method may not always be the one that
/// handles the presentation. Each presentation style has different rules
/// governing its behavior. For example, a full-screen presentation must be made
/// by a view controller that itself covers the entire screen. If the current
/// view controller is unable to fulfill a request, it forwards the request up
/// the view controller hierarchy to its nearest parent, which can then handle
/// or forward the request.
///
/// Before displaying the view controller, this method resizes the presented
/// view controller's view based on the presentation style. For most
/// presentation styles, the resulting view is then animated onscreen using the
/// transition style in the `modalTransitionStyle` property of the presented
/// view controller. For custom presentations, the view is animated onscreen
/// using the presented view controller’s transitioning delegate. For current
/// context presentations, the view may be animated onscreen using the current
/// view controller’s transition style.
///
/// The completion handler is called after the `viewDidAppear(_:)` method is
/// called on the presented view controller.
///
/// - Parameters:
/// - viewControllerToPresent: The view controller to display over the current
/// view controller’s content.
/// - flag: Pass `true` to animate the presentation; otherwise, pass `false`.
/// - completion: The block to execute after the presentation finishes. This
/// block has no return value and takes no parameters. You may specify `nil`
/// for this parameter.
open func present(_ viewControllerToPresent: UIViewController, animated flag: Bool, _ completion: (() -> Void)? = nil) {
show(animated: false) { [weak self, unowned viewControllerToPresent] in
self?.viewController.present(viewControllerToPresent, animated: flag, completion: completion)
}
}
private func _setHidden(_ hide: Bool, animated: Bool, _ completion: (() -> Void)?) {
guard isHidden != hide else {
completion?()
return
}
// If `hide` is `false` and `isTemporarilySuppressed` flag is `true`. Then, call
// completion handler and return to respect `isTemporarilySuppressed` flag.
if !hide, isTemporarilySuppressed {
isTemporarilySuppressed = false
completion?()
return
}
let duration = hide ? self.duration.hide : self.duration.show
isHidden = hide
if hide {
guard animated else {
view.alpha = 0
window.isHidden = true
completion?()
return
}
UIView.animate(withDuration: duration) {
self.view.alpha = 0
} completion: { _ in
self.window.isHidden = true
completion?()
}
} else {
adjustWindowAttributes?(window)
setNeedsStatusBarAppearanceUpdate()
window.isHidden = false
guard animated else {
view.alpha = 1
completion?()
return
}
view.alpha = 0
UIView.animate(withDuration: duration) {
self.view.alpha = 1
} completion: { _ in
completion?()
}
}
}
private func setHidden(_ hide: Bool, animated: Bool, _ completion: (() -> Void)?) {
guard let presentedViewController = viewController.presentedViewController else {
return _setHidden(hide, animated: animated, completion)
}
presentedViewController.dismiss(animated: animated) { [weak self] in
self?._setHidden(true, animated: false, completion)
}
}
private func setHidden(_ hide: Bool, delay delayDuration: TimeInterval, animated: Bool, _ completion: (() -> Void)?) {
guard delayDuration > 0 else {
return setHidden(hide, animated: animated, completion)
}
Timer.after(delayDuration) { [weak self] in
self?.setHidden(hide, animated: animated, completion)
}
}
open func show(delay delayDuration: TimeInterval = 0, animated: Bool = true, _ completion: (() -> Void)? = nil) {
setHidden(false, delay: delayDuration, animated: animated, completion)
}
open func hide(delay delayDuration: TimeInterval = 0, animated: Bool = true, _ completion: (() -> Void)? = nil) {
setHidden(true, delay: delayDuration, animated: animated, completion)
}
/// Suppress next call to `show(delay:animated:_:)` method.
///
/// Consider a scenario where you have a splash screen that shows up whenever
/// app resign active state. Later on, you want to request Push Notifications
/// permission, this will cause the splash screen to appear. However, if you
/// call `suppressTemporarily()` on the splash screen HUD before asking for
/// permission then splash screen is suppressed when system permission dialog
/// appears.
open func suppressTemporarily() {
isTemporarilySuppressed = true
}
}
// MARK: - StatusBarAppearance
extension HUD {
public enum StatusBarAppearance {
/// Specifies whether HUD inherits status bar style from the presenting view
/// controller.
case inherit
/// Specifies HUD status bar style.
case style(UIStatusBarStyle)
/// A dark status bar, intended for use on light backgrounds.
public static var `default`: Self {
.style(.default)
}
/// A light status bar, intended for use on dark backgrounds.
public static var lightContent: Self {
.style(.lightContent)
}
}
}
// MARK: - Duration
extension HUD {
public struct Duration: ExpressibleByFloatLiteral, ExpressibleByIntegerLiteral {
public let show: TimeInterval
public let hide: TimeInterval
public init(floatLiteral value: FloatLiteralType) {
self.init(TimeInterval(value))
}
public init(integerLiteral value: IntegerLiteralType) {
self.init(TimeInterval(value))
}
public init(_ duration: TimeInterval) {
self.show = duration
self.hide = duration
}
public init(show: TimeInterval, hide: TimeInterval) {
self.show = show
self.hide = hide
}
public static var `default`: Self {
.init(.default)
}
}
}
// MARK: - ViewController
extension HUD {
private final class ViewController: UIViewController {
var backgroundColor: UIColor? {
didSet {
guard isViewLoaded else {
return
}
view.backgroundColor = backgroundColor
}
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = backgroundColor
}
override var preferredStatusBarStyle: UIStatusBarStyle {
statusBarStyle ?? .default
}
}
}
// MARK: - Appearance
extension HUD {
/// This configuration exists to allow some of the properties to be configured
/// to match app's appearance style. The `UIAppearance` protocol doesn't work
/// when the stored properites are set using associated object.
///
/// **Usage**
///
/// ```swift
/// HUD.appearance().backgroundColor = .gray
/// LaunchScreen.View.appearance().backgroundColor = .blue
/// ```
public final class Appearance: Appliable {
public var backgroundColor: UIColor = .white
fileprivate var adjustWindowAttributes: ((_ window: UIWindow) -> Void)?
/// A closure to adjust window attributes (e.g., level or make it key) so this
/// HUD is displayed appropriately.
///
/// For example, you can adjust the window level so this HUD is always shown
/// behind the passcode screen to ensure that this HUD is not shown before user
/// is fully authorized.
///
/// - Note: By default, window level is set so it appears on the top of the
/// currently visible window.
public func adjustWindowAttributes(_ callback: @escaping (_ window: UIWindow) -> Void) {
adjustWindowAttributes = callback
}
}
private static var appearanceStorage: [String: Appearance] = [:]
public class func appearance() -> Appearance {
let instanceName = name(of: self)
if let proxy = appearanceStorage[instanceName] {
return proxy
}
let proxy = Appearance()
appearanceStorage[instanceName] = proxy
return proxy
}
private var appearance: Appearance? {
let instanceName = name(of: self)
// Return the type proxy if exists.
if let proxy = HUD.appearanceStorage[instanceName] {
return proxy
}
let baseInstanceName = name(of: HUD.self)
// Return the base type proxy if exists.
return HUD.appearanceStorage[baseInstanceName]
}
}
| mit | 97ba6fb3c76af60bade067409d5d42ba | 35.266821 | 124 | 0.629006 | 5.157044 | false | false | false | false |
xiangpengzhu/QuickStart | QuickStart/UIKit+Extension/UIView+Extension.swift | 1 | 989 | //
// UIView+Extension.swift
// ShuFaLibrary
//
// Created by zhu on 16/4/2.
// Copyright © 2016年 xpz. All rights reserved.
//
import UIKit
extension UIView {
public var screenshotImage: UIImage? {
var image: UIImage?
UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.isOpaque, 0.0)
if let context = UIGraphicsGetCurrentContext() {
self.layer.render(in: context)
image = UIGraphicsGetImageFromCurrentImageContext()
}
UIGraphicsEndImageContext()
return image
}
public var currentViewController: UIViewController? {
var next = self.superview
while next != nil {
let responder = next?.next
if let responder = responder , responder is UIViewController {
return responder as? UIViewController
}
next = next?.superview
}
return nil
}
}
| gpl-3.0 | 28ab7b5ad75fba6263f3fd939310f1d8 | 24.282051 | 84 | 0.58215 | 5.32973 | false | false | false | false |
kstaring/swift | validation-test/compiler_crashers_fixed/00519-void.swift | 11 | 651 | // 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
import Foundation
var d {
init(f, b : NSObject {
}
struct B<T where H.c: NSObject {
deinit {
print() -> (f: d where I) {
e = {
}
}
protocol e = e: C {
}
class A {
return g<T : AnyObject, f: A {
let c, AnyObject.c = D> String = B<(")
}
}
typealias e = F>(self
| apache-2.0 | 5e140cc30bb488ac21ab4f01ce0e90c6 | 24.038462 | 78 | 0.683564 | 3.206897 | false | false | false | false |
tensorflow/swift-apis | Sources/TensorFlow/Epochs/NonuniformTrainingEpochs.swift | 1 | 8746 | // Copyright 2020 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/// An infinite sequence of collections of sample batches suitable for training
/// a DNN when samples are not uniformly sized.
///
/// - Parameter `Samples`: the type of collection from which samples will be
/// drawn.
/// - Parameter `Entropy`: a source of entropy used to randomize sample order in
/// each epoch. See the `init` documentation for details.
///
/// The batches in each epoch:
/// - all have exactly the same number of samples.
/// - are formed from samples of similar size.
/// - start with a batch whose maximum sample size is the maximum size over all
/// samples used in the epoch.
public final class NonuniformTrainingEpochs<
Samples: Collection,
Entropy: RandomNumberGenerator
>: Sequence, IteratorProtocol {
private let samples: Samples
/// The number of samples in a batch.
let batchSize: Int
/// The ordering of samples in the current epoch.
private var sampleOrder: [Samples.Index]
/// The maximal number of sample batches whose samples will be sorted by size.
private let batchesPerSort: Int
/// A sorting predicate used to group samples of similar size.
private let areInAscendingSizeOrder: (Samples.Element, Samples.Element) -> Bool
// TODO: Figure out how to handle non-threasafe PRNGs with a parallel shuffle
// algorithm.
/// A source of entropy for shuffling samples.
private var entropy: Entropy
/// Creates an instance drawing samples from `samples` into batches of size
/// `batchSize`.
///
/// - Parameters:
/// - entropy: a source of randomness used to shuffle sample ordering. It
/// will be stored in `self`, so if it is only pseudorandom and has value
/// semantics, the sequence of epochs is determinstic and not dependent on
/// other operations.
/// - batchesPerSort: the number of batches across which to group sample
/// sizes similarly, or `nil` to indicate that the implementation should
/// choose a number. Choosing too high can destroy the effects of sample
/// shuffling in many training schemes, leading to poor results. Choosing
/// too low will reduce the similarity of sizes in a given batch, leading
/// to inefficiency.
/// - areInAscendingSizeOrder: a predicate that returns `true` iff the size
/// of the first parameter is less than that of the second.
public init(
samples: Samples,
batchSize: Int,
entropy: Entropy,
batchesPerSort: Int? = nil,
areInAscendingSizeOrder:
@escaping (Samples.Element, Samples.Element) -> Bool
) {
self.samples = samples
self.batchSize = batchSize
sampleOrder = Array(samples.indices)
let batchCount = sampleOrder.count / batchSize
self.entropy = entropy
self.batchesPerSort = batchesPerSort ?? Swift.max(2, batchCount / 100)
self.areInAscendingSizeOrder = areInAscendingSizeOrder
}
/// The type of each epoch, a collection of batches of samples.
public typealias Element = Slices<
Sampling<Samples, Array<Samples.Index>.SubSequence>
>
/// Returns the next epoch in sequence.
public func next() -> Element? {
let remainder = sampleOrder.count % batchSize
sampleOrder.withUnsafeMutableBufferPointer { order in
// TODO: use a parallel shuffle like mergeshuffle
// (http://ceur-ws.org/Vol-2113/paper3.pdf)
order.shuffle(using: &entropy)
// The indices of samples used in this epoch
var epochSampleOrder = order.dropLast(remainder)
// The index in order of the largest sample.
let leader = epochSampleOrder.indices.max {
areInAscendingSizeOrder(
samples[epochSampleOrder[$0]], samples[epochSampleOrder[$1]])
}!
// The last position in epochSamples that will end up in the first batch.
let lastOfFirstBatch = epochSampleOrder.index(atOffset: batchSize - 1)
if leader > lastOfFirstBatch {
epochSampleOrder[lastOfFirstBatch...leader]
.rotate(shiftingToStart: leader)
}
// The regions of usedOrder to be sorted by descending batch size
let megabatches =
epochSampleOrder
.inBatches(of: batchSize * batchesPerSort)
for var megabatch in megabatches {
// TODO: fully sorting is overkill; we should use introselect here.
// Also, parallelize.
megabatch.sort { areInAscendingSizeOrder(samples[$1], samples[$0]) }
}
}
return samples.sampled(at: sampleOrder.dropLast(remainder))
.inBatches(of: batchSize)
}
}
extension NonuniformTrainingEpochs
where Entropy == SystemRandomNumberGenerator {
/// Creates an instance drawing samples from `samples` into batches of size
/// `batchSize`.
///
/// - Parameters:
/// - batchesPerSort: the number of batches across which to group sample
/// sizes similarly, or `nil` to indicate that the implementation should
/// choose a number. Choosing too high can destroy the effects of sample
/// shuffling in many training schemes, leading to poor results. Choosing
/// too low will reduce the similarity of sizes in a given batch, leading
/// to inefficiency.
/// - areInAscendingSizeOrder: a predicate that returns `true` iff the size
/// of the first parameter is less than that of the second.
public convenience init(
samples: Samples,
batchSize: Int,
batchesPerSort: Int? = nil,
areInAscendingSizeOrder:
@escaping (Samples.Element, Samples.Element) -> Bool
) {
self.init(
samples: samples,
batchSize: batchSize,
entropy: SystemRandomNumberGenerator(),
batchesPerSort: batchesPerSort,
areInAscendingSizeOrder: areInAscendingSizeOrder
)
}
}
/// A collection of batches suitable for inference, drawing samples from
/// `samples` into batches of `batchSize`.
public typealias NonuniformInferenceBatches<Samples: Collection> = Slices<
Sampling<Samples, [Samples.Index]>
>
/// An implementation detail used to work around the fact that Swift can't
/// express a generic constraint that some type must be an instance of
/// `Sampling`.
public protocol SamplingProtocol: Collection {
associatedtype Samples: Collection
associatedtype Selection: Collection where Selection.Element == Samples.Index
/// Creates an instance from `base` and `selection`.
init(base: Samples, selection: Selection)
}
extension Sampling: SamplingProtocol {}
extension Slices
// This constraint matches when Self == NonuniformInferenceBatches<T>.
where Base: SamplingProtocol, Base.Selection == [Base.Samples.Index] {
/// Creates an instance containing batches of `n` elements of `samples` where
/// the size of the largest sample in successive batches is strictly
/// descending.
///
/// - Parameter areInAscendingSizeOrder: returns `true` iff the memory
/// footprint of the first parameter is less than that of the second.
public init(
samples: Base.Samples, batchSize n: Int,
areInAscendingSizeOrder:
@escaping (Base.Samples.Element, Base.Samples.Element) -> Bool
) {
self.init(samples: samples, batchSize: n) {
areInAscendingSizeOrder(samples[$0], samples[$1])
}
}
/// Creates an instance containing batches of `n` elements of `samples` where
/// the size of the largest sample in successive batches is strictly
/// descending, with batch size determined by sample index.
///
/// This initializer doesn't read elements from `samples`, so will preserve
/// any underlying laziness as long as `samplesAreInAscendingSizeOrder`
/// doesn't access them.
///
/// - Parameter samplesAreInAscendingSizeOrder: returns `true` iff the memory
/// footprint of the sample at the first parameter is less than that of the
/// sample at the second parameter.
///
public init(
samples: Base.Samples, batchSize n: Int,
samplesAreInAscendingSizeOrder:
@escaping (Base.Samples.Index, Base.Samples.Index) -> Bool
) {
let sampleOrder = samples.indices
.sorted { samplesAreInAscendingSizeOrder($1, $0) }
self = Base(base: samples, selection: sampleOrder).inBatches(of: n)
}
// TODO: Test the laziness of the result.
}
| apache-2.0 | def506eb9d4fe35a70821a4b323f2c1d | 38.936073 | 81 | 0.708438 | 4.340447 | false | false | false | false |
natecook1000/swift | test/Inputs/resilient_struct.swift | 4 | 1733 | // Fixed-layout struct
@_fixed_layout public struct Point {
public var x: Int // read-write stored property
public let y: Int // read-only stored property
public init(x: Int, y: Int) {
self.x = x
self.y = y
}
public func method() {}
public mutating func mutantMethod() {}
}
// Resilient-layout struct
public struct Size {
public var w: Int // should have getter and setter
public let h: Int // getter only
public init(w: Int, h: Int) {
self.w = w
self.h = h
}
public func method() {}
public mutating func mutantMethod() {}
}
// Fixed-layout struct with resilient members
@_fixed_layout public struct Rectangle {
public let p: Point
public let s: Size
public let color: Int
public init(p: Point, s: Size, color: Int) {
self.p = p
self.s = s
self.color = color
}
}
// More complicated resilient structs for runtime tests
public struct ResilientBool {
public let b: Bool
public init(b: Bool) {
self.b = b
}
}
public struct ResilientInt {
public let i: Int
public init(i: Int) {
self.i = i
}
}
public struct ResilientDouble {
public let d: Double
public init(d: Double) {
self.d = d
}
}
@_fixed_layout public struct ResilientLayoutRuntimeTest {
public let b1: ResilientBool
public let i: ResilientInt
public let b2: ResilientBool
public let d: ResilientDouble
public init(b1: ResilientBool, i: ResilientInt, b2: ResilientBool, d: ResilientDouble) {
self.b1 = b1
self.i = i
self.b2 = b2
self.d = d
}
}
public class Referent {}
public struct ResilientWeakRef {
public weak var ref: Referent?
public init (_ r: Referent) {
ref = r
}
}
public struct ResilientRef {
public var r: Referent
}
| apache-2.0 | 561ce1ca53ee9b540b3719d626a2cc76 | 17.634409 | 90 | 0.658973 | 3.55123 | false | false | false | false |
danielmartin/swift | stdlib/public/core/NormalizedCodeUnitIterator.swift | 1 | 17240 | //===--- StringNormalization.swift ----------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
extension _Normalization {
internal typealias _SegmentOutputBuffer = _FixedArray16<UInt16>
}
//
// Pointer casting helpers
//
@inline(__always)
private func _unsafeMutableBufferPointerCast<T, U>(
_ ptr: UnsafeMutablePointer<T>,
_ count: Int,
to: U.Type = U.self
) -> UnsafeMutableBufferPointer<U> {
return UnsafeMutableBufferPointer(
start: UnsafeMutableRawPointer(ptr).assumingMemoryBound(to: U.self),
count: count
)
}
@inline(__always)
private func _unsafeBufferPointerCast<T, U>(
_ ptr: UnsafePointer<T>,
_ count: Int,
to: U.Type = U.self
) -> UnsafeBufferPointer<U> {
return UnsafeBufferPointer(
start: UnsafeRawPointer(ptr).assumingMemoryBound(to: U.self),
count: count
)
}
internal func _castOutputBuffer(
_ ptr: UnsafeMutablePointer<_Normalization._SegmentOutputBuffer>,
endingAt endIdx: Int = _Normalization._SegmentOutputBuffer.capacity
) -> UnsafeMutableBufferPointer<UInt16> {
let bufPtr: UnsafeMutableBufferPointer<UInt16> =
_unsafeMutableBufferPointerCast(
ptr, _Normalization._SegmentOutputBuffer.capacity)
return UnsafeMutableBufferPointer<UInt16>(rebasing: bufPtr[..<endIdx])
}
internal func _castOutputBuffer(
_ ptr: UnsafePointer<_Normalization._SegmentOutputBuffer>,
endingAt endIdx: Int = _Normalization._SegmentOutputBuffer.capacity
) -> UnsafeBufferPointer<UInt16> {
let bufPtr: UnsafeBufferPointer<UInt16> =
_unsafeBufferPointerCast(
ptr, _Normalization._SegmentOutputBuffer.capacity)
return UnsafeBufferPointer<UInt16>(rebasing: bufPtr[..<endIdx])
}
extension _StringGuts {
internal func foreignHasNormalizationBoundary(
before index: String.Index
) -> Bool {
let offset = index.encodedOffset
if offset == 0 || offset == count {
return true
}
let scalar = foreignErrorCorrectedScalar(startingAt: index).0
return scalar._hasNormalizationBoundaryBefore
}
}
extension UnsafeBufferPointer where Element == UInt8 {
internal func hasNormalizationBoundary(before index: Int) -> Bool {
if index == 0 || index == count {
return true
}
assert(!_isContinuation(self[_unchecked: index]))
// Sub-300 latiny fast-path
if self[_unchecked: index] < 0xCC { return true }
let cu = _decodeScalar(self, startingAt: index).0
return cu._hasNormalizationBoundaryBefore
}
}
internal struct _NormalizedUTF8CodeUnitIterator: IteratorProtocol {
internal typealias CodeUnit = UInt8
var utf16Iterator: _NormalizedUTF16CodeUnitIterator
var utf8Buffer = _FixedArray4<CodeUnit>(allZeros:())
var bufferIndex = 0
var bufferCount = 0
internal init(foreign guts: _StringGuts, range: Range<String.Index>) {
_internalInvariant(guts.isForeign)
utf16Iterator = _NormalizedUTF16CodeUnitIterator(guts, range)
}
internal init(_ buffer: UnsafeBufferPointer<UInt8>, range: Range<Int>) {
utf16Iterator = _NormalizedUTF16CodeUnitIterator(buffer, range)
}
internal mutating func next() -> UInt8? {
if bufferIndex == bufferCount {
bufferIndex = 0
bufferCount = 0
guard let cu = utf16Iterator.next() else {
return nil
}
var array = _FixedArray2<UInt16>()
array.append(cu)
if _isSurrogate(cu) {
guard let nextCU = utf16Iterator.next() else {
fatalError("unpaired surrogate")
}
array.append(nextCU)
}
let iterator = array.makeIterator()
_ = transcode(iterator, from: UTF16.self, to: UTF8.self,
stoppingOnError: false) { codeUnit in
_internalInvariant(bufferCount < 4)
_internalInvariant(bufferIndex < 4)
utf8Buffer[bufferIndex] = codeUnit
bufferIndex += 1
bufferCount += 1
}
bufferIndex = 0
}
defer { bufferIndex += 1 }
return utf8Buffer[bufferIndex]
}
}
extension _NormalizedUTF8CodeUnitIterator: Sequence { }
internal
struct _NormalizedUTF16CodeUnitIterator: IteratorProtocol {
internal typealias CodeUnit = UInt16
var segmentBuffer = _FixedArray16<CodeUnit>(allZeros:())
var normalizationBuffer = _FixedArray16<CodeUnit>(allZeros:())
var segmentHeapBuffer: [CodeUnit]? = nil
var normalizationHeapBuffer: [CodeUnit]? = nil
var source: _SegmentSource
var segmentBufferIndex = 0
var segmentBufferCount = 0
init(_ guts: _StringGuts, _ range: Range<String.Index>) {
source = _ForeignStringGutsSource(guts, range)
}
init(_ buffer: UnsafeBufferPointer<UInt8>, _ range: Range<Int>) {
source = _UTF8BufferSource(buffer, range)
}
struct _UTF8BufferSource: _SegmentSource {
var remaining: Int {
return range.count - index
}
var isEmpty: Bool {
return remaining <= 0
}
var buffer: UnsafeBufferPointer<UInt8>
var index: Int
var range: Range<Int>
init(_ buffer: UnsafeBufferPointer<UInt8>, _ range: Range<Int>) {
self.buffer = buffer
self.range = range
index = range.lowerBound
}
mutating func tryFill(
into output: UnsafeMutableBufferPointer<UInt16>
) -> Int? {
var outputIndex = 0
let originalIndex = index
repeat {
guard !isEmpty else {
break
}
guard outputIndex < output.count else {
//The buff isn't big enough for the current segment
index = originalIndex
return nil
}
let (cu, len) = _decodeScalar(buffer, startingAt: index)
let utf16 = cu.utf16
switch utf16.count {
case 1:
output[outputIndex] = utf16[0]
outputIndex += 1
case 2:
if outputIndex+1 >= output.count {
index = originalIndex
return nil
}
output[outputIndex] = utf16[0]
output[outputIndex+1] = utf16[1]
outputIndex += 2
default:
_conditionallyUnreachable()
}
index = index &+ len
} while !buffer.hasNormalizationBoundary(before: index)
return outputIndex
}
}
struct _ForeignStringGutsSource: _SegmentSource {
var remaining: Int {
return range.upperBound.encodedOffset - index.encodedOffset
}
var isEmpty: Bool {
return index >= range.upperBound
}
var guts: _StringGuts
var index: String.Index
var range: Range<String.Index>
init(_ guts: _StringGuts, _ range: Range<String.Index>) {
self.guts = guts
self.range = range
index = range.lowerBound
}
mutating func tryFill(
into output: UnsafeMutableBufferPointer<UInt16>
) -> Int? {
var outputIndex = 0
let originalIndex = index
repeat {
guard index != range.upperBound else {
break
}
guard outputIndex < output.count else {
//The buffer isn't big enough for the current segment
index = originalIndex
return nil
}
let (scalar, len) = guts.foreignErrorCorrectedScalar(startingAt: index)
output[outputIndex] = scalar.utf16[0]
outputIndex += 1
index = index.nextEncoded
if len == 2 {
output[outputIndex] = scalar.utf16[1]
outputIndex += 1
index = index.nextEncoded
}
} while !guts.foreignHasNormalizationBoundary(before: index)
return outputIndex
}
}
mutating func next() -> UInt16? {
if segmentBufferCount == segmentBufferIndex {
if source.isEmpty {
return nil
}
segmentBuffer = _FixedArray16<CodeUnit>(allZeros:())
segmentBufferCount = 0
segmentBufferIndex = 0
}
if segmentBufferCount == 0 {
segmentBufferCount = normalizeFromSource()
}
guard segmentBufferIndex < segmentBufferCount else { return nil }
defer { segmentBufferIndex += 1 }
if _slowPath(segmentHeapBuffer != nil) {
return segmentHeapBuffer![segmentBufferIndex]
}
return segmentBuffer[segmentBufferIndex]
}
mutating func normalizeFromSource() -> Int {
if segmentHeapBuffer == nil,
let filled = source.tryFill(into: &normalizationBuffer)
{
if let count = _tryNormalize(
_castOutputBuffer(&normalizationBuffer,
endingAt: filled),
into: &segmentBuffer
) {
return count
}
return normalizeWithHeapBuffers(filled)
}
return normalizeWithHeapBuffers()
}
//This handles normalization from an intermediate buffer to the heap segment
//buffer. This can get called in 3 situations:
//* We've already transitioned to heap buffers
//* We attempted to fill the pre-normal stack buffer but there was not enough
//. room, so we need to promote both and then attempt the fill again.
//* The fill for the stack buffer succeeded, but the normalization didn't. In
// this case, we want to first copy the contents of the stack buffer that
// we filled into the new heap buffer. The stackBufferCount
// parameter signals that we need to do this copy, thus skipping the fill
// that we would normally do before normalization.
mutating func normalizeWithHeapBuffers(
_ stackBufferCount: Int? = nil
) -> Int {
if segmentHeapBuffer == nil {
_internalInvariant(normalizationHeapBuffer == nil)
let preFilledBufferCount = stackBufferCount ?? 0
let size = (source.remaining + preFilledBufferCount)
* _Normalization._maxNFCExpansionFactor
segmentHeapBuffer = Array(repeating: 0, count: size)
normalizationHeapBuffer = Array(repeating:0, count: size)
for i in 0..<preFilledBufferCount {
normalizationHeapBuffer![i] = normalizationBuffer[i]
}
}
guard let count = normalizationHeapBuffer!.withUnsafeMutableBufferPointer({
(normalizationHeapBufferPtr) -> Int? in
guard let filled = stackBufferCount ??
source.tryFill(into: normalizationHeapBufferPtr)
else {
fatalError("Invariant broken, buffer should have space")
}
return segmentHeapBuffer!.withUnsafeMutableBufferPointer {
(segmentHeapBufferPtr) -> Int? in
return _tryNormalize(
UnsafeBufferPointer(rebasing: normalizationHeapBufferPtr[..<filled]),
into: segmentHeapBufferPtr
)
}
}) else {
fatalError("Invariant broken, overflow buffer should have space")
}
return count
}
}
protocol _SegmentSource {
var remaining: Int { get }
var isEmpty: Bool { get }
mutating func tryFill(into: UnsafeMutableBufferPointer<UInt16>) -> Int?
}
extension _SegmentSource {
mutating func tryFill(
into output: UnsafeMutablePointer<_Normalization._SegmentOutputBuffer>
) -> Int? {
return tryFill(into: _castOutputBuffer(output))
}
}
internal struct _NormalizedUTF8CodeUnitIterator_2: Sequence, IteratorProtocol {
private var outputBuffer = _SmallBuffer<UInt8>()
private var outputPosition = 0
private var outputBufferCount = 0
private var gutsSlice: _StringGutsSlice
private var readPosition: String.Index
private var _backupIsEmpty = false
internal init(_ sliced: _StringGutsSlice) {
self.gutsSlice = sliced
self.readPosition = self.gutsSlice.range.lowerBound
}
internal mutating func next() -> UInt8? {
return _next()
}
}
extension _NormalizedUTF8CodeUnitIterator_2 {
// The thresdhold we try to stay within while filling. Always leaves enough
// code units at the end to finish a scalar, but not necessarily enough to
// finish a segment.
private var outputBufferThreshold: Int {
return outputBuffer.capacity - 4
}
private var outputBufferEmpty: Bool {
return outputPosition == outputBufferCount
}
private var outputBufferFull: Bool {
return outputBufferCount >= outputBufferThreshold
}
private var inputBufferEmpty: Bool {
return gutsSlice.range.isEmpty
}
}
extension _NormalizedUTF8CodeUnitIterator_2 {
@_effects(releasenone)
private mutating func _next() -> UInt8? {
defer { _fixLifetime(self) }
if _slowPath(outputBufferEmpty) {
if _slowPath(inputBufferEmpty) {
return nil
}
fill()
if _slowPath(outputBufferEmpty) {
//_internalInvariant(inputBufferEmpty)
return nil
}
}
_internalInvariant(!outputBufferEmpty)
_internalInvariant(outputPosition < outputBufferCount)
let result = outputBuffer[outputPosition]
outputPosition &+= 1
return result
}
// Try to fill from the start without using ICU's normalizer. Returns number
// of code units filled in.
@inline(__always)
@_effects(releasenone)
private mutating func fastPathFill() -> (numRead: Int, numWritten: Int) {
// TODO: Additional fast-path: All CCC-ascending NFC_QC segments are NFC
// TODO: Just freakin do normalization and don't bother with ICU
var outputCount = 0
let outputEnd = outputBufferThreshold
var inputCount = 0
let inputEnd = gutsSlice.count
if _fastPath(gutsSlice.isFastUTF8) {
gutsSlice.withFastUTF8 { utf8 in
while inputCount < inputEnd && outputCount < outputEnd {
// TODO: Slightly faster code-unit scan for latiny (<0xCC)
// Check scalar-based fast-paths
let (scalar, len) = _decodeScalar(utf8, startingAt: inputCount)
_internalInvariant(inputCount &+ len <= inputEnd)
if _slowPath(
!utf8.hasNormalizationBoundary(before: inputCount &+ len)
|| !scalar._isNFCStarter
) {
break
}
inputCount &+= len
for cu in UTF8.encode(scalar)._unsafelyUnwrappedUnchecked {
outputBuffer[outputCount] = cu
outputCount &+= 1
}
_internalInvariant(inputCount == outputCount,
"non-normalizing UTF-8 fast path should be 1-to-1 in code units")
}
}
} else { // Foreign
while inputCount < inputEnd && outputCount < outputEnd {
let startIdx = gutsSlice.range.lowerBound.encoded(
offsetBy: inputCount)
let (scalar, len) = gutsSlice.foreignErrorCorrectedScalar(
startingAt: startIdx)
_internalInvariant(inputCount &+ len <= inputEnd)
if _slowPath(
!gutsSlice.foreignHasNormalizationBoundary(
before: startIdx.encoded(offsetBy: len))
|| !scalar._isNFCStarter
) {
break
}
inputCount &+= len
for cu in UTF8.encode(scalar)._unsafelyUnwrappedUnchecked {
outputBuffer[outputCount] = cu
outputCount &+= 1
}
_internalInvariant(inputCount <= outputCount,
"non-normalizing UTF-16 fast path shoule be 1-to-many in code units")
}
}
return (inputCount, outputCount)
}
@_effects(releasenone)
private mutating func fill() {
_internalInvariant(outputBufferEmpty)
let priorInputCount = gutsSlice._offsetRange.count
outputPosition = 0
let (inputCount, outputCount) = fastPathFill()
self.outputBufferCount = outputCount
// Check if we filled in any, and adjust our scanning range appropriately
if inputCount > 0 {
_internalInvariant(outputCount > 0)
gutsSlice._offsetRange = Range(uncheckedBounds: (
gutsSlice._offsetRange.lowerBound + inputCount,
gutsSlice._offsetRange.upperBound))
_internalInvariant(gutsSlice._offsetRange.count >= 0)
return
}
let remaining: Int = gutsSlice.withNFCCodeUnitsIterator {
var nfc = $0
while !outputBufferFull, let cu = nfc.next() {
outputBuffer[outputBufferCount] = cu
outputBufferCount &+= 1
}
return nfc.utf16Iterator.source.remaining
}
if !(outputBufferCount == 0 || remaining < priorInputCount) {
// TODO: _internalInvariant(outputBufferCount == 0 || remaining < priorInputCount)
}
gutsSlice._offsetRange = Range(uncheckedBounds: (
gutsSlice._offsetRange.lowerBound + (priorInputCount - remaining),
gutsSlice._offsetRange.upperBound))
_internalInvariant(outputBufferFull || gutsSlice._offsetRange.isEmpty)
_internalInvariant(gutsSlice._offsetRange.count >= 0)
}
@_effects(readonly)
internal mutating func compare(
with other: _NormalizedUTF8CodeUnitIterator_2,
expecting: _StringComparisonResult
) -> Bool {
var mutableOther = other
for cu in self {
guard let otherCU = mutableOther.next() else {
// We have more code units, therefore we are greater
return false
}
if cu == otherCU { continue }
return expecting == .less ? cu < otherCU : false
}
// We have exhausted our code units. We are less if there's more remaining
return mutableOther.next() == nil ? expecting == .equal : expecting == .less
}
}
| apache-2.0 | 6c5de4aac1ea196bdec6ad793a3c3c88 | 29.730838 | 88 | 0.660905 | 4.583887 | false | false | false | false |
practicalswift/swift | test/stmt/foreach.swift | 5 | 5976 | // RUN: %target-typecheck-verify-swift
// Bad containers and ranges
struct BadContainer1 {
}
func bad_containers_1(bc: BadContainer1) {
for e in bc { } // expected-error{{type 'BadContainer1' does not conform to protocol 'Sequence'}}
}
struct BadContainer2 : Sequence { // expected-error{{type 'BadContainer2' does not conform to protocol 'Sequence'}}
var generate : Int
}
func bad_containers_2(bc: BadContainer2) {
for e in bc { }
}
struct BadContainer3 : Sequence { // expected-error{{type 'BadContainer3' does not conform to protocol 'Sequence'}}
func makeIterator() { } // expected-note{{candidate can not infer 'Iterator' = '()' because '()' is not a nominal type and so can't conform to 'IteratorProtocol'}}
}
func bad_containers_3(bc: BadContainer3) {
for e in bc { }
}
struct BadIterator1 {}
struct BadContainer4 : Sequence { // expected-error{{type 'BadContainer4' does not conform to protocol 'Sequence'}}
typealias Iterator = BadIterator1 // expected-note{{possibly intended match 'BadContainer4.Iterator' (aka 'BadIterator1') does not conform to 'IteratorProtocol'}}
func makeIterator() -> BadIterator1 { }
}
func bad_containers_4(bc: BadContainer4) {
for e in bc { }
}
// Pattern type-checking
struct GoodRange<Int> : Sequence, IteratorProtocol {
typealias Element = Int
func next() -> Int? {}
typealias Iterator = GoodRange<Int>
func makeIterator() -> GoodRange<Int> { return self }
}
struct GoodTupleIterator: Sequence, IteratorProtocol {
typealias Element = (Int, Float)
func next() -> (Int, Float)? {}
typealias Iterator = GoodTupleIterator
func makeIterator() -> GoodTupleIterator {}
}
func patterns(gir: GoodRange<Int>, gtr: GoodTupleIterator) {
var sum : Int
var sumf : Float
for i : Int in gir { sum = sum + i }
for i in gir { sum = sum + i }
for f : Float in gir { sum = sum + f } // expected-error{{'Int' is not convertible to 'Float'}}
for (i, f) : (Int, Float) in gtr { sum = sum + i }
for (i, f) in gtr {
sum = sum + i
sumf = sumf + f
sum = sum + f // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Float'}} expected-note {{expected an argument list of type '(Int, Int)'}}
}
for (i, _) : (Int, Float) in gtr { sum = sum + i }
for (i, _) : (Int, Int) in gtr { sum = sum + i } // expected-error{{'GoodTupleIterator.Element' (aka '(Int, Float)') is not convertible to '(Int, Int)'}}
for (i, f) in gtr {}
}
func slices(i_s: [Int], ias: [[Int]]) {
var sum = 0
for i in i_s { sum = sum + i }
for ia in ias {
for i in ia {
sum = sum + i
}
}
}
func discard_binding() {
for _ in [0] {}
}
struct X<T> {
var value: T
}
struct Gen<T> : IteratorProtocol {
func next() -> T? { return nil }
}
struct Seq<T> : Sequence {
func makeIterator() -> Gen<T> { return Gen() }
}
func getIntSeq() -> Seq<Int> { return Seq() }
func getOvlSeq() -> Seq<Int> { return Seq() } // expected-note{{found this candidate}}
func getOvlSeq() -> Seq<Double> { return Seq() } // expected-note{{found this candidate}}
func getOvlSeq() -> Seq<X<Int>> { return Seq() } // expected-note{{found this candidate}}
func getGenericSeq<T>() -> Seq<T> { return Seq() }
func getXIntSeq() -> Seq<X<Int>> { return Seq() }
func getXIntSeqIUO() -> Seq<X<Int>>! { return nil }
func testForEachInference() {
for i in getIntSeq() { }
// Overloaded sequence resolved contextually
for i: Int in getOvlSeq() { }
for d: Double in getOvlSeq() { }
// Overloaded sequence not resolved contextually
for v in getOvlSeq() { } // expected-error{{ambiguous use of 'getOvlSeq()'}}
// Generic sequence resolved contextually
for i: Int in getGenericSeq() { }
for d: Double in getGenericSeq() { }
// Inference of generic arguments in the element type from the
// sequence.
for x: X in getXIntSeq() {
let z = x.value + 1
}
for x: X in getOvlSeq() {
let z = x.value + 1
}
// Inference with implicitly unwrapped optional
for x: X in getXIntSeqIUO() {
let z = x.value + 1
}
// Range overloading.
for i: Int8 in 0..<10 { }
for i: UInt in 0...10 { }
}
func testMatchingPatterns() {
// <rdar://problem/21428712> for case parse failure
let myArray : [Int?] = []
for case .some(let x) in myArray {
_ = x
}
// <rdar://problem/21392677> for/case/in patterns aren't parsed properly
class A {}
class B : A {}
class C : A {}
let array : [A] = [A(), B(), C()]
for case (let x as B) in array {
_ = x
}
}
// <rdar://problem/21662365> QoI: diagnostic for for-each over an optional sequence isn't great
func testOptionalSequence() {
let array : [Int]?
for x in array { // expected-error {{value of optional type '[Int]?' must be unwrapped}}
// expected-note@-1{{coalesce}}
// expected-note@-2{{force-unwrap}}
}
}
// Crash with (invalid) for each over an existential
func testExistentialSequence(s: Sequence) { // expected-error {{protocol 'Sequence' can only be used as a generic constraint because it has Self or associated type requirements}}
for x in s { // expected-error {{protocol type 'Sequence' cannot conform to 'Sequence' because only concrete types can conform to protocols}}
_ = x
}
}
// Conditional conformance to Sequence and IteratorProtocol.
protocol P { }
struct RepeatedSequence<T> {
var value: T
var count: Int
}
struct RepeatedIterator<T> {
var value: T
var count: Int
}
extension RepeatedIterator: IteratorProtocol where T: P {
typealias Element = T
mutating func next() -> T? {
if count == 0 { return nil }
count = count - 1
return value
}
}
extension RepeatedSequence: Sequence where T: P {
typealias Element = T
typealias Iterator = RepeatedIterator<T>
typealias SubSequence = AnySequence<T>
func makeIterator() -> RepeatedIterator<T> {
return Iterator(value: value, count: count)
}
}
extension Int : P { }
func testRepeated(ri: RepeatedSequence<Int>) {
for x in ri { _ = x }
}
| apache-2.0 | 876c3da93ec22c91f598eab6354b7ebb | 26.040724 | 181 | 0.65077 | 3.544484 | false | false | false | false |
practicalswift/swift | validation-test/compiler_crashers_fixed/01732-swift-parser-parsebraceitemlist.swift | 65 | 552 | // 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
// RUN: not %target-swift-frontend %s -typecheck
{
typealias R = [(self.h == {
}
protocol d where h> a {
typealias f = h, Any, range.a<U {
let f == { c: T) {
if true }
}
}
}
}
protocol P {
func b<T : b>
| apache-2.0 | 6653213d2d872b95322df84e53972dcb | 25.285714 | 79 | 0.690217 | 3.285714 | false | false | false | false |
piscoTech/Workout | WorkoutHelper/ContentView.swift | 1 | 3090 | //
// ContentView.swift
// WorkoutHelper
//
// Created by Marco Boschi on 27/10/2019.
// Copyright © 2019 Marco Boschi. All rights reserved.
//
import SwiftUI
import HealthKit
let hkStore = HKHealthStore()
struct ContentView: View {
@State var result: Bool? = nil
var body: some View {
VStack {
Button(action: {
self.createSamples()
}) {
Text("Add samples...")
}
if result != nil {
Text(result == true ? "Ok!" : "Failed")
} else {
Text("Waiting...")
}
}
}
func createSamples() {
hkStore.requestAuthorization(toShare: [HKObjectType.workoutType()], read: nil) { _, _ in
let s = Date()
let ri = HKWorkout(activityType: .running, start: s, end: s.advanced(by: 30 * 60), duration: 0, totalEnergyBurned: nil, totalDistance: nil, metadata: [HKMetadataKeyIndoorWorkout : true])
let ro = HKWorkout(activityType: .running, start: s, end: s.advanced(by: 30 * 60), duration: 0, totalEnergyBurned: nil, totalDistance: nil, metadata: [HKMetadataKeyIndoorWorkout : false])
let r = HKWorkout(activityType: .running, start: s, end: s.advanced(by: 30 * 60))
let ci = HKWorkout(activityType: .cycling, start: s, end: s.advanced(by: 30 * 60), duration: 0, totalEnergyBurned: nil, totalDistance: nil, metadata: [HKMetadataKeyIndoorWorkout : true])
let co = HKWorkout(activityType: .cycling, start: s, end: s.advanced(by: 30 * 60), duration: 0, totalEnergyBurned: nil, totalDistance: nil, metadata: [HKMetadataKeyIndoorWorkout : false])
let c = HKWorkout(activityType: .cycling, start: s, end: s.advanced(by: 30 * 60))
let wi = HKWorkout(activityType: .walking, start: s, end: s.advanced(by: 30 * 60), duration: 0, totalEnergyBurned: nil, totalDistance: nil, metadata: [HKMetadataKeyIndoorWorkout : true])
let wo = HKWorkout(activityType: .walking, start: s, end: s.advanced(by: 30 * 60), duration: 0, totalEnergyBurned: nil, totalDistance: nil, metadata: [HKMetadataKeyIndoorWorkout : false])
let w = HKWorkout(activityType: .walking, start: s, end: s.advanced(by: 30 * 60))
let si = HKWorkout(activityType: .swimming, start: s, end: s.advanced(by: 30 * 60), duration: 0, totalEnergyBurned: nil, totalDistance: nil, metadata: [HKMetadataKeySwimmingLocationType : HKWorkoutSwimmingLocationType.pool.rawValue])
let so = HKWorkout(activityType: .swimming, start: s, end: s.advanced(by: 30 * 60), duration: 0, totalEnergyBurned: nil, totalDistance: nil, metadata: [HKMetadataKeySwimmingLocationType : HKWorkoutSwimmingLocationType.openWater.rawValue])
let su = HKWorkout(activityType: .swimming, start: s, end: s.advanced(by: 45 * 60), duration: 0, totalEnergyBurned: nil, totalDistance: nil, metadata: [HKMetadataKeySwimmingLocationType : HKWorkoutSwimmingLocationType.unknown.rawValue])
let swim = HKWorkout(activityType: .swimming, start: s, end: s.advanced(by: 30 * 60))
hkStore.save([ri, ro, r, ci, co, c, wi, wo, w, si, so, su, swim]) { (r, err) in
self.result = r
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| mit | 55e92fbe8a5baa814650e0140c08217f | 46.523077 | 241 | 0.698932 | 3.459127 | false | false | false | false |
PigDogBay/swift-utils | SwiftUtils/WordList.swift | 1 | 11939 | //
// WordList.swift
// Anagram Solver
//
// Created by Mark Bailey on 09/02/2015.
// Copyright (c) 2015 MPD Bailey Technology. All rights reserved.
//
import Foundation
public class WordList
{
private let wordlist: [String]
//Stop needs to be protected by a mutex,
//keep an eye out for future enhancements in Swift, such as synchronized blocks
private var _Stop = false
private var stop: Bool
{
get
{
objc_sync_enter(self)
let tmp = _Stop
objc_sync_exit(self)
return tmp
}
set(newValue)
{
objc_sync_enter(self)
_Stop = newValue
objc_sync_exit(self)
}
}
public func stopSearch()
{
stop = true
}
public init(wordlist: [String])
{
self.wordlist = wordlist
}
public func reset()
{
stop = false
}
public func spellingBee(_ letters: String, mustContain : Character, callback: WordListCallback){
let set = LetterSet(word: letters)
for word in self.wordlist {
if (self.stop)
{
break
}
//spelling bee min length is 4 letters
if word.length>3 && set.isSpellingBee(word, mustContain: mustContain){
callback.update(word)
}
}
}
public func findSupergrams(_ letters: String, callback: WordListCallback, length: Int)
{
let len = letters.length
let anagram = LetterSet(word: letters)
for word in self.wordlist
{
if (self.stop)
{
break
}
if (length==0 && word.length>len) || word.length == length
{
if anagram.isSupergram(word)
{
callback.update(word)
}
}
}
}
public func findAnagrams(_ letters: String, numberOfBlanks: Int, callback: WordListCallback)
{
let len = letters.length
let anagram = LetterSet(word: letters)
let too_big = len + numberOfBlanks + 1
for word in self.wordlist
{
if (self.stop)
{
break
}
if word.length < too_big {
if anagram.isAnagram(word, numberOfBlanks: numberOfBlanks){
callback.update(word)
}
}
}
}
public func findAnagramsExactLength(_ letters: String, numberOfBlanks: Int, callback: WordListCallback)
{
let len = letters.length + numberOfBlanks
let anagram = LetterSet(word: letters)
for word in self.wordlist
{
if (self.stop) { break }
if word.length == len {
if anagram.isAnagram(word, numberOfBlanks: numberOfBlanks){
callback.update(word)
}
}
}
}
public func findAnagrams(_ letters: String, callback: WordListCallback)
{
let len = letters.length
let anagram = LetterSet(word: letters)
for word in self.wordlist
{
if (self.stop)
{
break
}
if word.length == len
{
if anagram.isAnagram(word)
{
callback.update(word)
}
}
}
}
public func findSubAnagrams(_ letters: String, callback: WordListCallback)
{
let len = letters.length
let anagram = LetterSet(word: letters)
for word in self.wordlist
{
if (self.stop)
{
break
}
let wordLen = word.length
if wordLen>0 && wordLen < len
{
if anagram.isSubgram(word)
{
callback.update(word)
}
}
}
}
/*
Speed Tests
-----------
Searching for .....ing returns 2543 matches
word.range(of: pattern, options:NSString.CompareOptions.regularExpression)
-Time taken 5.7s
NSRegularExpression
-Time taken 4.4s
In unit testing, NSRegEx is over twice as fast.
*/
public func findCrosswords(_ crossword: String, callback: WordListCallback)
{
let len = crossword.length
let pattern = createRegexPattern(crossword)
let regex = try? NSRegularExpression(pattern: pattern, options: [])
if nil == regex {return}
let range = NSRange(location: 0, length: len)
for word in self.wordlist
{
if (self.stop)
{
break
}
if word.length == len
{
if 1 == regex!.numberOfMatches(in: word, options: [], range: range){
callback.update(word)
}
}
}
}
/*
Speed Tests
-----------
Unit tests show NSRegEx is 3x faster than NSString
iPhone 5s Device tests: 16s for NSString, 10s for NSRegEx
*/
public func findWildcards(_ wildcard: String, callback: WordListCallback)
{
let pattern = createRegexPattern(wildcard)
let regex = try? NSRegularExpression(pattern: pattern, options: [])
if nil == regex {return}
for word in self.wordlist
{
if (self.stop)
{
break
}
let range = NSRange(location: 0, length: word.length)
if 1 == regex!.numberOfMatches(in: word, options: [], range: range){
callback.update(word)
}
}
}
fileprivate func createRegexPattern(_ query: String) ->String
{
//need to add word boundary to prevent regex matching just part of the word string
return "\\b"+query
.replace(".", withString: "[a-z]")
.replace("@", withString: "[a-z]+")+"\\b"
}
/*
Filter the word list so that it contains letters that are same size as word1
and is a subset of the letters contained in word1+word2
Create another filtered list if word2 is different length to word1
swap lists, we want the smallest to cut down on some processing
for each word in the first list find the unused letters
Then for each word in the second list see if it is an anagram of the unused letters,
if it is the first and second words make a two word anagram
*/
public func findMultiwordAnagrams(_ word1: String, word2: String, callback: WordListCallback)
{
let superset = LetterSet(word: word1+word2)
let listA = self.getFilteredList(superset, length: word1.length)
var listB: [String]
if word1.length == word2.length
{
listB = listA
}
else
{
listB = self.getFilteredList(superset, length: word2.length)
}
for first in listA
{
superset.clear()
superset.add(word1)
superset.add(word2)
superset.delete(first)
for second in listB
{
if (self.stop)
{
break
}
if superset.isAnagram(second)
{
callback.update(first+" "+second)
}
}
}
}
public func findMultiwordAnagrams(_ letters: String, startLen : Int, callback: WordListCallback){
let len = letters.length
let middleWordSize = len/2
//first show the user's requested word sizes
findOtherMultiwordAnagrams(letters, startLen, callback: callback)
let skipLen = startLen > middleWordSize ? len - startLen : startLen
for i in stride(from: middleWordSize, to: 0, by: -1) {
if (self.stop) { break }
if i != skipLen {
findOtherMultiwordAnagrams(letters, i, callback: callback)
}
}
}
fileprivate func findOtherMultiwordAnagrams(_ letters : String,_ i : Int, callback : WordListCallback) {
let index = letters.index(letters.startIndex, offsetBy: i)
let word1 = String(letters[..<index])
let word2 = String(letters[index...])
findMultiwordAnagrams(word1, word2: word2, callback: callback)
}
fileprivate func getFilteredList(_ set: LetterSet, length: Int) -> [String]{
var matches : [String] = []
for word in self.wordlist
{
if (self.stop) { break }
if word.length == length && set.isSubgram(word)
{
matches.append(word)
}
}
return matches
}
public func findMultiwordAnagrams(_ word1: String,_ word2: String,_ word3: String, callback: WordListCallback){
let superset = LetterSet(word: word1+word2+word3)
let listA = self.getFilteredList(superset, length: word1.length)
var listB: [String]
var listC: [String]
if word1.length == word2.length {
//In swift arrays are structs, so listA is copied here
listB = listA
} else {
listB = self.getFilteredList(superset, length: word2.length)
}
if word3.length == word1.length
{
listC = listA
} else if word3.length == word2.length {
listC = listB
} else {
listC = self.getFilteredList(superset, length: word3.length)
}
var sublistB : [String] = []
var sublistC : [String] = []
let are2And3SameLength = word2.length == word3.length
for first in listA {
//prune lists B and C of any words that are impossible with first
superset.clear()
superset.add(word1)
superset.add(word2)
superset.add(word3)
superset.delete(first)
sublistB.removeAll()
filterList(set: superset, length: word2.length, matches: &sublistB, wordList: listB)
sublistC.removeAll()
if are2And3SameLength {
//Ideally in the case sublistC and sublistB would be the same array
//however in swift they are structs, so are copied if you assign to a new instance.
//I could use NSMutableArray but requires downcasting of the objects to Strings
//or wrap the [String] in a class and use inout
sublistC.append(contentsOf: sublistB)
} else {
filterList(set: superset, length: word3.length, matches: &sublistC, wordList: listC)
}
for second in sublistB {
superset.clear()
superset.add(word1)
superset.add(word2)
superset.add(word3)
superset.delete(first)
superset.delete(second)
for third in sublistC {
if (self.stop) { break }
if superset.isAnagram(third){
callback.update("\(first) \(second) \(third)")
}
}
}
}
}
func filterList(set : LetterSet, length : Int, matches : inout [String], wordList : [String]){
for word in wordList {
if (self.stop) { break }
if word.length == length && set.isSubgram(word) {
matches.append(word)
}
}
}
public func findCodewords(codewordSolver : CodewordSolver, callback : WordListCallback){
for word in self.wordlist
{
if (self.stop) { break}
if codewordSolver.isMatch(word: word){
callback.update(word)
}
}
}
}
| apache-2.0 | aa740317df0f0faacde7a042b5c4aaca | 30.335958 | 115 | 0.523913 | 4.490034 | false | false | false | false |
jpush/jchat-swift | JChat/Src/UserModule/View/JCDatePickerViwe.swift | 1 | 3469 | //
// JCDatePickerViwe.swift
// YHRSS
//
// Created by JIGUANG on 2017/3/23.
// Copyright © 2017年 dengyonghao. All rights reserved.
//
import UIKit
@objc public protocol JCDatePickerViweDelegate: NSObjectProtocol {
@objc optional func datePicker(finish finishButton: UIButton, date: Date)
@objc optional func datePicker(cancel cancelButton: UIButton, date: Date)
}
class JCDatePickerViwe: UIView {
open weak var delegate: JCDatePickerViweDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
_init()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private lazy var cancelButton: UIButton = {
var cancelButton = UIButton()
cancelButton.layer.borderWidth = 0.5
cancelButton.layer.borderColor = UIColor.gray.cgColor
cancelButton.setTitle("取消", for: .normal)
cancelButton.setTitleColor(.black, for: .normal)
cancelButton.addTarget(self, action: #selector(_cancel(_:)), for: .touchUpInside)
return cancelButton
}()
private lazy var finishButton: UIButton = {
var finishButton = UIButton()
finishButton.layer.borderWidth = 0.5
finishButton.layer.borderColor = UIColor.gray.cgColor
finishButton.setTitle("完成", for: .normal)
finishButton.setTitleColor(.black, for: .normal)
finishButton.addTarget(self, action: #selector(_finish(_:)), for: .touchUpInside)
return finishButton
}()
private lazy var datePicker: UIDatePicker = {
var datePicker = UIDatePicker()
datePicker.calendar = Calendar.current
datePicker.datePickerMode = .date
datePicker.locale = Locale(identifier: "zh_CN")
return datePicker
}()
//MARK: - private func
private func _init() {
// 216 + 40
backgroundColor = .white
addSubview(finishButton)
addSubview(cancelButton)
addSubview(datePicker)
addConstraint(_JCLayoutConstraintMake(cancelButton, .left, .equal, self, .left))
addConstraint(_JCLayoutConstraintMake(cancelButton, .right, .equal, self, .centerX))
addConstraint(_JCLayoutConstraintMake(cancelButton, .top, .equal, self, .top))
addConstraint(_JCLayoutConstraintMake(cancelButton, .height, .equal, nil, .notAnAttribute, 40))
addConstraint(_JCLayoutConstraintMake(finishButton, .left, .equal, self, .centerX))
addConstraint(_JCLayoutConstraintMake(finishButton, .right, .equal, self, .right))
addConstraint(_JCLayoutConstraintMake(finishButton, .top, .equal, self, .top))
addConstraint(_JCLayoutConstraintMake(finishButton, .height, .equal, nil, .notAnAttribute, 40))
addConstraint(_JCLayoutConstraintMake(datePicker, .left, .equal, self, .left, 8))
addConstraint(_JCLayoutConstraintMake(datePicker, .right, .equal, self, .right, -8))
addConstraint(_JCLayoutConstraintMake(datePicker, .top, .equal, finishButton, .bottom))
addConstraint(_JCLayoutConstraintMake(datePicker, .height, .equal, nil, .notAnAttribute, 216))
}
//MARK: - click event
@objc func _cancel(_ sender: UIButton) {
delegate?.datePicker?(cancel: sender, date: datePicker.date)
}
@objc func _finish(_ sender: UIButton) {
delegate?.datePicker?(finish: sender, date: datePicker.date)
}
}
| mit | 33bea78072a6a71474c9e6bf1b78e537 | 37.853933 | 103 | 0.668305 | 4.568032 | false | false | false | false |
barteljan/VISPER | VISPER-Wireframe/Classes/Wireframe/DefaultComposedRoutingObserver.swift | 1 | 4531 | //
// DefaultComposedRoutingObserver.swift
// VISPER-Wireframe
//
// Created by bartel on 22.11.17.
//
import Foundation
import VISPER_Core
open class DefaultComposedRoutingObserver : ComposedRoutingObserver {
var routingObservers: [RoutingObserverWrapper]
public init() {
self.routingObservers = [RoutingObserverWrapper]()
}
/// Add an instance observing controllers before they are presented
///
/// - Parameters:
/// - routingObserver: An instance observing controllers before they are presented
/// - priority: The priority for calling your provider, higher priorities are called first. (Defaults to 0)
/// - routePattern: The route pattern to call this observer, the observer is called for every route if this pattern is nil
public func add(routingObserver: RoutingObserver, priority: Int, routePattern: String?) {
let wrapper = RoutingObserverWrapper(priority: priority, routePattern: routePattern, routingObserver: routingObserver)
self.addRoutingObserverWrapper(wrapper: wrapper)
}
/// Event that indicates that a view controller will be presented
///
/// - Parameters:
/// - controller: The view controller that will be presented
/// - routePattern: The route pattern triggering the presentation
/// - routingOption: The RoutingOption describing how the controller will be presented
/// - parameters: The parameters (data) extraced from the route, or given by the sender
/// - routingPresenter: The RoutingPresenter responsible for presenting the controller
/// - wireframe: The wireframe presenting the view controller
public func willPresent(controller: UIViewController,
routeResult: RouteResult,
routingPresenter: RoutingPresenter?,
wireframe: Wireframe) throws {
//notify all responsible routing observers that the presentation will occour soon
for observerWrapper in self.routingObservers {
if observerWrapper.routePattern == nil ||
observerWrapper.routePattern == routeResult.routePattern {
try observerWrapper.routingObserver.willPresent(controller: controller,
routeResult: routeResult,
routingPresenter: routingPresenter,
wireframe: wireframe)
}
}
}
/// Event that indicates that a view controller was presented
///
/// - Parameters:
/// - controller: The view controller that will be presented
/// - routePattern: The route pattern triggering the presentation
/// - routingOption: The RoutingOption describing how the controller will be presented
/// - parameters: The parameters (data) extraced from the route, or given by the sender
/// - routingPresenter: The RoutingPresenter responsible for presenting the controller
/// - wireframe: The wireframe presenting the view controller
open func didPresent( controller: UIViewController,
routeResult: RouteResult,
routingPresenter: RoutingPresenter?,
wireframe: Wireframe) {
//notify all responsible routing observers that the view controller presentation did occure
for observerWrapper in self.routingObservers {
if observerWrapper.routePattern == nil ||
observerWrapper.routePattern == routeResult.routePattern {
observerWrapper.routingObserver.didPresent( controller: controller,
routeResult: routeResult,
routingPresenter: routingPresenter,
wireframe: wireframe)
}
}
}
internal struct RoutingObserverWrapper {
let priority : Int
let routePattern : String?
let routingObserver : RoutingObserver
}
func addRoutingObserverWrapper(wrapper: RoutingObserverWrapper) {
self.routingObservers.append(wrapper)
self.routingObservers.sort { (wrapper1, wrapper2) -> Bool in
return wrapper1.priority > wrapper2.priority
}
}
}
| mit | 3565c4f15a7c9da99395befd95d5ab56 | 44.31 | 128 | 0.6162 | 6.106469 | false | false | false | false |
bphenriques/CircleProgressView | CircularProgressView/CircleProgressView.swift | 1 | 2533 | //
// CircleProgressView.swift
// CircularProgressView
//
// Created by Bruno Henriques on 08/08/15.
// Copyright (c) 2015 Bruno Henriques. All rights reserved.
//
import UIKit
@IBDesignable public class CircleProgressView: UIView {
@IBInspectable public var circleColor: UIColor = UIColor(hex: 0xE3C79B)
@IBInspectable public var progressColor: UIColor = UIColor(hex: 0xE46D71)
@IBInspectable public var clockWise: Bool = true
@IBInspectable public var lineWidth: CGFloat = 4.0 {
didSet {
backgroundCircle.lineWidth = lineWidth
self.progressCircle.lineWidth = lineWidth + 0.1
}
}
@IBInspectable public var valueProgress: Float = 0 {
didSet {
self.progressCircle.strokeEnd = CGFloat(valueProgress) / 100
}
}
private let backgroundCircle = CAShapeLayer()
private let progressCircle = CAShapeLayer()
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.clearColor()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public override func drawRect(rect: CGRect) {
// Create path
let centerPointArc = CGPoint(x: frame.size.width / 2, y: frame.size.height / 2)
let radiusArc: CGFloat = self.frame.width / 2 * 0.8
let circlePath = UIBezierPath(arcCenter: centerPointArc, radius: radiusArc, startAngle: radial_angle(0), endAngle: radial_angle(360), clockwise: clockWise)
// Define background circle still to be loaded
backgroundCircle.path = circlePath.CGPath
backgroundCircle.strokeColor = circleColor.CGColor
backgroundCircle.fillColor = UIColor.clearColor().CGColor
backgroundCircle.lineWidth = lineWidth
backgroundCircle.strokeStart = 0
backgroundCircle.strokeEnd = CGFloat(1.0)
// Define circle showing loading
progressCircle.path = circlePath.CGPath
progressCircle.strokeColor = progressColor.CGColor
progressCircle.fillColor = UIColor.clearColor().CGColor
progressCircle.lineWidth = lineWidth + 0.1
progressCircle.strokeStart = 0
progressCircle.strokeEnd = CGFloat(valueProgress) / 100
// set layers
layer.addSublayer(backgroundCircle)
layer.addSublayer(progressCircle)
}
private func radial_angle(arc: CGFloat) -> CGFloat {
return CGFloat(M_PI) * arc / 180
}
} | mit | 2d041d22d1c4e8d41057084746d95c16 | 34.690141 | 163 | 0.662456 | 4.861804 | false | false | false | false |
sora0077/iTunesMusic | Demo/Views/SettingsViewController.swift | 1 | 5579 | //
// SettingsViewController.swift
// iTunesMusic
//
// Created by 林達也 on 2016/10/24.
// Copyright © 2016年 jp.sora0077. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import SnapKit
import iTunesMusic
private extension Reactive where Base: Model.DiskCache {
var diskSizeText: Observable<String> {
return diskSizeInBytes.map { bytes in
switch bytes {
case 0...1024*1024:
return String(format: "%.2fKB", Float(bytes)/1024)
case 1024*1024...1024*1024*1024:
return String(format: "%.2fMB", Float(bytes)/1024/1024)
default:
return String(format: "%.2fGB", Float(bytes)/1024/1024/1024)
}
}
}
}
private protocol RowType {
var cellClass: UITableViewCell.Type { get }
func configure(cell: UITableViewCell, parent: UIViewController)
func action(_ tableView: UITableView, at indexPath: IndexPath, parent: UIViewController)
}
extension RowType {
func register(_ tableView: UITableView) {
tableView.register(cellClass, forCellReuseIdentifier: String(describing: cellClass))
}
func cell(_ tableView: UITableView, at indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: cellClass), for: indexPath)
return cell
}
func action(_ tableView: UITableView, at indexPath: IndexPath, parent: UIViewController) {}
}
extension SettingsViewController {
fileprivate enum Section: Int {
case cache
}
}
extension SettingsViewController.Section {
var rows: [RowType] {
switch self {
case .cache:
enum Row: Int, RowType {
case cache
var cellClass: UITableViewCell.Type {
switch self {
case .cache:
class Cell: UITableViewCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: .value1, reuseIdentifier: reuseIdentifier)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareForReuse() {
super.prepareForReuse()
disposeBag = DisposeBag()
}
}
return Cell.self
}
}
func configure(cell: UITableViewCell, parent: UIViewController) {
cell.textLabel?.text = "キャッシュの削除"
if let text = cell.detailTextLabel?.rx.text {
Model.DiskCache.shared.rx.diskSizeText
.asDriver(onErrorJustReturn: "")
.drive(text)
.addDisposableTo(cell.disposeBag)
}
}
func action(_ tableView: UITableView, at indexPath: IndexPath, parent: UIViewController) {
let sheet = UIAlertController(title: "キャッシュの削除", message: "本当に削除しますか?", preferredStyle: .actionSheet)
sheet.addAction(UIAlertAction(title: "削除", style: .destructive) { _ in
Model.DiskCache.shared.removeAll()
.subscribe(UIBindingObserver(UIElement: parent) { _, _ in
})
.addDisposableTo(parent.disposeBag)
})
sheet.addAction(UIAlertAction(title: "キャンセル", style: .cancel) { _ in
})
parent.present(sheet, animated: true) {
tableView.deselectRow(at: indexPath, animated: true)
}
}
}
return [Row.cache]
}
}
}
final class SettingsViewController: UIViewController {
fileprivate let tableView = UITableView(frame: .zero, style: .grouped)
fileprivate let sections: [Section] = [.cache]
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(tableView)
tableView.delegate = self
tableView.dataSource = self
sections.forEach {
$0.rows.forEach {
$0.register(tableView)
}
}
tableView.snp.makeConstraints { make in
make.edges.equalTo(0)
}
}
}
extension SettingsViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[section].rows.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let row = sections[indexPath.section].rows[indexPath.row]
let cell = row.cell(tableView, at: indexPath)
row.configure(cell: cell, parent: self)
return cell
}
}
extension SettingsViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let row = sections[indexPath.section].rows[indexPath.row]
row.action(tableView, at: indexPath, parent: self)
}
}
| mit | 5eea8065a6d66e505a3c77c00196099e | 32.357576 | 121 | 0.560501 | 5.380254 | false | false | false | false |
noppefoxwolf/FlowBarButtonItem | Pod/Classes/FlowBarButtonItem.swift | 1 | 8476 | //
// FlowBarButtonItem.swift
// OSKNavigationFlowButton
//
// Created by Tomoya Hirano on 2015/12/15.
// Copyright © 2015年 Tomoya Hirano. All rights reserved.
//
import UIKit
class FlowBarButtonItem: UIBarButtonItem {
private var press:UILongPressGestureRecognizer?
var flowWindow:FlowWindow?
var flowButton:FlowButton?
var _view:UIView?{
return valueForKey("view") as? UIView
}
func enableFlow(){
if let p = press {
_view?.removeGestureRecognizer(p)
}
press = UILongPressGestureRecognizer(target: self, action: "longPress:")
press?.minimumPressDuration = 0.2
_view?.addGestureRecognizer(press!)
flowButton = FlowButton(barButtonItem: self)
}
private override init() {
super.init()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
internal func longPress(gesture:UILongPressGestureRecognizer){
let p = gesture.locationInView(_view?.superview)
if gesture.state == .Began {
_view?.hidden = true
FlowWindow.sharedInstance.addFlowButton(flowButton!)
flowButton?.center = _view!.center
UIView.animateWithDuration(0.2, animations: { () -> Void in
self.flowButton?.center = p
})
}else if gesture.state == .Changed {
flowButton?.pan(gesture)
}else if gesture.state == .Ended {
flowButton?.pan(gesture)
}
}
}
class FlowWindow:UIWindow {
static let sharedInstance = FlowWindow(frame: UIScreen.mainScreen().bounds)
internal func addFlowButton(button:FlowButton){
makeKeyAndVisible()
addSubview(button)
button.transform = CGAffineTransformMakeScale(0.1, 0.1)
UIView.animateWithDuration(0.4, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.7, options: UIViewAnimationOptions.AllowAnimatedContent, animations: { () -> Void in
button.transform = CGAffineTransformIdentity
}) { (_) -> Void in
}
}
override init(frame: CGRect) {
super.init(frame: frame)
windowLevel = UIWindowLevelAlert-1
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
internal func returnButton(button:FlowButton){
UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.7, options: UIViewAnimationOptions.AllowAnimatedContent, animations: { () -> Void in
button.alpha = 0.0
button.transform = CGAffineTransformIdentity
}) { (_) -> Void in
button.alpha = 1.0
button.barButton?._view?.hidden = false
button.removeFromSuperview()
if self.subviews.count == 0{
self.resignKeyWindow()
self.removeFromSuperview()
self.hidden = true
}
}
}
//FlowButtonは押せるようにする
override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {
if let v = super.hitTest(point, withEvent: event) as? FlowButton {
return v
}
return nil
}
}
class FlowButton:UIView {
private var canMove = false
private var myWindow = FlowWindow.sharedInstance
private var barButton:FlowBarButtonItem?
private var barButtonZone:CGRect?
internal var dismissOnButton = false
private var baseView = UIView(frame: CGRectMake(0, 0, 64, 64))
private var imageView = UIImageView(frame: CGRectMake(0, 0, 21, 21))
private var coverView = UIView(frame: CGRectMake(0, 0, 64, 64))
init(barButtonItem:FlowBarButtonItem){
super.init(frame: CGRectMake(0, 0, 64, 64))
baseView.backgroundColor = UIColor(hue:0.63, saturation:0.25, brightness:0.21, alpha:1)
baseView.layer.cornerRadius = 32
baseView.layer.masksToBounds = true
baseView.userInteractionEnabled = false
baseView.layer.masksToBounds = false
baseView.layer.borderColor = UIColor.whiteColor().CGColor
baseView.layer.borderWidth = 2.0
baseView.layer.shadowOffset = CGSizeZero
baseView.layer.shadowOpacity = 0.5
baseView.layer.shadowColor = UIColor.blackColor().CGColor
baseView.layer.shadowRadius = 5.0
addSubview(baseView)
imageView.contentMode = UIViewContentMode.Center
imageView.center = CGPointMake(bounds.width/2, bounds.height/2)
imageView.userInteractionEnabled = false
baseView.addSubview(imageView)
coverView.backgroundColor = UIColor.blackColor()
coverView.alpha = 0.0
coverView.userInteractionEnabled = false
baseView.addSubview(coverView)
barButton = barButtonItem
barButtonZone = barButtonItem._view?.frame
imageView.image = barButtonItem.image?.imageWithRenderingMode(.AlwaysTemplate)
backgroundColor = UIColor.clearColor()
imageView.tintColor = tintColor
let pan = UIPanGestureRecognizer(target: self, action: "pan:")
addGestureRecognizer(pan)
let tap = UITapGestureRecognizer(target: self, action: "tapGesture:")
addGestureRecognizer(tap)
}
private func onBar()->Bool{
let zone = CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, 64)
return CGRectContainsPoint(zone, center)
}
private func onBarButton()->Bool{
let offset:CGFloat = 40.0
var zone = barButtonZone!
zone.size.width += offset
zone.size.width += offset
zone.origin.x -= offset/2
zone.origin.y += offset/2
return CGRectContainsPoint(zone, center)
}
private func onContain()->Bool{
return dismissOnButton ? onBarButton() : onBar()
}
func tapGesture(gesture:UITapGestureRecognizer){
let app = UIApplication.sharedApplication()
app.sendAction(self.barButton!.action, to: self.barButton!.target,
from: self, forEvent: nil)
}
func pan(gesture:UILongPressGestureRecognizer){
if gesture.state == .Began {
canMove = true
let scale:CGFloat = 1.2
UIView.animateWithDuration(0.3, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.7, options: [.AllowAnimatedContent,.AllowUserInteraction], animations: { () -> Void in
self.transform = CGAffineTransformMakeScale(scale,scale)
self.baseView.layer.shadowRadius = 20.0
}, completion: { (_) -> Void in
})
}else if gesture.state == .Changed{
let p = gesture.locationInView(superview)
center = p
let scale:CGFloat = onContain() ? 1.5 : 1.2
UIView.animateWithDuration(0.3, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.7, options: [.AllowAnimatedContent,.AllowUserInteraction], animations: { () -> Void in
self.transform = CGAffineTransformMakeScale(scale,scale)
}, completion: { (_) -> Void in
})
}else if gesture.state == .Ended {
canMove = false
if onContain() {
myWindow.returnButton(self)
}else{
fitSide()
}
}else{
fitSide()
}
}
private func fitSide(){
let padding:CGFloat = 44.0
let superWidth = myWindow.bounds.width
let superHeight = myWindow.bounds.height
let posX = center.x < superWidth/2 ? padding : superWidth-padding
var posY = center.y
posY = posY<padding ? padding : posY
posY = posY>superHeight-padding ? superHeight-padding : posY
let pos = CGPointMake(posX, posY)
UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.7, options: [.AllowAnimatedContent,.AllowUserInteraction], animations: { () -> Void in
self.center = pos
self.transform = CGAffineTransformIdentity
self.baseView.layer.shadowRadius = 5.0
}, completion: { (_) -> Void in
})
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | c3ff4b6addf5f0d207d65ee9e38fa62a | 36.745536 | 194 | 0.618805 | 4.876009 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.