hexsha
stringlengths 40
40
| size
int64 3
1.03M
| content
stringlengths 3
1.03M
| avg_line_length
float64 1.33
100
| max_line_length
int64 2
1k
| alphanum_fraction
float64 0.25
0.99
|
---|---|---|---|---|---|
71e49d5cbe82ce0d630547bfff78472844efa4b4 | 1,073 | import Foundation
final class EntryPointAttributeRetainer: SourceGraphVisitor {
static func make(graph: SourceGraph) -> Self {
return self.init(graph: graph)
}
private let graph: SourceGraph
required init(graph: SourceGraph) {
self.graph = graph
}
func visit() {
let classes = graph.declarations(ofKinds: [.class, .struct])
let mainClasses = classes.filter {
$0.attributes.contains("NSApplicationMain") ||
$0.attributes.contains("UIApplicationMain") ||
$0.attributes.contains("main")
}
mainClasses.forEach {
graph.markRetained($0)
$0.ancestralDeclarations.forEach {
graph.markRetained($0)
}
if $0.attributes.contains("main") {
// @main requires a static main() function.
$0.declarations
.filter { $0.kind == .functionMethodStatic && $0.name == "main()"}
.forEach { graph.markRetained($0) }
}
}
}
}
| 28.236842 | 86 | 0.54986 |
ef496cf3c9447a3ac0e9f893736c5d06b2d9abaf | 230 | import Swinject
final class SharedAssembly: Assembly {
func assemble(container: Container) {
container.autoregister(UserStorage.self, initializer: UserStorage.init)
.inObjectScope(.container)
}
}
| 23 | 79 | 0.695652 |
e429e917a111358a72af15baeef62bc7223e1daf | 893 | // RUN: %target-swift-frontend %s -emit-ir -g -o - | FileCheck %s
// CHECK: define hidden void @_TFC12generic_arg25Class3foo{{.*}}, %swift.type* %U
// CHECK: [[Y:%.*]] = getelementptr inbounds %C12generic_arg25Class, %C12generic_arg25Class* %2, i32 0, i32 0, i32 0
// store %swift.opaque* %[[Y]], %swift.opaque** %[[Y_SHADOW:.*]], align
// CHECK: call void @llvm.dbg.declare(metadata %swift.opaque** %y.addr, metadata ![[U:.*]], metadata !{{[0-9]+}})
// Make sure there is no conflicting dbg.value for this variable.x
// CHECK-NOT: dbg.value{{.*}}metadata ![[U]]
class Class <T> {
// CHECK: ![[U]] = !DILocalVariable(name: "y", arg: 2{{.*}} line: [[@LINE+1]],
func foo<U>(_ x: T, y: U) {}
func bar(_ x: String, y: Int64) {}
init() {}
}
func main() {
var object: Class<String> = Class()
var x = "hello"
var y : Int64 = 1234
object.bar(x, y: y)
object.foo(x, y: y)
}
main()
| 33.074074 | 116 | 0.605823 |
4adfd70f706fc11ff6e9330c08429f45ed1f8437 | 651 | // swift-tools-version:5.3
import PackageDescription
let package = Package(
name: "MaskedUITextField",
platforms: [
.iOS(.v10)
],
products: [
.library(
name: "MaskedUITextField",
targets: ["MaskedUITextField"])
],
dependencies: [
.package(url: "https://github.com/Columbina/MaskedFormatter.git",
from: "1.0.0")
],
targets: [
.target(
name: "MaskedUITextField",
dependencies: ["MaskedFormatter"]),
.testTarget(
name: "MaskedUITextFieldTests",
dependencies: ["MaskedUITextField"]),
]
)
| 23.25 | 73 | 0.540707 |
4818b879129fb0ecd6c715e5a4efb7dfdc976a01 | 4,015 | //
// CMLatLngBounds.swift
// CercaliaSDK
//
// Created by Marc on 29/6/17.
//
//
import UIKit
import TangramMap
import MapKit
/**
* The type Lat lng bounds.
*/
public class CMLatLngBounds: NSObject {
// Northeast corner of the bound.
public let northeast: CMLatLng
// Southwest corner of the bound.
public let southwest: CMLatLng
/**
* Instantiates a new Lat lng bounds.
*
* - parameter northeast: the northeast
* - parameter southwest: the southwest
*/
init(northeast: CMLatLng, southwest: CMLatLng) {
self.northeast = northeast;
self.southwest = southwest;
}
/**
* Get center.
*
* - returns: the lat lng
*/
public func getCenter() -> CMLatLng? {
let northeastMercator = self.northeast.toMercator();
let southwestMercator = self.southwest.toMercator();
let x = southwestMercator[1] + ((northeastMercator[1] - southwestMercator[1]) / 2);
let y = southwestMercator[0] + ((northeastMercator[0] - southwestMercator[0]) / 2);
return CMLatLng.fromMercator(lat: y, lng: x);
}
/**
* Include lat lng bounds.
*
* - parameter point: to be included in the new bounds
* - returns: A new LatLngBounds that contains this and the extra point.
*/
public func include(point: CMLatLng) -> CMLatLngBounds? {
return Builder()
.include(point: self.northeast)
.include(point: self.southwest)
.include(point: point)
.build();
}
/**
* The type Builder.
*/
public class Builder: NSObject {
/**
* The List.
*/
var list = Array<CMLatLng>();
/**
* Include builder.
*
* - parameter point: the point
* - returns: the builder
*/
public func include(point: CMLatLng) -> Builder {
list.append(point);
return self;
}
/**
* Build lat lng bounds.
*
* - returns: the lat lng bounds
*/
public func build() -> CMLatLngBounds? {
if (self.list.count == 0){
return nil;
}
else if (self.list.count == 1){
return CMLatLngBounds(northeast: self.list[0], southwest: self.list[0]);
}
else if (self.list.count == 2){
let line = MKPolyline(coordinates: self.getCoordinatesList(list: self.list), count: self.list.count);
return self.build(mapRect: line.boundingMapRect);
}
else if (self.list.count > 2){
let polygon = MKPolygon(coordinates: self.getCoordinatesList(list: self.list), count: self.list.count);
return self.build(mapRect: polygon.boundingMapRect);
}
return nil;
}
public func build(mapRect: MKMapRect) -> CMLatLngBounds? {
let northeastY = mapRect.origin.y + mapRect.size.height;
let northeastX = mapRect.origin.x + mapRect.size.width;
let northeast = CMLatLng(MKCoordinateForMapPoint(MKMapPoint(x: mapRect.origin.x, y: northeastY)).latitude,MKCoordinateForMapPoint(MKMapPoint(x: northeastX, y: mapRect.origin.y)).longitude);
let southwest = CMLatLng(MKCoordinateForMapPoint(mapRect.origin).latitude, MKCoordinateForMapPoint(mapRect.origin).longitude);
return CMLatLngBounds(northeast: northeast, southwest: southwest);
}
private func getCoordinatesList(list : Array<CMLatLng>) -> Array<CLLocationCoordinate2D> {
var coordinates = Array<CLLocationCoordinate2D>();
for coord: CMLatLng in list {
coordinates.append(CLLocationCoordinate2DMake(coord.lat, coord.lng));
}
return coordinates;
}
}
}
| 30.884615 | 201 | 0.562142 |
db090ac15cb9beffca0eab17919912e455e37da6 | 2,007 | //
// ASSpinner.swift
// superapp
//
// Created by Amit on 13/7/20.
// Copyright © 2020 Amit. All rights reserved.
//
import Foundation
import UIKit
@available(iOS 9.0, *)
public class ASProgressView: UIView {
var container: UIView?
var spinner: ASProgressSpinner?
var size = CGSize(width: 50, height: 50)
public override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
public required init?(coder: NSCoder) {
super.init(coder: coder)
setup()
}
public init() {
super.init(frame: CGRect.zero)
setup()
}
public func setup() {
setupUIElements()
setupConstraints()
}
public func setupUIElements() {
self.container = UIView()
self.addSubview(self.container.unsafelyUnwrapped)
self.spinner = ASProgressSpinner()
self.container?.addSubview(self.spinner.unsafelyUnwrapped)
}
public func setupConstraints() {
container?.translatesAutoresizingMaskIntoConstraints = false
container?.topAnchor.constraint(equalTo: topAnchor).isActive = true
container?.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
container?.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
container?.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
spinner?.translatesAutoresizingMaskIntoConstraints = false
spinner?.widthAnchor.constraint(equalToConstant: size.width).isActive = true
spinner?.heightAnchor.constraint(equalToConstant: size.height).isActive = true
spinner?.centerXAnchor.constraint(equalTo: container.unsafelyUnwrapped.centerXAnchor).isActive = true
spinner?.centerYAnchor.constraint(equalTo: container.unsafelyUnwrapped.centerYAnchor).isActive = true
}
public func getSpinner() -> ASProgressSpinner? {
return spinner
}
}
@available(iOS 9.0, *)
extension ASProgressView {
}
| 29.514706 | 109 | 0.669158 |
6782272e23510fe728390c2ce90c15e6c6c7de40 | 444 | //
// OptionType.swift
// goTapAPI
//
// Created by Dennis Pashkov on 10/13/16.
// Copyright © 2016 Tap Payments. All rights reserved.
//
public protocol OptionType: EnumType {
static func |(left: Self, right: Self) -> Self
static func &(left: Self, right: Self) -> Self
static func ^(left: Self, right: Self) -> Self
static prefix func ~(left: Self) -> Self
func contains(bit: Self) -> Bool
}
| 21.142857 | 55 | 0.608108 |
8f374541def7b78f528b48586a359bc5e9bef238 | 1,483 | //
// ButtonStyle.swift
// ProjectManager
//
// Created by Lee Jaeho on 2021/07/15.
//
import Foundation
import SwiftUI
struct AddButtonStyle : ButtonStyle{
func makeBody(configuration: Configuration) -> some View {
configuration.label.padding([.leading,.trailing]).padding([.top,.bottom],5).background(VisualEffectView(material: .contentBackground, blendingMode: .withinWindow)).clipShape(RoundedRectangle(cornerRadius: 10))
}
}
struct CancelButtonStyle : ButtonStyle{
func makeBody(configuration: Configuration) -> some View {
configuration.label.padding([.leading,.trailing]).padding([.top,.bottom],5).foregroundColor(.red).background(VisualEffectView(material: .contentBackground, blendingMode: .withinWindow)).clipShape(RoundedRectangle(cornerRadius: 10))
}
}
struct StartButtonStyle : ButtonStyle{
func makeBody(configuration: Configuration) -> some View {
configuration.label.padding([.leading,.trailing]).padding([.top,.bottom],5).background(VisualEffectView(material: .fullScreenUI, blendingMode: .withinWindow)).clipShape(RoundedRectangle(cornerRadius: 10))
}
}
struct PinButtonStyle : ButtonStyle{
var pin : Bool
func makeBody(configuration: Configuration) -> some View {
ZStack{
Image(systemName: pin ? "star.fill" : "star")
}
}
}
struct RemoveBackgroundStyle : ButtonStyle{
func makeBody(configuration: Configuration) -> some View {
configuration.label
}
}
| 34.488372 | 239 | 0.723533 |
1daf002708bb4bc65f923bcdb148fbbdb87fd19d | 852 | //
// MP3File.swift
// Chapters
//
// Created by Quentin Zervaas on 23/11/18.
// Copyright © 2018 Crunchy Bagel Pty Ltd. All rights reserved.
//
import Foundation
public class OutcastID3 {
public struct ID3Tag {
public let version: TagVersion
public let frames: [OutcastID3TagFrame]
public init(version: TagVersion, frames: [OutcastID3TagFrame]) {
self.version = version
self.frames = frames
}
}
public class MP3File {
public struct TagProperties {
public let tag: ID3Tag
public let startingByteOffset: UInt64
public let endingByteOffset: UInt64
}
let localUrl: URL
public init(localUrl: URL) throws {
self.localUrl = localUrl
}
}
public struct Frame {}
}
| 21.846154 | 72 | 0.588028 |
e6f447d2297d6f9136f980a2dc9cb13028787c89 | 3,152 | //
// CGFloat.swift
// Pods
//
// Created by away4m on 12/30/16.
//
//
import Foundation
/** The value of π as a CGFloat */
let π = CGFloat(Double.pi)
// MARK: - Properties
public extension CGFloat {
/**
* Returns 1.0 if a floating point value is positive; -1.0 if it is negative.
*/
public func sign() -> CGFloat {
return (self >= 0.0) ? 1.0 : -1.0
}
// Absolute of CGFloat value.
public var abs: CGFloat {
return Swift.abs(self)
}
// Ceil of CGFloat value.
public var ceil: CGFloat {
return Foundation.ceil(self)
}
// Radian value of degree input.
public var degreesToRadians: CGFloat {
return CGFloat(Double.pi) * self / 180.0
}
// Floor of CGFloat value.
public var floor: CGFloat {
return Foundation.floor(self)
}
// Degree value of radian input.
public var radiansToDegrees: CGFloat {
return self * 180 / CGFloat(Double.pi)
}
/// Generate a random CGFloat bounded by a closed interval range.
public static func random(_ range: ClosedRange<CGFloat>) -> CGFloat {
return CGFloat(arc4random()) / CGFloat(UInt64(UINT32_MAX)) * (range.upperBound - range.lowerBound) + range.lowerBound
}
/// Generate a random CGFloat bounded by a range from min to max.
public static func random(min: CGFloat, max: CGFloat) -> CGFloat {
return random(min ... max)
}
/**
Round self to a specified number of decimal places.
- parameter places: The number of decimal places by which to round self.
- returns: A CGFloat value, rounded to the specified number of decimal places.
Examples:
```
let val: CGFloat = 12.345678
val.rounded(places: 2) // 12.35
val.rounded(places: 3) // 12.346
```
*/
public func rounded(places: UInt) -> CGFloat {
let multiplier = pow(10, CGFloat(places))
return (self * multiplier).rounded() / multiplier
}
/**
* Ensures that the float value stays between the given values, inclusive.
*/
public func clamped(_ v1: CGFloat, _ v2: CGFloat) -> CGFloat {
let min = v1 < v2 ? v1 : v2
let max = v1 > v2 ? v1 : v2
return self < min ? min : (self > max ? max : self)
}
/**
* Ensures that the float value stays between the given values, inclusive.
*/
public mutating func clamp(_ v1: CGFloat, _ v2: CGFloat) -> CGFloat {
self = self.clamped(v1, v2)
return self
}
/**
* Returns the shortest angle between two angles. The result is always between
* -π and π.
*/
public func shortestAngleBetween(_ angle1: CGFloat, angle2: CGFloat) -> CGFloat {
let twoπ = π * 2.0
var angle = (angle2 - angle1).truncatingRemainder(dividingBy: twoπ)
if angle >= π {
angle = angle - twoπ
}
if angle <= -π {
angle = angle + twoπ
}
return angle
}
public func roundToPlaces(places: Int) -> CGFloat {
let divisor = pow(10.0, CGFloat(places))
return Darwin.round(self * divisor) / divisor
}
}
| 27.408696 | 125 | 0.595495 |
e53a8ee2cadb38955eb8b5463b3103e3530058b7 | 318 | /**
* Ink
* Copyright (c) John Sundell 2019
* MIT license, see LICENSE file for details
*/
internal extension Character {
var escaped: String? {
switch self {
case ">": return ">"
case "<": return "<"
case "&": return "&"
default: return nil
}
}
}
| 18.705882 | 44 | 0.525157 |
26211d01cb760ca2e8f8e31edd4d36713849b595 | 4,593 | //===----------------------------------------------------------------------===//
//
// This source file is part of the AWSSDKSwift open source project
//
// Copyright (c) 2017-2020 the AWSSDKSwift project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of AWSSDKSwift project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/swift-aws/aws-sdk-swift/blob/master/CodeGenerator/Sources/CodeGenerator/main.swift. DO NOT EDIT.
@_exported import AWSSDKSwiftCore
import NIO
/**
Client object for interacting with AWS IoTEventsData service.
AWS IoT Events monitors your equipment or device fleets for failures or changes in operation, and triggers actions when such events occur. AWS IoT Events Data API commands enable you to send inputs to detectors, list detectors, and view or update a detector's status.
*/
public struct IoTEventsData {
//MARK: Member variables
public let client: AWSClient
//MARK: Initialization
/// Initialize the IoTEventsData client
/// - parameters:
/// - accessKeyId: Public access key provided by AWS
/// - secretAccessKey: Private access key provided by AWS
/// - sessionToken: Token provided by STS.AssumeRole() which allows access to another AWS account
/// - region: Region of server you want to communicate with
/// - endpoint: Custom endpoint URL to use instead of standard AWS servers
/// - middlewares: Array of middlewares to apply to requests and responses
/// - httpClientProvider: HTTPClient to use. Use `createNew` if the client should manage its own HTTPClient.
public init(
accessKeyId: String? = nil,
secretAccessKey: String? = nil,
sessionToken: String? = nil,
region: AWSSDKSwiftCore.Region? = nil,
endpoint: String? = nil,
middlewares: [AWSServiceMiddleware] = [],
httpClientProvider: AWSClient.HTTPClientProvider = .createNew
) {
self.client = AWSClient(
accessKeyId: accessKeyId,
secretAccessKey: secretAccessKey,
sessionToken: sessionToken,
region: region,
partition: region?.partition ?? .aws,
service: "data.iotevents",
signingName: "ioteventsdata",
serviceProtocol: .restjson,
apiVersion: "2018-10-23",
endpoint: endpoint,
middlewares: middlewares,
possibleErrorTypes: [IoTEventsDataErrorType.self],
httpClientProvider: httpClientProvider
)
}
//MARK: API Calls
/// Sends a set of messages to the AWS IoT Events system. Each message payload is transformed into the input you specify ("inputName") and ingested into any detectors that monitor that input. If multiple messages are sent, the order in which the messages are processed isn't guaranteed. To guarantee ordering, you must send messages one at a time and wait for a successful response.
public func batchPutMessage(_ input: BatchPutMessageRequest, on eventLoop: EventLoop? = nil) -> EventLoopFuture<BatchPutMessageResponse> {
return client.send(operation: "BatchPutMessage", path: "/inputs/messages", httpMethod: "POST", input: input, on: eventLoop)
}
/// Updates the state, variable values, and timer settings of one or more detectors (instances) of a specified detector model.
public func batchUpdateDetector(_ input: BatchUpdateDetectorRequest, on eventLoop: EventLoop? = nil) -> EventLoopFuture<BatchUpdateDetectorResponse> {
return client.send(operation: "BatchUpdateDetector", path: "/detectors", httpMethod: "POST", input: input, on: eventLoop)
}
/// Returns information about the specified detector (instance).
public func describeDetector(_ input: DescribeDetectorRequest, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeDetectorResponse> {
return client.send(operation: "DescribeDetector", path: "/detectors/{detectorModelName}/keyValues/", httpMethod: "GET", input: input, on: eventLoop)
}
/// Lists detectors (the instances of a detector model).
public func listDetectors(_ input: ListDetectorsRequest, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListDetectorsResponse> {
return client.send(operation: "ListDetectors", path: "/detectors/{detectorModelName}", httpMethod: "GET", input: input, on: eventLoop)
}
}
| 51.033333 | 387 | 0.682125 |
6902b257155b2d24c142e2970b3f14163e5ad1e7 | 1,348 | //
// AppDelegate.swift
// Prework
//
// Created by Huang, Fenghai on 8/30/21.
//
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 36.432432 | 179 | 0.744807 |
20acdf336645005bbb807aa484544ba92bc4683a | 2,472 | import UIKit
extension UITouch.Phase {
// Returns 1 for all events where the fingers are on the glass.
var isTouching: Bool {
return self == .began || self == .moved || self == .stationary
}
var eventMask: IOHID.DigitizerEventMask {
var mask: IOHID.DigitizerEventMask = []
if self == .began || self == .ended || self == .cancelled {
mask.insert(.touch)
mask.insert(.range)
}
if self == .moved {
mask.insert(.position)
}
if self == .cancelled {
mask.insert(.cancel)
}
return mask
}
}
extension UIDevice {
public var maxNumberOfFingers: Int {
switch self.userInterfaceIdiom {
case .phone, .carPlay:
return 5
case .pad:
return 10
default:
return 0
}
}
public var supportsStylus: Bool {
return self.userInterfaceIdiom == .pad
}
}
extension UIWindow {
convenience init(wrapping viewController: UIViewController) {
self.init(frame: UIScreen.main.bounds)
self.rootViewController = viewController
}
}
extension UIViewController {
convenience init(wrapping view: UIView, alignment: EventGenerator.WrappingAlignment) {
self.init(nibName: nil, bundle: nil)
view.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(view)
switch alignment {
case .fill:
NSLayoutConstraint.activate([
view.topAnchor.constraint(equalTo: self.view.topAnchor),
view.bottomAnchor.constraint(equalTo: self.view.bottomAnchor),
view.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
view.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
])
case .center:
NSLayoutConstraint.activate([
view.centerYAnchor.constraint(equalTo: self.view.centerYAnchor),
view.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
view.topAnchor.constraint(greaterThanOrEqualTo: self.view.topAnchor),
view.bottomAnchor.constraint(lessThanOrEqualTo: self.view.bottomAnchor),
view.leadingAnchor.constraint(greaterThanOrEqualTo: self.view.leadingAnchor),
view.trailingAnchor.constraint(lessThanOrEqualTo: self.view.trailingAnchor),
])
}
}
}
| 31.291139 | 93 | 0.613673 |
148754e6bed88e0972013e8175c80c68407c3cfd | 6,094 | // swift-tools-version:5.3
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "Permission",
platforms: [
.iOS(.v10),
],
products: [
.library(
name: "Permission",
targets: ["Permission"]
),
.library(
name: "Permission/Bluetooth",
targets: ["Permission/Bluetooth"]
),
.library(
name: "Permission/Camera",
targets: ["Permission/Camera"]
),
.library(
name: "Permission/Contacts",
targets: ["Permission/Contacts"]
),
.library(
name: "Permission/Events",
targets: ["Permission/Events"]
),
.library(
name: "Permission/Location",
targets: ["Permission/Location"]
),
.library(
name: "Permission/Microphone",
targets: ["Permission/Microphone"]
), .library(
name: "Permission/Motion",
targets: ["Permission/Motion"]
),
.library(
name: "Permission/Notifications",
targets: ["Permission/Notifications"]
),
.library(
name: "Permission/Photos",
targets: ["Permission/Photos"]
),
.library(
name: "Permission/Reminders",
targets: ["Permission/Reminders"]
),
.library(
name: "Permission/SpeechRecognizer",
targets: ["Permission/SpeechRecognizer"]
),
.library(
name: "Permission/MediaLibrary",
targets: ["Permission/MediaLibrary"]
),
.library(
name: "Permission/Siri",
targets: ["Permission/Siri"]
),
],
targets: [
.target(
name: "Permission",
dependencies: [],
path: "Source",
sources: [
"Supporting Files/Utilities.swift",
"Core"
]
),
.target(
name: "Permission/Bluetooth",
dependencies: ["Permission"],
path: "Source/Types",
sources: [
"Bluetooth.swift",
],
cSettings: [
.define("PERMISSION_BLUETOOTH"),
]
),
.target(
name: "Permission/Camera",
dependencies: ["Permission"],
path: "Source/Types",
sources: [
"Camera.swift",
],
cSettings: [
.define("PERMISSION_CAMERA"),
]
),
.target(
name: "Permission/Contacts",
dependencies: ["Permission"],
path: "Source/Types",
sources: [
"Contacts.swift",
],
cSettings: [
.define("PERMISSION_CONTACTS"),
]
),
.target(
name: "Permission/Events",
dependencies: ["Permission"],
path: "Source/Types",
sources: [
"Events.swift",
],
cSettings: [
.define("PERMISSION_EVENTS"),
]
),
.target(
name: "Permission/Location",
dependencies: ["Permission"],
path: "Source/Types",
sources: [
"Location.swift",
],
cSettings: [
.define("PERMISSION_LOCATION"),
]
), .target(
name: "Permission/Microphone",
dependencies: ["Permission"],
path: "Source/Types",
sources: [
"Microphone.swift",
],
cSettings: [
.define("PERMISSION_MICROPHONE"),
]
),
.target(
name: "Permission/Motion",
dependencies: ["Permission"],
path: "Source/Types",
sources: [
"Motion.swift",
],
cSettings: [
.define("PERMISSION_MOTION"),
]
),
.target(
name: "Permission/Notifications",
dependencies: ["Permission"],
path: "Source/Types",
sources: [
"Notifications.swift",
],
cSettings: [
.define("PERMISSION_NOTIFICATIONS"),
]
),
.target(
name: "Permission/Photos",
dependencies: ["Permission"],
path: "Source/Types",
sources: [
"Photos.swift",
],
cSettings: [
.define("PERMISSION_PHOTOS"),
]
),
.target(
name: "Permission/Reminders",
dependencies: ["Permission"],
path: "Source/Types",
sources: [
"Reminders.swift",
],
cSettings: [
.define("PERMISSION_REMINDERS"),
]
),
.target(
name: "Permission/SpeechRecognizer",
dependencies: ["Permission"],
path: "Source/Types",
sources: [
"SpeechRecognizer.swift",
],
cSettings: [
.define("PERMISSION_SPEECH_RECOGNIZER"),
]
),
.target(
name: "Permission/MediaLibrary",
dependencies: ["Permission"],
path: "Source/Types",
sources: [
"MediaLibrary.swift",
],
cSettings: [
.define("PERMISSION_MEDIA_LIBRARY"),
]
),
.target(
name: "Permission/Siri",
dependencies: ["Permission"],
path: "Source/Types",
sources: [
"Siri.swift",
],
cSettings: [
.define("PERMISSION_SIRI"),
]
),
]
)
| 27.45045 | 96 | 0.426321 |
48b46b632d166158a72a38da4993186f3b7edfa7 | 12,229 | //
// TransactionsTableViewController.swift
// breadwallet
//
// Created by Adrian Corscadden on 2016-11-16.
// Copyright © 2016 breadwallet LLC. All rights reserved.
//
import UIKit
private let promptDelay: TimeInterval = 0.6
enum TransactionFilterMode {
case showAll
case showOutgoing
case showIncoming
}
// global
// only show table row animation once!
var hideRows: Bool = true
var firstLogin: Bool = true
class TransactionsTableViewController : UITableViewController, Subscriber, Trackable {
//MARK: - Public
init(store: Store, didSelectTransaction: @escaping ([Transaction], Int) -> Void, kvStore: BRReplicatedKVStore? = nil, filterMode: TransactionFilterMode = .showAll) {
self.store = store
self.kvStore = kvStore
self.didSelectTransaction = didSelectTransaction
self.isBtcSwapped = store.state.isBtcSwapped
self.filterMode = filterMode
super.init(nibName: nil, bundle: nil)
}
let filterMode: TransactionFilterMode
let didSelectTransaction: ([Transaction], Int) -> Void
var filters: [TransactionFilter] = [] {
didSet {
transactions = filters.reduce(allTransactions, { $0.filter($1) })
tableView.reloadData()
}
}
var kvStore: BRReplicatedKVStore? {
didSet {
tableView.reloadData()
}
}
var walletManager: WalletManager?
//MARK: - Private
private let store: Store
private let headerCellIdentifier = "HeaderCellIdentifier"
private let transactionCellIdentifier = "TransactionCellIdentifier"
private var transactions: [Transaction] = []
private var allTransactions: [Transaction] = [] {
didSet {
switch filterMode {
case .showAll:
transactions = allTransactions
case .showIncoming:
transactions = allTransactions.filter({ (t) -> Bool in
t.direction == .received
})
case .showOutgoing:
transactions = allTransactions.filter({ (t) -> Bool in
t.direction == .sent
})
}
}
}
private var isBtcSwapped: Bool {
didSet {
reload()
}
}
private var rate: Rate? {
didSet {
reload()
}
}
private let emptyMessage = UILabel.wrapping(font: .customBody(size: 16.0), color: .grayTextTint)
private var currentPrompt: Prompt? {
didSet {
if currentPrompt != nil && oldValue == nil {
tableView.beginUpdates()
tableView.insertSections(IndexSet(integer: 0), with: .automatic)
tableView.endUpdates()
} else if currentPrompt == nil && oldValue != nil {
tableView.beginUpdates()
tableView.deleteSections(IndexSet(integer: 0), with: .automatic)
tableView.endUpdates()
}
}
}
private var hasExtraSection: Bool {
return (currentPrompt != nil)
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
// this will only be called once after login (create a fancy animation)
cell.clipsToBounds = true
if firstLogin {
cell.transform = CGAffineTransform(translationX: 0, y: 800)
UIView.spring(0.5 + (Double(indexPath.row) * 0.2), animations: {
cell.transform = CGAffineTransform.identity
}) { (completed) in
firstLogin = false
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(TransactionCardViewCell.self, forCellReuseIdentifier: transactionCellIdentifier)
tableView.register(TransactionCardViewCell.self, forCellReuseIdentifier: headerCellIdentifier)
tableView.separatorStyle = .none
tableView.estimatedRowHeight = 100.0
tableView.rowHeight = UITableViewAutomaticDimension
tableView.backgroundColor = UIColor(red: 0x01 / 255, green: 0x69 / 255, blue: 0x59 / 255, alpha: 1) //191b2a //016959
// subscriptions
store.subscribe(self, selector: { $0.walletState.transactions != $1.walletState.transactions },
callback: { state in
self.allTransactions = state.walletState.transactions
self.reload()
})
store.subscribe(self, selector: { $0.isLoginRequired != $1.isLoginRequired },
callback: { state in
guard !state.isLoginRequired else { return }
hideRows = false
self.tableView.reloadData()
})
// create animation
store.subscribe(self, selector: { $0.walletState.syncState != $1.walletState.syncState || $0.isLoginRequired != $1.isLoginRequired },
callback: { state in
if !state.isLoginRequired && state.walletState.syncState == .success {
DispatchQueue.main.asyncAfter(deadline: .now(), execute: {
hideRows = false
})
}
})
store.subscribe(self,
selector: { $0.isBtcSwapped != $1.isBtcSwapped },
callback: { self.isBtcSwapped = $0.isBtcSwapped })
store.subscribe(self,
selector: { $0.currentRate != $1.currentRate},
callback: { self.rate = $0.currentRate })
store.subscribe(self, selector: { $0.maxDigits != $1.maxDigits }, callback: {_ in
self.reload()
})
store.subscribe(self, selector: { $0.recommendRescan != $1.recommendRescan }, callback: { _ in
self.attemptShowPrompt()
})
store.subscribe(self, selector: { $0.walletState.syncState != $1.walletState.syncState }, callback: { _ in
self.reload()
})
store.subscribe(self, name: .didUpgradePin, callback: { _ in
if self.currentPrompt?.type == .upgradePin {
self.currentPrompt = nil
}
})
store.subscribe(self, name: .didEnableShareData, callback: { _ in
if self.currentPrompt?.type == .shareData {
self.currentPrompt = nil
}
})
store.subscribe(self, name: .didWritePaperKey, callback: { _ in
if self.currentPrompt?.type == .paperKey {
self.currentPrompt = nil
}
})
store.subscribe(self, name: .txMemoUpdated(""), callback: {
guard let trigger = $0 else { return }
if case .txMemoUpdated(let txHash) = trigger {
self.reload(txHash: txHash)
}
})
emptyMessage.textAlignment = .center
emptyMessage.text = S.TransactionDetails.emptyMessage
reload()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
private func reload(txHash: String) {
self.transactions.enumerated().forEach { i, tx in
if tx.hash == txHash {
DispatchQueue.main.async {
self.tableView.beginUpdates()
self.tableView.reloadRows(at: [IndexPath(row: i, section: self.hasExtraSection ? 1 : 0)], with: .automatic)
self.tableView.endUpdates()
}
}
}
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return hasExtraSection ? 2 : 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if hasExtraSection && section == 0 {
return 1
} else {
return hideRows ? 0 : transactions.count
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if hasExtraSection && indexPath.section == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: headerCellIdentifier, for: indexPath)
if let transactionCell = cell as? TransactionCardViewCell {
transactionCell.setStyle(.single)
transactionCell.container.subviews.forEach {
$0.removeFromSuperview()
}
if let prompt = currentPrompt {
transactionCell.container.addSubview(prompt)
prompt.constrain(toSuperviewEdges: nil)
prompt.constrain([
prompt.heightAnchor.constraint(equalToConstant: 88.0) ])
transactionCell.selectionStyle = .default
}
}
return cell
} else {
let numRows = tableView.numberOfRows(inSection: indexPath.section)
var style: TransactionCellStyle = .middle
if numRows == 1 {
style = .single
}
if numRows > 1 {
if indexPath.row == 0 {
style = .first
}
if indexPath.row == numRows - 1 {
style = .last
}
}
let cell = tableView.dequeueReusableCell(withIdentifier: transactionCellIdentifier, for: indexPath)
if let transactionCell = cell as? TransactionCardViewCell, let rate = rate {
transactionCell.setStyle(style)
transactions[indexPath.row].kvStore = kvStore
transactionCell.setTransaction(transactions[indexPath.row], isBtcSwapped: isBtcSwapped, rate: rate, maxDigits: store.state.maxDigits, isSyncing: store.state.walletState.syncState != .success)
transactionCell.layer.zPosition = CGFloat(indexPath.row)
}
return cell
}
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if hasExtraSection && section == 1 {
return UIView(color: .clear)
} else {
return nil
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
didSelectTransaction(transactions, indexPath.row)
}
private func reload() {
tableView.reloadData()
if transactions.count == 0 {
if emptyMessage.superview == nil {
tableView.addSubview(emptyMessage)
emptyMessage.constrain([
emptyMessage.centerXAnchor.constraint(equalTo: tableView.centerXAnchor),
emptyMessage.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: -accountHeaderHeight),
emptyMessage.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -C.padding[2]) ])
}
} else {
emptyMessage.removeFromSuperview()
}
}
private func attemptShowPrompt() {
guard let walletManager = walletManager else { return }
let types = PromptType.defaultOrder
if let type = types.first(where: { $0.shouldPrompt(walletManager: walletManager, state: store.state) }) {
//self.saveEvent("prompt.\(type.name).displayed")
currentPrompt = Prompt(type: type)
currentPrompt?.close.tap = { [weak self] in
//self?.saveEvent("prompt.\(type.name).dismissed")
self?.currentPrompt = nil
}
if type == .biometrics {
UserDefaults.hasPromptedBiometrics = true
}
if type == .shareData {
UserDefaults.hasPromptedShareData = true
}
} else {
currentPrompt = nil
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 37.743827 | 207 | 0.573309 |
1da1f89620bf976f2a205bf36de896270a030c75 | 1,919 | //
// MakerConfiguration.swift
// Pizzaiolo
//
// Created by Fadion Dashi on 24/03/17.
// Copyright © 2017 Fadion Dashi. All rights reserved.
//
import Foundation
enum LayoutType {
case title
case button
}
struct MakerConfiguration {
static let basePrice = 299
static let layout = [
["type": LayoutType.title, "title": "Base"],
["type": LayoutType.button, "title": "Tomato Sauce", "price": 100],
["type": LayoutType.title, "title": "Cheese"],
["type": LayoutType.button, "title": "Parmigiano", "price": 200],
["type": LayoutType.button, "title": "Mozzarella", "price": 150],
["type": LayoutType.button, "title": "Gorgonzola", "price": 220],
["type": LayoutType.title, "title": "Meat & Fish"],
["type": LayoutType.button, "title": "Salami", "price": 130],
["type": LayoutType.button, "title": "Speck", "price": 220],
["type": LayoutType.button, "title": "Anchovies", "price": 170],
["type": LayoutType.button, "title": "Shrimps", "price": 260],
["type": LayoutType.button, "title": "Squid", "price": 210],
["type": LayoutType.title, "title": "Vegetables"],
["type": LayoutType.button, "title": "Peppers", "price": 60],
["type": LayoutType.button, "title": "Mushrooms", "price": 170],
["type": LayoutType.button, "title": "Tomatoes", "price": 70],
["type": LayoutType.button, "title": "Olives", "price": 90],
["type": LayoutType.button, "title": "Onions", "price": 40],
["type": LayoutType.button, "title": "Truffles", "price": 440],
["type": LayoutType.title, "title": "Herbs"],
["type": LayoutType.button, "title": "Basil", "price": 50],
["type": LayoutType.button, "title": "Rosemary", "price": 60],
["type": LayoutType.button, "title": "Parsley", "price": 40],
]
}
| 39.163265 | 75 | 0.566441 |
9149082198516d33c52537bf51a0d1824f4af9b4 | 4,713 | //
// Copyright (c) 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
import Firebase
@objc(EmailViewController)
class EmailViewController: UIViewController {
@IBOutlet weak var emailField: UITextField!
@IBOutlet weak var passwordField: UITextField!
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
@IBAction func didTapEmailLogin(_ sender: AnyObject) {
guard let email = self.emailField.text, let password = self.passwordField.text else {
self.showMessagePrompt("email/password can't be empty")
return
}
showSpinner {
// [START headless_email_auth]
Auth.auth().signIn(withEmail: email, password: password) { [weak self] user, error in
guard let strongSelf = self else { return }
// [START_EXCLUDE]
strongSelf.hideSpinner {
if let error = error {
strongSelf.showMessagePrompt(error.localizedDescription)
return
}
strongSelf.navigationController?.popViewController(animated: true)
}
// [END_EXCLUDE]
}
// [END headless_email_auth]
}
}
/** @fn requestPasswordReset
@brief Requests a "password reset" email be sent.
*/
@IBAction func didRequestPasswordReset(_ sender: AnyObject) {
showTextInputPrompt(withMessage: "Email:") { [weak self] userPressedOK, email in
guard let strongSelf = self, let email = email else {
return
}
strongSelf.showSpinner {
// [START password_reset]
Auth.auth().sendPasswordReset(withEmail: email) { error in
// [START_EXCLUDE]
strongSelf.hideSpinner {
if let error = error {
strongSelf.showMessagePrompt(error.localizedDescription)
return
}
strongSelf.showMessagePrompt("Sent")
}
// [END_EXCLUDE]
}
// [END password_reset]
}
}
}
/** @fn getProvidersForEmail
@brief Prompts the user for an email address, calls @c FIRAuth.getProvidersForEmail:callback:
and displays the result.
*/
@IBAction func didGetProvidersForEmail(_ sender: AnyObject) {
showTextInputPrompt(withMessage: "Email:") { [weak self] userPressedOK, email in
guard let strongSelf = self else { return }
guard let email = email else {
strongSelf.showMessagePrompt("email can't be empty")
return
}
strongSelf.showSpinner {
// [START get_providers]
Auth.auth().fetchProviders(forEmail: email) { providers, error in
// [START_EXCLUDE]
strongSelf.hideSpinner {
if let error = error {
strongSelf.showMessagePrompt(error.localizedDescription)
return
}
strongSelf.showMessagePrompt(providers!.joined(separator: ", "))
}
// [END_EXCLUDE]
}
// [END get_providers]
}
}
}
@IBAction func didCreateAccount(_ sender: AnyObject) {
showTextInputPrompt(withMessage: "Email:") { [weak self] userPressedOK, email in
guard let strongSelf = self else { return }
guard let email = email else {
strongSelf.showMessagePrompt("email can't be empty")
return
}
strongSelf.showTextInputPrompt(withMessage: "Password:") { userPressedOK, password in
guard let password = password else {
strongSelf.showMessagePrompt("password can't be empty")
return
}
strongSelf.showSpinner {
// [START create_user]
Auth.auth().createUser(withEmail: email, password: password) { authResult, error in
// [START_EXCLUDE]
strongSelf.hideSpinner {
guard let user = authResult?.user, error == nil else {
strongSelf.showMessagePrompt(error!.localizedDescription)
return
}
print("\(user.email!) created")
strongSelf.navigationController?.popViewController(animated: true)
}
// [END_EXCLUDE]
}
// [END create_user]
}
}
}
}
}
| 33.190141 | 96 | 0.626565 |
d5a7435b3cd98b0a78232d9e75ddfd2c3c090590 | 3,390 | //
// IdentityMLModelLoader.swift
// StripeIdentity
//
// Created by Mel Ludowise on 2/1/22.
//
import Foundation
import CoreML
import Vision
@_spi(STP) import StripeCore
enum IdentityMLModelLoaderError: Error {
case invalidURL
}
protocol IdentityMLModelLoaderProtocol {
var documentModelsFuture: Future<DocumentScannerProtocol> { get }
func startLoadingDocumentModels(
from documentModelURLs: VerificationPageStaticContentDocumentCaptureModels
)
}
/**
Loads the ML models used by Identity.
*/
@available(iOS 13, *)
final class IdentityMLModelLoader: IdentityMLModelLoaderProtocol {
private static let cacheDirectoryName = "com.stripe.stripe-identity"
// MARK: Instance Properties
let mlModelLoader: MLModelLoader
private let documentMLModelsPromise = Promise<DocumentScannerProtocol>()
/// Resolves to the ML models needed for document scanning
var documentModelsFuture: Future<DocumentScannerProtocol> {
return documentMLModelsPromise
}
// MARK: Init
init() {
let config = URLSessionConfiguration.ephemeral
config.waitsForConnectivity = true
let urlSession = URLSession(configuration: config)
self.mlModelLoader = .init(
fileDownloader: FileDownloader(urlSession: urlSession),
cacheDirectory: IdentityMLModelLoader.createCacheDirectory()
)
}
static func createCacheDirectory() -> URL {
// Since the models are unlikely to be used after the user has finished
// verifying their identity, cache them to a temp directory so the
// system will delete them when it needs the space.
let tempDirectory = URL(
fileURLWithPath: NSTemporaryDirectory(),
isDirectory: true
)
// Create a name-spaced subdirectory inside the temp directory so
// we don't clash with any other files the app is storing here.
let cacheDirectory = tempDirectory.appendingPathComponent(IdentityMLModelLoader.cacheDirectoryName)
do {
try FileManager.default.createDirectory(
at: cacheDirectory,
withIntermediateDirectories: true,
attributes: nil
)
return cacheDirectory
} catch {
// If creating the subdirectory fails, use temp directory directly
return tempDirectory
}
}
// MARK: Load models
/**
Starts loading the ML models needed for document scanning. When the models
are done loading, they can be retrieved by observing `documentModelsFuture`.
- Parameters:
- documentModelURLs: The URLs of all the ML models required to scan documents
*/
func startLoadingDocumentModels(
from documentModelURLs: VerificationPageStaticContentDocumentCaptureModels
) {
guard let idDetectorURL = URL(string: documentModelURLs.idDetectorUrl) else {
documentMLModelsPromise.reject(with: IdentityMLModelLoaderError.invalidURL)
return
}
mlModelLoader.loadVisionModel(
fromRemote: idDetectorURL
).chained { idDetectorModel in
return Promise(value: DocumentScanner(idDetectorModel: idDetectorModel))
}.observe { [weak self] result in
self?.documentMLModelsPromise.fullfill(with: result)
}
}
}
| 31.388889 | 107 | 0.683186 |
bf16abfef9ce262f36126de5b57b1aefae7a1aa7 | 8,540 | //
// String+Utils.swift
// CHPlugin
//
// Created by Haeun Chung on 17/02/2017.
// Copyright © 2017 ZOYI. All rights reserved.
//
import Foundation
enum StringTagType : String {
case bold = "b"
}
extension NSAttributedString {
func addFont(
_ font: UIFont,
color: UIColor,
style: NSParagraphStyle,
on range: NSRange) -> NSAttributedString {
let attributedText = NSMutableAttributedString(attributedString: self)
attributedText.addAttributes(
[.paragraphStyle: style,
.foregroundColor: color,
.font: font,
.baselineOffset: (style.minimumLineHeight - font.lineHeight)/4],
range: range
)
return attributedText
}
func combine(_ text: NSAttributedString) -> NSAttributedString {
let attributedText = NSMutableAttributedString(attributedString: self)
attributedText.append(text)
return attributedText
}
func replace(_ target: String, with text: String) -> NSAttributedString {
let str = NSMutableAttributedString(attributedString: self)
if let range = str.string.nsRange(of: target) {
str.replaceCharacters(in: range, with: text)
}
return str
}
var dropTailingNewline: NSAttributedString {
if self.string.hasSuffix("\n") {
return self.attributedSubstring(from: NSMakeRange(0, self.length - 1))
} else {
return self
}
}
func split(seperateBy: String) -> [NSAttributedString] {
let input = self.string
let separatedInput = input.components(separatedBy: seperateBy)
var output = [NSAttributedString]()
var start = 0
for sub in separatedInput {
let range = NSRange(location: start, length: sub.utf16.count)
let attribStr = self.attributedSubstring(from: range)
output.append(attribStr)
start += range.length + seperateBy.count
}
return output
}
}
extension RangeExpression where Bound == String.Index {
func nsRange<S: StringProtocol>(in string: S) -> NSRange {
.init(self, in: string)
}
}
extension StringProtocol where Index == String.Index {
func nsRange(from range: Range<Index>) -> NSRange {
return NSRange(range, in: self)
}
}
extension StringProtocol {
func nsRange<S: StringProtocol>(
of string: S,
options: String.CompareOptions = [],
range: Range<Index>? = nil,
locale: Locale? = nil) -> NSRange? {
self.range(
of: string,
options: options,
range: range ?? startIndex..<endIndex,
locale: locale ?? .current)?.nsRange(in: self)
}
func nsRanges<S: StringProtocol>(
of string: S,
options: String.CompareOptions = [],
range: Range<Index>? = nil,
locale: Locale? = nil) -> [NSRange] {
var start = range?.lowerBound ?? startIndex
let end = range?.upperBound ?? endIndex
var ranges: [NSRange] = []
while start < end,
let range = self.range(
of: string,
options: options,
range: start..<end,
locale: locale ?? .current) {
ranges.append(range.nsRange(in: self))
start = range.lowerBound < range.upperBound ? range.upperBound :
index(range.lowerBound, offsetBy: 1, limitedBy: endIndex) ?? endIndex
}
return ranges
}
}
extension String {
func addFont(_ font: UIFont, color: UIColor, on range: NSRange) -> NSMutableAttributedString {
let attributedText = NSMutableAttributedString(string: self)
attributedText.addAttributes([
.foregroundColor: color,
.font: font], range: range)
return attributedText
}
func addLineHeight(
height: CGFloat,
font: UIFont,
color: UIColor,
alignment: NSTextAlignment = .left,
lineBreakMode: NSLineBreakMode = .byWordWrapping) -> NSMutableAttributedString {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = lineBreakMode
paragraphStyle.minimumLineHeight = height
paragraphStyle.alignment = alignment
let attributes: [NSAttributedString.Key: Any] = [
.foregroundColor: color,
.font: font,
.paragraphStyle: paragraphStyle,
.baselineOffset: (paragraphStyle.minimumLineHeight - font.lineHeight)/4
]
return NSMutableAttributedString(string: self, attributes: attributes)
}
func replace(_ target: String, withString: String) -> String {
return self.replacingOccurrences(of: target, with: withString, options: NSString.CompareOptions.literal, range: nil)
}
subscript (i: Int) -> Character {
return self[self.index(self.startIndex, offsetBy: i)]
}
static func randomString(length: Int) -> String {
let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
let len = UInt32(letters.length)
var randomString = ""
for _ in 0 ..< length {
let rand = arc4random_uniform(len)
var nextChar = letters.character(at: Int(rand))
randomString += NSString(characters: &nextChar, length: 1) as String
}
return randomString
}
func versionToInt() -> [Int] {
return self.components(separatedBy: ".")
.map { Int.init($0) ?? 0 }
}
func decodeHTML() throws -> String? {
guard let data = data(using: .utf8) else { return nil }
return try NSAttributedString(
data: data,
options: [
.documentType: NSAttributedString.DocumentType.html,
//iOS 8 symbol error
//https://stackoverflow.com/questions/46484650/documentreadingoptionkey-key-corrupt-after-swift4-migration
//NSAttributedString.DocumentReadingOptionKey("CharacterEncoding"): String.Encoding.utf8.rawValue
.characterEncoding: String.Encoding.utf8.rawValue
],
documentAttributes: nil).string
}
func guessLanguage() -> String {
let length = self.utf16.count
let languageCode = CFStringTokenizerCopyBestStringLanguage(
self as CFString, CFRange(location: 0, length: length)
) as String? ?? ""
let locale = Locale(identifier: languageCode)
return locale.localizedString(forLanguageCode: languageCode) ?? "Unknown"
}
}
extension UnicodeScalar {
var isEmoji: Bool {
switch value {
case 0x1F600...0x1F64F, // Emoticons
0x1F300...0x1F5FF, // Misc Symbols and Pictographs
0x1F680...0x1F6FF, // Transport and Map
0x1F1E6...0x1F1FF, // Regional country flags
0x2600...0x26FF, // Misc symbols
0x2700...0x27BF, // Dingbats
0xFE00...0xFE0F, // Variation Selectors
0x1F900...0x1F9FF, // Supplemental Symbols and Pictographs
65024...65039, // Variation selector
8400...8447: // Combining Diacritical Marks for Symbols
return true
default: return false
}
}
var isZeroWidthJoiner: Bool {
return value == 8205
}
}
extension String {
var glyphCount: Int {
let richText = NSAttributedString(string: self)
let line = CTLineCreateWithAttributedString(richText)
return CTLineGetGlyphCount(line)
}
var isSingleEmoji: Bool {
return glyphCount == 1 && containsEmoji
}
var containsEmoji: Bool {
return unicodeScalars.contains { $0.isEmoji }
}
var containsOnlyEmoji: Bool {
return !isEmpty && !unicodeScalars.contains(where: {
!$0.isEmoji && !$0.isZeroWidthJoiner
})
}
var emojiString: String {
return emojiScalars.map { String($0) }.reduce("", +)
}
var emojis: [String] {
var scalars: [[UnicodeScalar]] = []
var currentScalarSet: [UnicodeScalar] = []
var previousScalar: UnicodeScalar?
for scalar in emojiScalars {
if let prev = previousScalar, !prev.isZeroWidthJoiner && !scalar.isZeroWidthJoiner {
scalars.append(currentScalarSet)
currentScalarSet = []
}
currentScalarSet.append(scalar)
previousScalar = scalar
}
scalars.append(currentScalarSet)
return scalars.map { $0.map{ String($0) } .reduce("", +) }
}
fileprivate var emojiScalars: [UnicodeScalar] {
var chars: [UnicodeScalar] = []
var previous: UnicodeScalar?
for cur in unicodeScalars {
if let previous = previous, previous.isZeroWidthJoiner && cur.isEmoji {
chars.append(previous)
chars.append(cur)
} else if cur.isEmoji {
chars.append(cur)
}
previous = cur
}
return chars
}
}
func unwrap(any: Any) -> Any {
let mi = Mirror(reflecting: any)
if mi.displayStyle != .optional {
return any
}
if mi.children.count == 0 { return NSNull() }
let (_, some) = mi.children.first!
return some
}
| 28.092105 | 120 | 0.659485 |
2f3633e3ddfd99bb808d2cf4e1687af16b0232f5 | 1,465 | /**
* Copyright IBM Corporation 2015
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
import RestKit
/**
**Taxonomy**
Extracted topic categories. Can be up to five levels deeps.
For example:
/finance/personal finance/lending/credit cards
*/
public struct Taxonomy: JSONDecodable {
/** will be "no" if categorization doesn't meet confidence standards */
public let confident: String?
/** detected category */
public let label: String?
/** confidence score, 0.0 - 1.0 (higher is better) */
public let score: Double?
/// Used internally to initialize a Taxonomy object
public init(json: JSON) throws {
confident = try? json.getString(at: "confident")
label = try? json.getString(at: "label")
if let scoreString = try? json.getString(at: "score") {
score = Double(scoreString)
} else {
score = nil
}
}
}
| 27.12963 | 75 | 0.668259 |
5d3fd67bc9abe634aa70e20f2114210f62e0e80c | 5,428 | import XCTest
import GRDB
#if GRDB_COMPARE
import SQLite
#endif
private let insertedRowCount = 20_000
// Here we insert rows, referencing statement arguments by name.
class InsertNamedValuesTests: XCTestCase {
func testGRDB() {
let databaseFileName = "GRDBPerformanceTests-\(ProcessInfo.processInfo.globallyUniqueString).sqlite"
let databasePath = (NSTemporaryDirectory() as NSString).appendingPathComponent(databaseFileName)
defer {
let dbQueue = try! DatabaseQueue(path: databasePath)
try! dbQueue.inDatabase { db in
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, insertedRowCount)
XCTAssertEqual(try Int.fetchOne(db, "SELECT MIN(i0) FROM items")!, 0)
XCTAssertEqual(try Int.fetchOne(db, "SELECT MAX(i9) FROM items")!, insertedRowCount - 1)
}
try! FileManager.default.removeItem(atPath: databasePath)
}
measure {
_ = try? FileManager.default.removeItem(atPath: databasePath)
let dbQueue = try! DatabaseQueue(path: databasePath)
try! dbQueue.inDatabase { db in
try db.execute("CREATE TABLE items (i0 INT, i1 INT, i2 INT, i3 INT, i4 INT, i5 INT, i6 INT, i7 INT, i8 INT, i9 INT)")
}
try! dbQueue.inTransaction { db in
let statement = try! db.makeUpdateStatement("INSERT INTO items (i0, i1, i2, i3, i4, i5, i6, i7, i8, i9) VALUES (:i0, :i1, :i2, :i3, :i4, :i5, :i6, :i7, :i8, :i9)")
for i in 0..<insertedRowCount {
try statement.execute(arguments: ["i0": i, "i1": i, "i2": i, "i3": i, "i4": i, "i5": i, "i6": i, "i7": i, "i8": i, "i9": i])
}
return .commit
}
}
}
#if GRDB_COMPARE
func testFMDB() {
let databaseFileName = "GRDBPerformanceTests-\(ProcessInfo.processInfo.globallyUniqueString).sqlite"
let databasePath = (NSTemporaryDirectory() as NSString).appendingPathComponent(databaseFileName)
defer {
let dbQueue = try! DatabaseQueue(path: databasePath)
try! dbQueue.inDatabase { db in
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, insertedRowCount)
XCTAssertEqual(try Int.fetchOne(db, "SELECT MIN(i0) FROM items")!, 0)
XCTAssertEqual(try Int.fetchOne(db, "SELECT MAX(i9) FROM items")!, insertedRowCount - 1)
}
try! FileManager.default.removeItem(atPath: databasePath)
}
measure {
_ = try? FileManager.default.removeItem(atPath: databasePath)
let dbQueue = FMDatabaseQueue(path: databasePath)
dbQueue.inDatabase { db in
db.executeStatements("CREATE TABLE items (i0 INT, i1 INT, i2 INT, i3 INT, i4 INT, i5 INT, i6 INT, i7 INT, i8 INT, i9 INT)")
}
dbQueue.inTransaction { (db, rollback) -> Void in
db.shouldCacheStatements = true
for i in 0..<insertedRowCount {
db.executeUpdate("INSERT INTO items (i0, i1, i2, i3, i4, i5, i6, i7, i8, i9) VALUES (:i0, :i1, :i2, :i3, :i4, :i5, :i6, :i7, :i8, :i9)", withParameterDictionary: ["i0": i, "i1": i, "i2": i, "i3": i, "i4": i, "i5": i, "i6": i, "i7": i, "i8": i, "i9": i])
}
}
}
}
func testSQLiteSwift() {
let databaseFileName = "GRDBPerformanceTests-\(ProcessInfo.processInfo.globallyUniqueString).sqlite"
let databasePath = (NSTemporaryDirectory() as NSString).appendingPathComponent(databaseFileName)
defer {
let dbQueue = try! DatabaseQueue(path: databasePath)
try! dbQueue.inDatabase { db in
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, insertedRowCount)
XCTAssertEqual(try Int.fetchOne(db, "SELECT MIN(i0) FROM items")!, 0)
XCTAssertEqual(try Int.fetchOne(db, "SELECT MAX(i9) FROM items")!, insertedRowCount - 1)
}
try! FileManager.default.removeItem(atPath: databasePath)
}
measure {
_ = try? FileManager.default.removeItem(atPath: databasePath)
let db = try! Connection(databasePath)
try! db.run(itemsTable.create { t in
t.column(i0Column)
t.column(i1Column)
t.column(i2Column)
t.column(i3Column)
t.column(i4Column)
t.column(i5Column)
t.column(i6Column)
t.column(i7Column)
t.column(i8Column)
t.column(i9Column)
})
try! db.transaction {
for i in 0..<insertedRowCount {
_ = try db.run(itemsTable.insert(
i0Column <- i,
i1Column <- i,
i2Column <- i,
i3Column <- i,
i4Column <- i,
i5Column <- i,
i6Column <- i,
i7Column <- i,
i8Column <- i,
i9Column <- i))
}
}
}
}
#endif
}
| 44.130081 | 273 | 0.536478 |
f568319a732697af4fe828ded4607080378fdf71 | 2,113 | //
// SDWebImageManager+PromiseKit.swift
// Wikipedia
//
// Created by Brian Gerstle on 6/22/15.
// Copyright (c) 2015 Wikimedia Foundation. All rights reserved.
//
import Foundation
import PromiseKit
import SDWebImage
extension SDImageCacheType: ImageOriginConvertible {
public func asImageOrigin() -> ImageOrigin {
switch self {
case SDImageCacheType.Disk:
return ImageOrigin.Disk
case SDImageCacheType.Memory:
return ImageOrigin.Memory
case SDImageCacheType.None:
return ImageOrigin.Network
}
}
}
// FIXME: Can't extend the SDWebImageOperation protocol or cast the return value, so we wrap it.
class SDWebImageOperationWrapper: NSObject, Cancellable {
weak var operation: SDWebImageOperation?
required init(operation: SDWebImageOperation) {
super.init()
self.operation = operation
// keep wrapper around as long as operation is around
objc_setAssociatedObject(operation,
"SDWebImageOperationWrapper",
self,
objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
func cancel() -> Void {
operation?.cancel()
}
}
extension SDWebImageManager {
func promisedImageWithURL(URL: NSURL, options: SDWebImageOptions) -> (Cancellable, Promise<WMFImageDownload>) {
let (promise, fulfill, reject) = Promise<WMFImageDownload>.pendingPromise()
let promiseCompatibleOptions: SDWebImageOptions = [options, SDWebImageOptions.ReportCancellationAsError]
let webImageOperation = self.downloadImageWithURL(URL, options: promiseCompatibleOptions, progress: nil)
{ img, err, cacheType, finished, imageURL in
if finished && err == nil {
fulfill(WMFImageDownload(url: URL, image: img, origin: asImageOrigin(cacheType).rawValue))
} else {
reject(err)
}
}
return (SDWebImageOperationWrapper(operation: webImageOperation), promise)
}
}
| 34.080645 | 115 | 0.652153 |
e084bc6f85b9a9627b0e168a0622a10331c27b81 | 6,898 | //
// AuthManager.swift
// Spotify
//
// Created by Arthur Ruan on 26/02/22.
//
import Foundation
final class AuthManager {
static let shared = AuthManager()
private var refreshingToken = false
struct Constants {
static let clientID = "1c0ebccdb719492a894b1fcd085491b7"
static let clientSecret = "ebe25283063640e19cfe492341c64f17"
static let tokenAPIURL = "https://accounts.spotify.com/api/token"
static let redirectURI = "https://www.google.com/"
static let scopes = "user-read-private%20playlist-modify-public%20playlist-read-private%20playlist-modify-private%20user-follow-read%20user-library-modify%20user-library-read%20user-read-email"
}
private init() {}
public var signInURL: URL? {
let baseURL = "https://accounts.spotify.com/authorize"
let responseType = "code"
let string =
"\(baseURL)?response_type=\(responseType)&client_id=\(Constants.clientID)&scope=\(Constants.scopes)&redirect_uri=\(Constants.redirectURI)&show_dialog=TRUE"
return URL(string: string)
}
public var isSignedIn: Bool {
return accessToken != nil
}
private var accessToken: String? {
return UserDefaults.standard.string(forKey: "access_token")
}
private var refreshToken: String? {
return UserDefaults.standard.string(forKey: "refresh_token")
}
private var tokenExpirationDate: Date? {
return UserDefaults.standard.object(forKey: "expirationDate") as? Date
}
private var shouldRefreshToken: Bool {
guard let expirationDate = tokenExpirationDate else {
return false
}
let currentDate = Date()
let fiveMinutes: TimeInterval = 300
return currentDate.addingTimeInterval(fiveMinutes) >= expirationDate
}
public func exchangeCodeForToken(
code: String,
completion: @escaping ((Bool) -> Void)
) {
guard let url = URL(string: Constants.tokenAPIURL) else {
return
}
var components = URLComponents()
components.queryItems = [
URLQueryItem(name: "grant_type", value: "authorization_code"),
URLQueryItem(name: "code", value: code),
URLQueryItem(name: "redirect_uri", value: Constants.redirectURI),
]
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpBody = components.query?.data(using: .utf8)
let basicToken = "\(Constants.clientID):\(Constants.clientSecret)"
let data = basicToken.data(using: .utf8)
guard let base64String = data?.base64EncodedString() else {
print("Failure to get base64")
completion(false)
return
}
request.setValue("Basic \(base64String)", forHTTPHeaderField: "Authorization")
let task = URLSession.shared.dataTask(with: request) { [weak self] data, _, error in
guard let data = data, error == nil else {
completion(false)
return
}
do {
let result = try JSONDecoder().decode(AuthResponse.self, from: data)
self?.cacheToken(result: result)
completion(true)
} catch {
print(error.localizedDescription)
completion(false)
}
}
task.resume()
}
private var onRefreshBlocks = [((String) -> Void)]()
// Supplies valid token to be used with API Calls
public func withValidToken(completion: @escaping (String) -> Void) {
guard !refreshingToken else {
// Append the completion
onRefreshBlocks.append(completion)
return
}
if shouldRefreshToken {
// Refresh
refreshIfNeeded { [weak self] success in
if let token = self?.accessToken, success {
completion(token)
}
}
} else if let token = accessToken {
completion(token)
}
}
public func refreshIfNeeded(completion: ((Bool) -> Void)?) {
guard shouldRefreshToken else {
completion?(true)
return
}
guard let refreshToken = self.refreshToken else {
return
}
// Refresh the token
guard let url = URL(string: Constants.tokenAPIURL) else {
return
}
refreshingToken = true
var components = URLComponents()
components.queryItems = [
URLQueryItem(name: "grant_type", value: "refresh_token"),
URLQueryItem(name: "refresh_token", value: refreshToken),
]
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpBody = components.query?.data(using: .utf8)
let basicToken = "\(Constants.clientID):\(Constants.clientSecret)"
let data = basicToken.data(using: .utf8)
guard let base64String = data?.base64EncodedString() else {
print("Failure to get base64")
completion?(false)
return
}
request.setValue("Basic \(base64String)", forHTTPHeaderField: "Authorization")
let task = URLSession.shared.dataTask(with: request) { [weak self] data, _, error in
self?.refreshingToken = false
guard let data = data, error == nil else {
completion?(false)
return
}
do {
let result = try JSONDecoder().decode(AuthResponse.self, from: data)
self?.onRefreshBlocks.forEach{ $0(result.access_token) }
self?.onRefreshBlocks.removeAll()
self?.cacheToken(result: result)
completion?(true)
} catch {
print(error.localizedDescription)
completion?(false)
}
}
task.resume()
}
private func cacheToken(result: AuthResponse) {
UserDefaults.standard.setValue(
result.access_token,
forKey: "access_token"
)
if let refresh_token = result.refresh_token {
UserDefaults.standard.setValue(
refresh_token,
forKey: "refresh_token"
)
}
UserDefaults.standard.setValue(
Date().addingTimeInterval(TimeInterval(result.expires_in)),
forKey: "expirationDate"
)
}
}
| 33.813725 | 201 | 0.575094 |
f80bf498abf66858e7d24fd0959595fa8a19b918 | 19,380 | //
// PumpOpsSynchronousBuildFromFramesTests.swift
// RileyLink
//
// Created by Jaim Zuber on 3/8/17.
// Copyright © 2017 Pete Schwamb. All rights reserved.
//
import XCTest
@testable import RileyLinkKit
import MinimedKit
import RileyLinkBLEKit
class PumpOpsSynchronousBuildFromFramesTests: XCTestCase {
var sut: PumpOpsSynchronous!
var pumpState: PumpState!
var pumpID: String!
var pumpRegion: PumpRegion!
var rileyLinkCmdSession: RileyLinkCmdSession!
var pumpModel: PumpModel!
var pumpOpsCommunicationStub: PumpOpsCommunicationStub!
var timeZone: TimeZone!
override func setUp() {
super.setUp()
pumpID = "350535"
pumpRegion = .worldWide
pumpModel = PumpModel.Model523
rileyLinkCmdSession = RileyLinkCmdSession()
pumpOpsCommunicationStub = PumpOpsCommunicationStub(session: rileyLinkCmdSession)
timeZone = TimeZone(secondsFromGMT: 0)
loadSUT()
}
func loadSUT() {
pumpState = PumpState(pumpID: pumpID, pumpRegion: pumpRegion)
pumpState.pumpModel = pumpModel
pumpState.awakeUntil = Date(timeIntervalSinceNow: 100) // pump is awake
sut = PumpOpsSynchronous(pumpState: pumpState, session: rileyLinkCmdSession)
sut.communication = pumpOpsCommunicationStub
}
func testErrorIsntThrown() {
pumpOpsCommunicationStub.responses = buildResponsesDictionary()
assertNoThrow(try _ = sut.getHistoryEvents(since: Date()))
}
func testUnexpectedResponseThrowsError() {
var responseDictionary = buildResponsesDictionary()
var pumpAckArray = responseDictionary[.getHistoryPage]!
pumpAckArray.insert(sut.makePumpMessage(to: .buttonPress), at: 0)
responseDictionary[.getHistoryPage]! = pumpAckArray
pumpOpsCommunicationStub.responses = responseDictionary
// Didn't receive a .pumpAck short reponse so throw an error
assertThrows(try _ = sut.getHistoryEvents(since: Date()))
}
func testUnexpectedPumpAckResponseThrowsError() {
var responseDictionary = buildResponsesDictionary()
var pumpAckArray = responseDictionary[.getHistoryPage]!
pumpAckArray.insert(sut.makePumpMessage(to: .buttonPress), at: 1)
responseDictionary[.getHistoryPage]! = pumpAckArray
pumpOpsCommunicationStub.responses = responseDictionary
// Didn't receive a .getHistoryPage as 2nd response so throw an error
assertThrows(try _ = sut.getHistoryEvents(since: Date()))
}
func test332EventsReturnedUntilOutOrder() {
pumpOpsCommunicationStub.responses = buildResponsesDictionary()
let date = Date(timeIntervalSince1970: 0)
do {
let (historyEvents, _) = try sut.getHistoryEvents(since: date)
XCTAssertEqual(historyEvents.count, 332)
} catch {
XCTFail()
}
}
func testEventsReturnedAfterTime() {
pumpOpsCommunicationStub.responses = buildResponsesDictionary()
timeZone = TimeZone.current
loadSUT()
let date = DateComponents(calendar: Calendar.current, timeZone: pumpState.timeZone, year: 2017, month: 2, day: 11, hour: 0, minute: 0, second: 0).date!
do {
let (historyEvents, _) = try sut.getHistoryEvents(since: date)
// Ends because we reached event before or at date
XCTAssertEqual(historyEvents.count, 290)
} catch {
XCTFail()
}
}
func testGMTEventsAreTheSame() {
pumpOpsCommunicationStub.responses = buildResponsesDictionary()
timeZone = TimeZone(secondsFromGMT:0)
loadSUT()
let date = DateComponents(calendar: Calendar.current, timeZone: pumpState.timeZone, year: 2017, month: 2, day: 11, hour: 0, minute: 0, second: 0).date!
do {
let (historyEvents, _) = try sut.getHistoryEvents(since: date)
// Ends because we reached event before or at date
XCTAssertEqual(historyEvents.count, 290)
} catch {
XCTFail()
}
}
func testEventsReturnedAreAscendingOrder() {
pumpOpsCommunicationStub.responses = buildResponsesDictionary()
//02/11/2017 @ 12:00am (UTC)
let date = DateComponents(calendar: Calendar.current, timeZone: pumpState.timeZone, year: 2017, month: 2, day: 11, hour: 0, minute: 0, second: 0).date!
do {
let (historyEvents, _) = try sut.getHistoryEvents(since: date)
var dateCursor = historyEvents[0].date
historyEvents.forEach { event in
// Events can be slightly out of order
if ( dateCursor.timeIntervalSince(event.date) > TimeInterval(minutes: 0.2)) {
// But shouldn't be this much
XCTFail("Found out of order event")
}
dateCursor = event.date
}
} catch {
XCTFail()
}
}
func buildResponsesDictionary() -> [MessageType : [PumpMessage]] {
var dictionary = [MessageType : [PumpMessage]]()
// Build array of Messages for each frame
let frameZeroMessages = buildPumpMessagesFromFrameArray(fetchPageZeroFrames)
let frameOneMessages = buildPumpMessagesFromFrameArray(fetchPageOneFrames)
let frameTwoMessages = buildPumpMessagesFromFrameArray(fetchPageTwoFrames)
let frameThreeMessages = buildPumpMessagesFromFrameArray(fetchPageThreeFrames)
let frameFourMessages = buildPumpMessagesFromFrameArray(fetchPageFourFrames)
let pumpAckMessage = sut.makePumpMessage(to: .pumpAck)
let errorResponseMessage = sut.makePumpMessage(to: .errorResponse)
var getHistoryPageArray = [pumpAckMessage, frameZeroMessages[0]]
getHistoryPageArray.append(contentsOf: [pumpAckMessage, frameOneMessages[0]])
getHistoryPageArray.append(contentsOf: [pumpAckMessage, frameTwoMessages[0]])
getHistoryPageArray.append(contentsOf: [pumpAckMessage, frameThreeMessages[0]])
getHistoryPageArray.append(contentsOf: [pumpAckMessage, frameFourMessages[0]])
getHistoryPageArray.append(errorResponseMessage)
// pump will be called twice, normal operation will receive a pumpAck and getHistoryPageMessage
dictionary[.getHistoryPage] = getHistoryPageArray
var pumpAckArray = Array(frameZeroMessages.suffix(from: 1))
pumpAckArray.append(contentsOf: Array(frameOneMessages.suffix(from: 1)))
pumpAckArray.append(contentsOf: Array(frameTwoMessages.suffix(from: 1)))
pumpAckArray.append(contentsOf: Array(frameThreeMessages.suffix(from: 1)))
pumpAckArray.append(contentsOf: Array(frameFourMessages.suffix(from: 1)))
// Pump sends more data after we send a .pumpAck
dictionary[.pumpAck] = pumpAckArray
return dictionary
}
func buildPumpMessagesFromFrameArray(_ frameArray: [String]) -> [PumpMessage] {
return frameArray.map { self.buildPumpMessageFromFrame($0) }
}
func buildPumpMessageFromFrame(_ frame: String) -> PumpMessage {
let frameData: Data = dataFromHexString(frame)
let getHistoryPageMessageBody = GetHistoryPageCarelinkMessageBody(rxData: frameData)!
let getHistoryPageMessage = PumpMessage(packetType: PacketType.carelink, address: self.pumpID, messageType: .getHistoryPage, messageBody: getHistoryPageMessageBody)
return getHistoryPageMessage
}
let fetchPageZeroFrames = [
"01030000001822892c15117b050b8a0c1511180a000300030003018a0c1511330028990d551100160128990d551133001fa30d55110016001fa30d55117b051fa3",
"020d1511180a0033001fb20d55110016011fb20d55113300208a0e5511001601208a0e55117b0520a80e1511180a007b060080101511200e007b07008013151126",
"0310007b08009e1415112915007b000080001611001000070000014635110000006e351105005e00000100000146013c61000a030005000a000000000000010000",
"04000000000000000000005e5e00000000000000007b010080011611020c007b020080041611080d007b0300800616110c100033001e800656110016011e800656",
"05117b031e9e0616110c100033001e9e0856110016011e9e08561133001da80856110016001da80856117b031da80816110c100033001eb20856110016011eb208",
"06561133001d8a0956110016011d8a09561133001d990956110016001d990956117b031d990916110c100033001da30956110016011da309561133001ead095611",
"070016001ead0956117b031ead0916110c10007b0400800a1611140b007b0500800c1611180a007b060080101611200e007b0700801316112610007b08009e1416",
"08112915007b000080001711001000070000014136110000006e361105000000000000000141014164000000000000000000000000000000000000000000000000",
"090000000000000000000000007b010080011711020c007b020080041711080d007b0300800617110c10007b0400800a1711140b007b0500800c1711180a007b06",
"0a0080101711200e007b0700801317112610007b08009e1417112915007b000080001811001000070000015737110000006e371105000000000000000157015764",
"0b0000000000000000000000000000000000000000000000000000000000000000000000007b010080011811020c007b020080041811080d007b0300800618110c",
"0c100033001d9e0858110016011d9e08581133001dad0858110016001dad0858117b031dad0818110c10007b0400800a1811140b00000000000000000000000000",
"0d00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
"0e00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
"0f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
"900000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000cbf5"
]
let fetchPageOneFrames = [
"016e3011050000000000000005c601821a04444a000000000000000004440000000b000000000000000000000000000000000000007b010080011111020c007b02",
"020080041111080d007b0300800611110c1000010050005000000025a12951117b0400800a1111140b007b0500800c1111180a000100780078000a0032bb2b5111",
"037b060080101111200e007b0700801311112610007b08009e1411112915007b000080001211001000070000021f31110000006e31110500000000000000021f01",
"04573f00c825000000000000000000c800000002000000000000000000000000000000000000007b010080011211020c007b020080041211080d007b0300800612",
"05110c10007b0400800a1211140b007b0500800c1211180a007b060080101211200e007b0700801312112610007b08009e1412112915007b000080001311001000",
"06070000015732110000006e3211050000000000000001570157640000000000000000000000000000000000000000000000000000000000000000000000007b01",
"070080011311020c007b020080041311080d007b0300800613110c10007b0400800a1311140b007b0500800c1311180a007b060080101311200e007b0700801313",
"08112610007b08009e1413112915007b000080001411001000070000015733110000006e3311050000000000000001570157640000000000000000000000000000",
"09000000000000000000000000000000000000000000007b010080011411020c007b020080041411080d00346417b70514117b0300800614110c10007b0400800a",
"0a1411140b007b0500800c1411180a007b060080101411200e0033002a931254110016012a931254117b062ab1121411200e007b0700801314112610007b08009e",
"0b1414112915003432198b1514117b000080001511001000070000015034110000006e341105000000000000000150015064000000000000000000000000000000",
"0c0000000000000000000000000000000000000000007b010080011511020c007b020080041511080d007b0300800615110c1000330021a206551100160121a206",
"0d5511330026a706551100160026a70655117b0326a70615110c1000330021bb06551100160121bb0655113300248407551100160024840755117b032584071511",
"0e0c1000330021a708551100160121a7085511330021b108551100160021b10855117b0321b10815110c1000330021bb08551100160121bb085511330020930955",
"0f110016012093095511330022a709551100160122a7095511330021ac09551100160021ac0955117b0322ac0915110c10007b0400800a1511140b000a5e06a32b",
"9015115b5e0ea30b7511055000b4555a00000a000000000a8c01000a000a0000000ea32b75117b0500800c1511180a00210030880c151100000000000000004e9d"
]
let fetchPageTwoFrames = [
"016e2d110500000000000000016c016c640000000000000000000000000000000000000000000000000000000000000000000000007b010080010e11020c007b02",
"020080040e11080d007b030080060e110c10007b0400800a0e11140b0033531c840a4e110016011c840a4e1133001d890a4e110016001d890a4e117b041e890a0e",
"0311140b00334a1d930a4e110016011d930a4e1133001c980a4e110016001c980a4e117b041d980a0e11140b007b0500800c0e11180a007b060080100e11200e00",
"047b070080130e112610007b08009e140e112915007b000080000f1100100007000001632e110000006e2e11050000000000000001630163640000000000000000",
"05000000000000000000000000000000000000000000000000000000007b010080010f11020c007b020080040f11080d007b030080060f110c10007b0400800a0f",
"0611140b007b0500800c0f11180a00330017ae0c4f1100160117ae0c4f117b0518900d0f11180a007b060080100f11200e007b070080130f112610007b08009e14",
"070f112915007b00008000101100100007000001522f110000006e2f11050000000000000001520152640000000000000000000000000000000000000000000000",
"08000000000000000000000000007b010080011011020c007b020080041011080d007b0300800610110c100033473bb10950110016013bb109501133003bb60950",
"09110016003bb60950117b033bb60910110c10007b0400800a1011140b000100500050000000228a2a501101005000500050000c8d2a5011330000940a50110016",
"0a0100940a501133003b990a50110016013b990a501101005800580097000ea12a50117b043bb70a1011140b000100500050007d000ea92b5011330020ae0b5011",
"0b00160120ae0b50113338218d0c5011001601218d0c5011335934a60c501100160134a60c50117b0534880d1011180a00010050005000250007932d50110100d0",
"0c00d00071000e982d501101010001000130000ca22d5011330007a90d501100160107a90d501101005000500222000da92d5011330003b90d501100160103b90d",
"0d501133002c800e50110016012c800e501133003a8e0e50110016013a8e0e501133003a930e50110016003a930e50117b053a930e1011180a00330039990e5011",
"0e00160139990e50113300169e0e5011001600169e0e50117b05169e0e1011180a00330000b20e501100160100b20e5011330001b70e501100160001b70e50117b",
"0f0501b70e1011180a0001002800280085000aa12f50110100500050009d001aa62f5011010014001400ce0038b12f50117b060080101011200e007b0700801310",
"90112610007b08009e1410112915007b00008000111100100007000005c63011000000000000000000000000000000000000000000000000000000000000008e53"
]
let fetchPageThreeFrames = [
"017b0700801309112610007b08009e1409112915007b000080000a11001000070000029429110000006e291105000000000000000294015634013e300000000000",
"02000000013e00000003000000000000000000000000000000000000007b010080010a11020c007b020080040a11080d007b030080060a110c10007b0400800a0a",
"0311140b000100c800c80000003abb294a11830106980a0a11010012001200ba00309a2a0a113310229c0a0a11001603229c0a0a117b0423ba0b0a11140b007b05",
"0400800c0a11180a007b060080100a11200e007b070080130a112610007b08009e140a112915007b000080000b1100100007000002392a110000006e2a11050000",
"0500000000000239015f3e00da26000000000000000000da00000002000000000000000000000000000000000000007b010080010b11020c007b020080040b1108",
"060d007b030080060b110c10007b0400800a0b11140b007b0500800c0b11180a00333b348e0d4b11001601348e0d4b1133001c930d4b110016001c930d4b117b05",
"071c930d0b11180a007b060080100b11200e007b070080130b112610007b08009e140b112915007b000080000c11001000070000015a2b110000006e2b11050000",
"080000000000015a015a640000000000000000000000000000000000000000000000000000000000000000000000007b010080010c11020c007b020080040c1108",
"090d007b030080060c110c10007b0400800a0c11140b00335b1dac0a4c110016011dac0a4c1133001db10a4c110016001db10a4c117b041db10a0c11140b003349",
"0a1db60a4c110016011db60a4c1133001ebb0a4c110016001ebb0a4c117b041ebb0a0c11140b007b0500800c0c11180a007b060080100c11200e007b070080130c",
"0b112610007b08009e140c112915007b000080000d1100100007000001632c110000006e2c11050000000000000001630163640000000000000000000000000000",
"0c000000000000000000000000000000000000000000007b010080010d11020c007b020080040d11080d007b030080060d110c100033551d9d084d110016011d9d",
"0d084d1133001ca2084d110016001ca2084d117b031da2080d110c100033531cb6084d110016011cb6084d1133001dbb084d110016001dbb084d117b031dbb080d",
"0e110c100033421d89094d110016011d89094d1133001c8e094d110016001c8e094d117b031c8e090d110c1000334b1d93094d110016011d93094d1133001e9809",
"0f4d110016001e98094d117b031e98090d110c10007b0400800a0d11140b007b0500800c0d11180a007b060080100d11200e007b070080130d112610007b08009e",
"90140d112915007b000080000e11001000070000016c2d110000000000000000000000000000000000000000000000000000000000000000000000000000000a4e"
]
let fetchPageFourFrames = [
"010615036800406001070636036f0040600107062f1dfc004020c107062f0e77004020c107062f0e88004020c107062f0e99004020c107062f0eaa004020c10706",
"022f0ebb004020c107062f0ee1004020c107062f0ef4004020c107062f0f05004020c10706110f12004020c10706150411004040a1070c151f4300010764000f40",
"0300010764001e400001076400024100010717002241000107180000a20c0211070000000001870000006e01870500000000000000000000000000000000000000",
"04000000000000000000000000000000000000000000000000000000000021001a9e0d02112100219f0d0211210031a10d02111a0024b30d02111a0138b30d0211",
"05210028ba0d02112100018a0f0211064202742a8a4f42110c420a8b0f021121000e8b0f02110300000000338b2f02117b05088c0f0211180a007b051b8c0f0211",
"06180a000300030003118c0f021181010e8e0f021100a27b87767d020e8e0f021100a2ce8aa000a27b877600000000000000000000000000000000000000007b06",
"070080100211200e001a002a80100211060303682a807002110c03384000010764003b400001076400214100010717000942000107180000a50703110700000008",
"08221100220c6e2211050000000000000000080008640000000000000000000000000000000000200000000000000000000000000080000000607b0301a5070311",
"090c10000a63258d2903115b632a8d0963110050006e555a00000000000000008c7b0400800a0311140b007b0500800c0311180a007b060080100311200e001a00",
"0a38b21003110603036838b27003110c03174000010764011c4000010717001141000107180000ad0b0811070000007023110125076e2311150063000001000000",
"0b700070640000000000000000000000000000000000500000000000000000636300000080000000387b0400ad0b0811140b007d0208b70b081100a2ce8aa000a2",
"0c7b877600000000000000000000000000000000000000007b0500800c0811180a007b060080100811200e007d0224b710081100a2ce8aa000a27b877600000000",
"0d000000000000000000000000000000007b0700801308112610007b08009e1408112915007b00008000091100100007000000b52811002d0b6e28110500000000",
"0e00000000b500b5640000000000000000000000000000000000d00000000000000000000000000080000000587b010080010911020c007b020080040911080d00",
"0f7b0300800609110c10007b0400800a0911140b007b0500800c0911180a0001011801180000000a812f4911010006000601160030882f091133001d890f491100",
"9016011d890f491133002d8e0f49110016002d8e0f49117b052d8e0f0911180a007b060080100911200e000100200020002a0018963109110000000000000095fb"
]
}
| 65.694915 | 172 | 0.80774 |
f51e3de61dc22f8c99e991688296ac3eef3ad8bd | 2,110 | //
// UIImage+Extension.swift
// common
//
// Created by togreat on 2021/9/6.
//
import UIKit
import Photos
// MARK: - 基本的拓展
extension UIImage {
/// 设置临时图片
public func setTemplateImg() -> UIImage {
return self.withRenderingMode(.alwaysTemplate)
}
/// 原图像
func setOriginalImg() -> UIImage {
return self.withRenderingMode(.alwaysOriginal)
}
/// 给我一个颜色,还你一个图片
class func imgWithColor(_ color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) -> UIImage {
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
/// 开始绘制
UIGraphicsBeginImageContext(rect.size)
/// 获取当前上下文
let context = UIGraphicsGetCurrentContext()
/// 上下文获取该颜色
context?.setFillColor(color.cgColor)
/// 用这个颜色填充这个上下文
context?.fill(rect)
//从这段上下文中获取Image
let img = UIGraphicsGetImageFromCurrentImageContext()
/// 结束绘制
UIGraphicsEndImageContext()
return img ?? UIImage()
}
class func fullResolutionImageData(asset: PHAsset) -> UIImage? {
let options = PHImageRequestOptions()
options.isSynchronous = true
options.resizeMode = .none
options.isNetworkAccessAllowed = false
options.version = .current
var image: UIImage? = nil
_ = PHCachingImageManager().requestImageData(for: asset, options: options) { (imageData, dataUTI, orientation, info) in
if let data = imageData {
image = UIImage(data: data)
}
}
return image
}
//view转图片
public class func imageWithView(_ view: UIView) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 0)
var image: UIImage?
if let currentContent = UIGraphicsGetCurrentContext() {
view.layer.render(in: currentContent)
image = UIGraphicsGetImageFromCurrentImageContext()
}
UIGraphicsEndImageContext()
return image
}
}
| 27.402597 | 127 | 0.595735 |
5d2890c2e1ef69891a49848c5fa360827655aed6 | 1,661 | //
// YEmptyDataSet.swift
// yulebaby
//
// Created by susuyan on 2017/12/22.
// Copyright © 2017年 susuyan. All rights reserved.
//
import Foundation
import EmptyDataSet_Swift
extension UIScrollView {
private struct AssociatedKeys {
static var uemptyKey: Void?
}
var yempty: YEmptyView? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.uemptyKey) as? YEmptyView
}
set {
self.emptyDataSetDelegate = newValue
self.emptyDataSetSource = newValue
objc_setAssociatedObject(self, &AssociatedKeys.uemptyKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
class YEmptyView: EmptyDataSetSource, EmptyDataSetDelegate {
var image: UIImage?
var allowShow: Bool = false
var verticalOffset: CGFloat = 0
private var tapClosure: (() -> Void)?
init(image: UIImage? = UIImage(named: "nodata"), verticalOffset: CGFloat = 0, tapClosure: (() -> Void)?) {
self.image = image
self.verticalOffset = verticalOffset
self.tapClosure = tapClosure
}
func verticalOffset(forEmptyDataSet scrollView: UIScrollView) -> CGFloat {
return verticalOffset
}
internal func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
return image
}
internal func emptyDataSetShouldDisplay(_ scrollView: UIScrollView) -> Bool {
return allowShow
}
internal func emptyDataSet(_ scrollView: UIScrollView, didTapView view: UIView) {
guard let tapClosure = tapClosure else { return }
tapClosure()
}
}
| 25.953125 | 115 | 0.646598 |
20b92e58e5711c848a53e358b483c811a1d7e287 | 1,224 | //
// Copyright (c) 2015 Hilton Campbell
//
// 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 Signals
public protocol Theme {
static func setTheme(themeName: String)
}
| 42.206897 | 80 | 0.763889 |
03f659208d767f94e126533a314b14e5a31f32e9 | 675 | enum ConfirmPaymentErrorType: String {
case Failed, Canceled, Unknown
}
enum ApplePayErrorType: String {
case Failed, Canceled, Unknown
}
enum NextPaymentActionErrorType: String {
case Failed, Canceled, Unknown
}
enum ConfirmSetupIntentErrorType: String {
case Failed, Canceled, Unknown
}
enum RetrievePaymentIntentErrorType: String {
case Unknown
}
enum PaymentSheetErrorType: String {
case Failed, Canceled
}
class Errors {
class func createError (code: String, message: String) -> NSDictionary {
let error: NSDictionary = [
"code": code,
"message": message,
]
return error
}
}
| 19.285714 | 76 | 0.66963 |
c1ac026c064078d19e72c9e542f41891e274ad87 | 34,270 | // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/swift-aws/aws-sdk-swift/blob/master/CodeGenerator/Sources/CodeGenerator/main.swift. DO NOT EDIT.
import Foundation
import AWSSDKSwiftCore
extension KinesisVideo {
public enum APIName: String, CustomStringConvertible, Codable {
case putMedia = "PUT_MEDIA"
case getMedia = "GET_MEDIA"
case listFragments = "LIST_FRAGMENTS"
case getMediaForFragmentList = "GET_MEDIA_FOR_FRAGMENT_LIST"
case getHlsStreamingSessionUrl = "GET_HLS_STREAMING_SESSION_URL"
case getDashStreamingSessionUrl = "GET_DASH_STREAMING_SESSION_URL"
public var description: String { return self.rawValue }
}
public enum ComparisonOperator: String, CustomStringConvertible, Codable {
case beginsWith = "BEGINS_WITH"
public var description: String { return self.rawValue }
}
public struct CreateStreamInput: AWSShape {
public static var _members: [AWSShapeMember] = [
AWSShapeMember(label: "DataRetentionInHours", required: false, type: .integer),
AWSShapeMember(label: "DeviceName", required: false, type: .string),
AWSShapeMember(label: "KmsKeyId", required: false, type: .string),
AWSShapeMember(label: "MediaType", required: false, type: .string),
AWSShapeMember(label: "StreamName", required: true, type: .string),
AWSShapeMember(label: "Tags", required: false, type: .map)
]
/// The number of hours that you want to retain the data in the stream. Kinesis Video Streams retains the data in a data store that is associated with the stream. The default value is 0, indicating that the stream does not persist data. When the DataRetentionInHours value is 0, consumers can still consume the fragments that remain in the service host buffer, which has a retention time limit of 5 minutes and a retention memory limit of 200 MB. Fragments are removed from the buffer when either limit is reached.
public let dataRetentionInHours: Int?
/// The name of the device that is writing to the stream. In the current implementation, Kinesis Video Streams does not use this name.
public let deviceName: String?
/// The ID of the AWS Key Management Service (AWS KMS) key that you want Kinesis Video Streams to use to encrypt stream data. If no key ID is specified, the default, Kinesis Video-managed key (aws/kinesisvideo) is used. For more information, see DescribeKey.
public let kmsKeyId: String?
/// The media type of the stream. Consumers of the stream can use this information when processing the stream. For more information about media types, see Media Types. If you choose to specify the MediaType, see Naming Requirements for guidelines. This parameter is optional; the default value is null (or empty in JSON).
public let mediaType: String?
/// A name for the stream that you are creating. The stream name is an identifier for the stream, and must be unique for each account and region.
public let streamName: String
/// A list of tags to associate with the specified stream. Each tag is a key-value pair (the value is optional).
public let tags: [String: String]?
public init(dataRetentionInHours: Int? = nil, deviceName: String? = nil, kmsKeyId: String? = nil, mediaType: String? = nil, streamName: String, tags: [String: String]? = nil) {
self.dataRetentionInHours = dataRetentionInHours
self.deviceName = deviceName
self.kmsKeyId = kmsKeyId
self.mediaType = mediaType
self.streamName = streamName
self.tags = tags
}
public func validate(name: String) throws {
try validate(dataRetentionInHours, name:"dataRetentionInHours", parent: name, min: 0)
try validate(deviceName, name:"deviceName", parent: name, max: 128)
try validate(deviceName, name:"deviceName", parent: name, min: 1)
try validate(deviceName, name:"deviceName", parent: name, pattern: "[a-zA-Z0-9_.-]+")
try validate(kmsKeyId, name:"kmsKeyId", parent: name, max: 2048)
try validate(kmsKeyId, name:"kmsKeyId", parent: name, min: 1)
try validate(mediaType, name:"mediaType", parent: name, max: 128)
try validate(mediaType, name:"mediaType", parent: name, min: 1)
try validate(mediaType, name:"mediaType", parent: name, pattern: "[\\w\\-\\.\\+]+/[\\w\\-\\.\\+]+(,[\\w\\-\\.\\+]+/[\\w\\-\\.\\+]+)*")
try validate(streamName, name:"streamName", parent: name, max: 256)
try validate(streamName, name:"streamName", parent: name, min: 1)
try validate(streamName, name:"streamName", parent: name, pattern: "[a-zA-Z0-9_.-]+")
try tags?.forEach {
try validate($0.key, name:"tags.key", parent: name, max: 128)
try validate($0.key, name:"tags.key", parent: name, min: 1)
try validate($0.value, name:"tags[\"\($0.key)\"]", parent: name, max: 256)
try validate($0.value, name:"tags[\"\($0.key)\"]", parent: name, min: 0)
}
}
private enum CodingKeys: String, CodingKey {
case dataRetentionInHours = "DataRetentionInHours"
case deviceName = "DeviceName"
case kmsKeyId = "KmsKeyId"
case mediaType = "MediaType"
case streamName = "StreamName"
case tags = "Tags"
}
}
public struct CreateStreamOutput: AWSShape {
public static var _members: [AWSShapeMember] = [
AWSShapeMember(label: "StreamARN", required: false, type: .string)
]
/// The Amazon Resource Name (ARN) of the stream.
public let streamARN: String?
public init(streamARN: String? = nil) {
self.streamARN = streamARN
}
private enum CodingKeys: String, CodingKey {
case streamARN = "StreamARN"
}
}
public struct DeleteStreamInput: AWSShape {
public static var _members: [AWSShapeMember] = [
AWSShapeMember(label: "CurrentVersion", required: false, type: .string),
AWSShapeMember(label: "StreamARN", required: true, type: .string)
]
/// Optional: The version of the stream that you want to delete. Specify the version as a safeguard to ensure that your are deleting the correct stream. To get the stream version, use the DescribeStream API. If not specified, only the CreationTime is checked before deleting the stream.
public let currentVersion: String?
/// The Amazon Resource Name (ARN) of the stream that you want to delete.
public let streamARN: String
public init(currentVersion: String? = nil, streamARN: String) {
self.currentVersion = currentVersion
self.streamARN = streamARN
}
public func validate(name: String) throws {
try validate(currentVersion, name:"currentVersion", parent: name, max: 64)
try validate(currentVersion, name:"currentVersion", parent: name, min: 1)
try validate(currentVersion, name:"currentVersion", parent: name, pattern: "[a-zA-Z0-9]+")
try validate(streamARN, name:"streamARN", parent: name, max: 1024)
try validate(streamARN, name:"streamARN", parent: name, min: 1)
try validate(streamARN, name:"streamARN", parent: name, pattern: "arn:aws:kinesisvideo:[a-z0-9-]+:[0-9]+:[a-z]+/[a-zA-Z0-9_.-]+/[0-9]+")
}
private enum CodingKeys: String, CodingKey {
case currentVersion = "CurrentVersion"
case streamARN = "StreamARN"
}
}
public struct DeleteStreamOutput: AWSShape {
public init() {
}
}
public struct DescribeStreamInput: AWSShape {
public static var _members: [AWSShapeMember] = [
AWSShapeMember(label: "StreamARN", required: false, type: .string),
AWSShapeMember(label: "StreamName", required: false, type: .string)
]
/// The Amazon Resource Name (ARN) of the stream.
public let streamARN: String?
/// The name of the stream.
public let streamName: String?
public init(streamARN: String? = nil, streamName: String? = nil) {
self.streamARN = streamARN
self.streamName = streamName
}
public func validate(name: String) throws {
try validate(streamARN, name:"streamARN", parent: name, max: 1024)
try validate(streamARN, name:"streamARN", parent: name, min: 1)
try validate(streamARN, name:"streamARN", parent: name, pattern: "arn:aws:kinesisvideo:[a-z0-9-]+:[0-9]+:[a-z]+/[a-zA-Z0-9_.-]+/[0-9]+")
try validate(streamName, name:"streamName", parent: name, max: 256)
try validate(streamName, name:"streamName", parent: name, min: 1)
try validate(streamName, name:"streamName", parent: name, pattern: "[a-zA-Z0-9_.-]+")
}
private enum CodingKeys: String, CodingKey {
case streamARN = "StreamARN"
case streamName = "StreamName"
}
}
public struct DescribeStreamOutput: AWSShape {
public static var _members: [AWSShapeMember] = [
AWSShapeMember(label: "StreamInfo", required: false, type: .structure)
]
/// An object that describes the stream.
public let streamInfo: StreamInfo?
public init(streamInfo: StreamInfo? = nil) {
self.streamInfo = streamInfo
}
private enum CodingKeys: String, CodingKey {
case streamInfo = "StreamInfo"
}
}
public struct GetDataEndpointInput: AWSShape {
public static var _members: [AWSShapeMember] = [
AWSShapeMember(label: "APIName", required: true, type: .enum),
AWSShapeMember(label: "StreamARN", required: false, type: .string),
AWSShapeMember(label: "StreamName", required: false, type: .string)
]
/// The name of the API action for which to get an endpoint.
public let aPIName: APIName
/// The Amazon Resource Name (ARN) of the stream that you want to get the endpoint for. You must specify either this parameter or a StreamName in the request.
public let streamARN: String?
/// The name of the stream that you want to get the endpoint for. You must specify either this parameter or a StreamARN in the request.
public let streamName: String?
public init(aPIName: APIName, streamARN: String? = nil, streamName: String? = nil) {
self.aPIName = aPIName
self.streamARN = streamARN
self.streamName = streamName
}
public func validate(name: String) throws {
try validate(streamARN, name:"streamARN", parent: name, max: 1024)
try validate(streamARN, name:"streamARN", parent: name, min: 1)
try validate(streamARN, name:"streamARN", parent: name, pattern: "arn:aws:kinesisvideo:[a-z0-9-]+:[0-9]+:[a-z]+/[a-zA-Z0-9_.-]+/[0-9]+")
try validate(streamName, name:"streamName", parent: name, max: 256)
try validate(streamName, name:"streamName", parent: name, min: 1)
try validate(streamName, name:"streamName", parent: name, pattern: "[a-zA-Z0-9_.-]+")
}
private enum CodingKeys: String, CodingKey {
case aPIName = "APIName"
case streamARN = "StreamARN"
case streamName = "StreamName"
}
}
public struct GetDataEndpointOutput: AWSShape {
public static var _members: [AWSShapeMember] = [
AWSShapeMember(label: "DataEndpoint", required: false, type: .string)
]
/// The endpoint value. To read data from the stream or to write data to it, specify this endpoint in your application.
public let dataEndpoint: String?
public init(dataEndpoint: String? = nil) {
self.dataEndpoint = dataEndpoint
}
private enum CodingKeys: String, CodingKey {
case dataEndpoint = "DataEndpoint"
}
}
public struct ListStreamsInput: AWSShape {
public static var _members: [AWSShapeMember] = [
AWSShapeMember(label: "MaxResults", required: false, type: .integer),
AWSShapeMember(label: "NextToken", required: false, type: .string),
AWSShapeMember(label: "StreamNameCondition", required: false, type: .structure)
]
/// The maximum number of streams to return in the response. The default is 10,000.
public let maxResults: Int?
/// If you specify this parameter, when the result of a ListStreams operation is truncated, the call returns the NextToken in the response. To get another batch of streams, provide this token in your next request.
public let nextToken: String?
/// Optional: Returns only streams that satisfy a specific condition. Currently, you can specify only the prefix of a stream name as a condition.
public let streamNameCondition: StreamNameCondition?
public init(maxResults: Int? = nil, nextToken: String? = nil, streamNameCondition: StreamNameCondition? = nil) {
self.maxResults = maxResults
self.nextToken = nextToken
self.streamNameCondition = streamNameCondition
}
public func validate(name: String) throws {
try validate(maxResults, name:"maxResults", parent: name, max: 10000)
try validate(maxResults, name:"maxResults", parent: name, min: 1)
try validate(nextToken, name:"nextToken", parent: name, max: 512)
try validate(nextToken, name:"nextToken", parent: name, min: 0)
try streamNameCondition?.validate(name: "\(name).streamNameCondition")
}
private enum CodingKeys: String, CodingKey {
case maxResults = "MaxResults"
case nextToken = "NextToken"
case streamNameCondition = "StreamNameCondition"
}
}
public struct ListStreamsOutput: AWSShape {
public static var _members: [AWSShapeMember] = [
AWSShapeMember(label: "NextToken", required: false, type: .string),
AWSShapeMember(label: "StreamInfoList", required: false, type: .list)
]
/// If the response is truncated, the call returns this element with a token. To get the next batch of streams, use this token in your next request.
public let nextToken: String?
/// An array of StreamInfo objects.
public let streamInfoList: [StreamInfo]?
public init(nextToken: String? = nil, streamInfoList: [StreamInfo]? = nil) {
self.nextToken = nextToken
self.streamInfoList = streamInfoList
}
private enum CodingKeys: String, CodingKey {
case nextToken = "NextToken"
case streamInfoList = "StreamInfoList"
}
}
public struct ListTagsForStreamInput: AWSShape {
public static var _members: [AWSShapeMember] = [
AWSShapeMember(label: "NextToken", required: false, type: .string),
AWSShapeMember(label: "StreamARN", required: false, type: .string),
AWSShapeMember(label: "StreamName", required: false, type: .string)
]
/// If you specify this parameter and the result of a ListTagsForStream call is truncated, the response includes a token that you can use in the next request to fetch the next batch of tags.
public let nextToken: String?
/// The Amazon Resource Name (ARN) of the stream that you want to list tags for.
public let streamARN: String?
/// The name of the stream that you want to list tags for.
public let streamName: String?
public init(nextToken: String? = nil, streamARN: String? = nil, streamName: String? = nil) {
self.nextToken = nextToken
self.streamARN = streamARN
self.streamName = streamName
}
public func validate(name: String) throws {
try validate(nextToken, name:"nextToken", parent: name, max: 512)
try validate(nextToken, name:"nextToken", parent: name, min: 0)
try validate(streamARN, name:"streamARN", parent: name, max: 1024)
try validate(streamARN, name:"streamARN", parent: name, min: 1)
try validate(streamARN, name:"streamARN", parent: name, pattern: "arn:aws:kinesisvideo:[a-z0-9-]+:[0-9]+:[a-z]+/[a-zA-Z0-9_.-]+/[0-9]+")
try validate(streamName, name:"streamName", parent: name, max: 256)
try validate(streamName, name:"streamName", parent: name, min: 1)
try validate(streamName, name:"streamName", parent: name, pattern: "[a-zA-Z0-9_.-]+")
}
private enum CodingKeys: String, CodingKey {
case nextToken = "NextToken"
case streamARN = "StreamARN"
case streamName = "StreamName"
}
}
public struct ListTagsForStreamOutput: AWSShape {
public static var _members: [AWSShapeMember] = [
AWSShapeMember(label: "NextToken", required: false, type: .string),
AWSShapeMember(label: "Tags", required: false, type: .map)
]
/// If you specify this parameter and the result of a ListTags call is truncated, the response includes a token that you can use in the next request to fetch the next set of tags.
public let nextToken: String?
/// A map of tag keys and values associated with the specified stream.
public let tags: [String: String]?
public init(nextToken: String? = nil, tags: [String: String]? = nil) {
self.nextToken = nextToken
self.tags = tags
}
private enum CodingKeys: String, CodingKey {
case nextToken = "NextToken"
case tags = "Tags"
}
}
public enum Status: String, CustomStringConvertible, Codable {
case creating = "CREATING"
case active = "ACTIVE"
case updating = "UPDATING"
case deleting = "DELETING"
public var description: String { return self.rawValue }
}
public struct StreamInfo: AWSShape {
public static var _members: [AWSShapeMember] = [
AWSShapeMember(label: "CreationTime", required: false, type: .timestamp),
AWSShapeMember(label: "DataRetentionInHours", required: false, type: .integer),
AWSShapeMember(label: "DeviceName", required: false, type: .string),
AWSShapeMember(label: "KmsKeyId", required: false, type: .string),
AWSShapeMember(label: "MediaType", required: false, type: .string),
AWSShapeMember(label: "Status", required: false, type: .enum),
AWSShapeMember(label: "StreamARN", required: false, type: .string),
AWSShapeMember(label: "StreamName", required: false, type: .string),
AWSShapeMember(label: "Version", required: false, type: .string)
]
/// A time stamp that indicates when the stream was created.
public let creationTime: TimeStamp?
/// How long the stream retains data, in hours.
public let dataRetentionInHours: Int?
/// The name of the device that is associated with the stream.
public let deviceName: String?
/// The ID of the AWS Key Management Service (AWS KMS) key that Kinesis Video Streams uses to encrypt data on the stream.
public let kmsKeyId: String?
/// The MediaType of the stream.
public let mediaType: String?
/// The status of the stream.
public let status: Status?
/// The Amazon Resource Name (ARN) of the stream.
public let streamARN: String?
/// The name of the stream.
public let streamName: String?
/// The version of the stream.
public let version: String?
public init(creationTime: TimeStamp? = nil, dataRetentionInHours: Int? = nil, deviceName: String? = nil, kmsKeyId: String? = nil, mediaType: String? = nil, status: Status? = nil, streamARN: String? = nil, streamName: String? = nil, version: String? = nil) {
self.creationTime = creationTime
self.dataRetentionInHours = dataRetentionInHours
self.deviceName = deviceName
self.kmsKeyId = kmsKeyId
self.mediaType = mediaType
self.status = status
self.streamARN = streamARN
self.streamName = streamName
self.version = version
}
private enum CodingKeys: String, CodingKey {
case creationTime = "CreationTime"
case dataRetentionInHours = "DataRetentionInHours"
case deviceName = "DeviceName"
case kmsKeyId = "KmsKeyId"
case mediaType = "MediaType"
case status = "Status"
case streamARN = "StreamARN"
case streamName = "StreamName"
case version = "Version"
}
}
public struct StreamNameCondition: AWSShape {
public static var _members: [AWSShapeMember] = [
AWSShapeMember(label: "ComparisonOperator", required: false, type: .enum),
AWSShapeMember(label: "ComparisonValue", required: false, type: .string)
]
/// A comparison operator. Currently, you can specify only the BEGINS_WITH operator, which finds streams whose names start with a given prefix.
public let comparisonOperator: ComparisonOperator?
/// A value to compare.
public let comparisonValue: String?
public init(comparisonOperator: ComparisonOperator? = nil, comparisonValue: String? = nil) {
self.comparisonOperator = comparisonOperator
self.comparisonValue = comparisonValue
}
public func validate(name: String) throws {
try validate(comparisonValue, name:"comparisonValue", parent: name, max: 256)
try validate(comparisonValue, name:"comparisonValue", parent: name, min: 1)
try validate(comparisonValue, name:"comparisonValue", parent: name, pattern: "[a-zA-Z0-9_.-]+")
}
private enum CodingKeys: String, CodingKey {
case comparisonOperator = "ComparisonOperator"
case comparisonValue = "ComparisonValue"
}
}
public struct TagStreamInput: AWSShape {
public static var _members: [AWSShapeMember] = [
AWSShapeMember(label: "StreamARN", required: false, type: .string),
AWSShapeMember(label: "StreamName", required: false, type: .string),
AWSShapeMember(label: "Tags", required: true, type: .map)
]
/// The Amazon Resource Name (ARN) of the resource that you want to add the tag or tags to.
public let streamARN: String?
/// The name of the stream that you want to add the tag or tags to.
public let streamName: String?
/// A list of tags to associate with the specified stream. Each tag is a key-value pair (the value is optional).
public let tags: [String: String]
public init(streamARN: String? = nil, streamName: String? = nil, tags: [String: String]) {
self.streamARN = streamARN
self.streamName = streamName
self.tags = tags
}
public func validate(name: String) throws {
try validate(streamARN, name:"streamARN", parent: name, max: 1024)
try validate(streamARN, name:"streamARN", parent: name, min: 1)
try validate(streamARN, name:"streamARN", parent: name, pattern: "arn:aws:kinesisvideo:[a-z0-9-]+:[0-9]+:[a-z]+/[a-zA-Z0-9_.-]+/[0-9]+")
try validate(streamName, name:"streamName", parent: name, max: 256)
try validate(streamName, name:"streamName", parent: name, min: 1)
try validate(streamName, name:"streamName", parent: name, pattern: "[a-zA-Z0-9_.-]+")
try tags.forEach {
try validate($0.key, name:"tags.key", parent: name, max: 128)
try validate($0.key, name:"tags.key", parent: name, min: 1)
try validate($0.value, name:"tags[\"\($0.key)\"]", parent: name, max: 256)
try validate($0.value, name:"tags[\"\($0.key)\"]", parent: name, min: 0)
}
}
private enum CodingKeys: String, CodingKey {
case streamARN = "StreamARN"
case streamName = "StreamName"
case tags = "Tags"
}
}
public struct TagStreamOutput: AWSShape {
public init() {
}
}
public struct UntagStreamInput: AWSShape {
public static var _members: [AWSShapeMember] = [
AWSShapeMember(label: "StreamARN", required: false, type: .string),
AWSShapeMember(label: "StreamName", required: false, type: .string),
AWSShapeMember(label: "TagKeyList", required: true, type: .list)
]
/// The Amazon Resource Name (ARN) of the stream that you want to remove tags from.
public let streamARN: String?
/// The name of the stream that you want to remove tags from.
public let streamName: String?
/// A list of the keys of the tags that you want to remove.
public let tagKeyList: [String]
public init(streamARN: String? = nil, streamName: String? = nil, tagKeyList: [String]) {
self.streamARN = streamARN
self.streamName = streamName
self.tagKeyList = tagKeyList
}
public func validate(name: String) throws {
try validate(streamARN, name:"streamARN", parent: name, max: 1024)
try validate(streamARN, name:"streamARN", parent: name, min: 1)
try validate(streamARN, name:"streamARN", parent: name, pattern: "arn:aws:kinesisvideo:[a-z0-9-]+:[0-9]+:[a-z]+/[a-zA-Z0-9_.-]+/[0-9]+")
try validate(streamName, name:"streamName", parent: name, max: 256)
try validate(streamName, name:"streamName", parent: name, min: 1)
try validate(streamName, name:"streamName", parent: name, pattern: "[a-zA-Z0-9_.-]+")
try tagKeyList.forEach {
try validate($0, name: "tagKeyList[]", parent: name, max: 128)
try validate($0, name: "tagKeyList[]", parent: name, min: 1)
}
try validate(tagKeyList, name:"tagKeyList", parent: name, max: 50)
try validate(tagKeyList, name:"tagKeyList", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case streamARN = "StreamARN"
case streamName = "StreamName"
case tagKeyList = "TagKeyList"
}
}
public struct UntagStreamOutput: AWSShape {
public init() {
}
}
public struct UpdateDataRetentionInput: AWSShape {
public static var _members: [AWSShapeMember] = [
AWSShapeMember(label: "CurrentVersion", required: true, type: .string),
AWSShapeMember(label: "DataRetentionChangeInHours", required: true, type: .integer),
AWSShapeMember(label: "Operation", required: true, type: .enum),
AWSShapeMember(label: "StreamARN", required: false, type: .string),
AWSShapeMember(label: "StreamName", required: false, type: .string)
]
/// The version of the stream whose retention period you want to change. To get the version, call either the DescribeStream or the ListStreams API.
public let currentVersion: String
/// The retention period, in hours. The value you specify replaces the current value. The maximum value for this parameter is 87600 (ten years).
public let dataRetentionChangeInHours: Int
/// Indicates whether you want to increase or decrease the retention period.
public let operation: UpdateDataRetentionOperation
/// The Amazon Resource Name (ARN) of the stream whose retention period you want to change.
public let streamARN: String?
/// The name of the stream whose retention period you want to change.
public let streamName: String?
public init(currentVersion: String, dataRetentionChangeInHours: Int, operation: UpdateDataRetentionOperation, streamARN: String? = nil, streamName: String? = nil) {
self.currentVersion = currentVersion
self.dataRetentionChangeInHours = dataRetentionChangeInHours
self.operation = operation
self.streamARN = streamARN
self.streamName = streamName
}
public func validate(name: String) throws {
try validate(currentVersion, name:"currentVersion", parent: name, max: 64)
try validate(currentVersion, name:"currentVersion", parent: name, min: 1)
try validate(currentVersion, name:"currentVersion", parent: name, pattern: "[a-zA-Z0-9]+")
try validate(dataRetentionChangeInHours, name:"dataRetentionChangeInHours", parent: name, min: 1)
try validate(streamARN, name:"streamARN", parent: name, max: 1024)
try validate(streamARN, name:"streamARN", parent: name, min: 1)
try validate(streamARN, name:"streamARN", parent: name, pattern: "arn:aws:kinesisvideo:[a-z0-9-]+:[0-9]+:[a-z]+/[a-zA-Z0-9_.-]+/[0-9]+")
try validate(streamName, name:"streamName", parent: name, max: 256)
try validate(streamName, name:"streamName", parent: name, min: 1)
try validate(streamName, name:"streamName", parent: name, pattern: "[a-zA-Z0-9_.-]+")
}
private enum CodingKeys: String, CodingKey {
case currentVersion = "CurrentVersion"
case dataRetentionChangeInHours = "DataRetentionChangeInHours"
case operation = "Operation"
case streamARN = "StreamARN"
case streamName = "StreamName"
}
}
public enum UpdateDataRetentionOperation: String, CustomStringConvertible, Codable {
case increaseDataRetention = "INCREASE_DATA_RETENTION"
case decreaseDataRetention = "DECREASE_DATA_RETENTION"
public var description: String { return self.rawValue }
}
public struct UpdateDataRetentionOutput: AWSShape {
public init() {
}
}
public struct UpdateStreamInput: AWSShape {
public static var _members: [AWSShapeMember] = [
AWSShapeMember(label: "CurrentVersion", required: true, type: .string),
AWSShapeMember(label: "DeviceName", required: false, type: .string),
AWSShapeMember(label: "MediaType", required: false, type: .string),
AWSShapeMember(label: "StreamARN", required: false, type: .string),
AWSShapeMember(label: "StreamName", required: false, type: .string)
]
/// The version of the stream whose metadata you want to update.
public let currentVersion: String
/// The name of the device that is writing to the stream. In the current implementation, Kinesis Video Streams does not use this name.
public let deviceName: String?
/// The stream's media type. Use MediaType to specify the type of content that the stream contains to the consumers of the stream. For more information about media types, see Media Types. If you choose to specify the MediaType, see Naming Requirements. To play video on the console, you must specify the correct video type. For example, if the video in the stream is H.264, specify video/h264 as the MediaType.
public let mediaType: String?
/// The ARN of the stream whose metadata you want to update.
public let streamARN: String?
/// The name of the stream whose metadata you want to update. The stream name is an identifier for the stream, and must be unique for each account and region.
public let streamName: String?
public init(currentVersion: String, deviceName: String? = nil, mediaType: String? = nil, streamARN: String? = nil, streamName: String? = nil) {
self.currentVersion = currentVersion
self.deviceName = deviceName
self.mediaType = mediaType
self.streamARN = streamARN
self.streamName = streamName
}
public func validate(name: String) throws {
try validate(currentVersion, name:"currentVersion", parent: name, max: 64)
try validate(currentVersion, name:"currentVersion", parent: name, min: 1)
try validate(currentVersion, name:"currentVersion", parent: name, pattern: "[a-zA-Z0-9]+")
try validate(deviceName, name:"deviceName", parent: name, max: 128)
try validate(deviceName, name:"deviceName", parent: name, min: 1)
try validate(deviceName, name:"deviceName", parent: name, pattern: "[a-zA-Z0-9_.-]+")
try validate(mediaType, name:"mediaType", parent: name, max: 128)
try validate(mediaType, name:"mediaType", parent: name, min: 1)
try validate(mediaType, name:"mediaType", parent: name, pattern: "[\\w\\-\\.\\+]+/[\\w\\-\\.\\+]+(,[\\w\\-\\.\\+]+/[\\w\\-\\.\\+]+)*")
try validate(streamARN, name:"streamARN", parent: name, max: 1024)
try validate(streamARN, name:"streamARN", parent: name, min: 1)
try validate(streamARN, name:"streamARN", parent: name, pattern: "arn:aws:kinesisvideo:[a-z0-9-]+:[0-9]+:[a-z]+/[a-zA-Z0-9_.-]+/[0-9]+")
try validate(streamName, name:"streamName", parent: name, max: 256)
try validate(streamName, name:"streamName", parent: name, min: 1)
try validate(streamName, name:"streamName", parent: name, pattern: "[a-zA-Z0-9_.-]+")
}
private enum CodingKeys: String, CodingKey {
case currentVersion = "CurrentVersion"
case deviceName = "DeviceName"
case mediaType = "MediaType"
case streamARN = "StreamARN"
case streamName = "StreamName"
}
}
public struct UpdateStreamOutput: AWSShape {
public init() {
}
}
}
| 50.397059 | 522 | 0.630989 |
acf3519a1c8b9e7e49685f5fb929a9777add4ade | 509 | //
// ViewController.swift
// CBLibrary
//
// Created by estebansanc on 03/24/2022.
// Copyright (c) 2022 estebansanc. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 20.36 | 80 | 0.67387 |
142b12d06032c7195d9b5dd8c23cf153258b63ed | 2,399 | //
// ViewController.swift
// MapComponent
//
// Created by Dave Duprey on 08/10/2021.
//
import UIKit
import W3WSwiftApi
import W3WSwiftComponents
/// This demonstrates `W3WMapViewController` which is a high level component
/// that has easy to use what3words functionality. If you already have a map in your
/// application then you will want to use `W3WMapHelper` to add the what3words
/// grid and pins to your map. Find the example called MapHelper. If you have no map in your
/// app and want to quickly include on with some default behaviours then it's easy
/// to include this one.
class ViewController: W3WMapViewController {
let api = What3WordsV3(apiKey: "Your API Key")
override func viewDidLoad() {
super.viewDidLoad()
// give the map access to the API
set(api)
// make an autosuggest text field with voice option, and attach it to the view (voice functionality requires API key permissions, contact what3words to enable this - https://accounts.what3words.com/overview)
let textField = W3WAutoSuggestTextField(api)
textField.set(voice: true)
attach(textField: textField)
// when an autosuggest suggestion is selected from the text field, show it on the map and clear previous selections
textField.onSuggestionSelected = { suggestion in
self.removeAllMarkers()
self.addMarker(at: suggestion, camera: .zoom)
}
// when a point on the map is touched, highlight that square, and put it's word into the text field
self.onSquareSelected = { square in
self.addMarker(at: square, camera: .center)
textField.set(display: square)
}
// make a satelite/map button, and attach it
let button = W3WMapTypeButton()
attach(view: button, position: .bottomRight)
// if the is an error then put it into an alert
onError = { error in self.showError(error: error) }
addMarker(at: "filled.count.soap", camera: .zoom)
}
/// display an error using a UIAlertController, error messages conform to CustomStringConvertible
func showError(error: Error) {
DispatchQueue.main.async {
let alert = UIAlertController(title: "Error", message: String(describing: error), preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Dismiss", style: .cancel, handler: nil))
self.present(alert, animated: true)
}
}
}
| 33.319444 | 211 | 0.703627 |
18248745c683023a48e385d7591e00d8847d44ce | 1,837 | //
// Copyright (c) 2015 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
import Firebase
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var currentDeepLink: NSURL?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
FIRApp.configure()
// [START register_app]
// Replace 123456 with the App Store ID of your app.
// Registering your application allows your app to be included in
// Google Search results.
FIRAppIndexing.sharedInstance().registerApp(123456)
// [END register_app]
return true
}
// [START handle_link]
func application(application: UIApplication,
openURL url: NSURL,
sourceApplication: String?,
annotation: AnyObject) -> Bool {
currentDeepLink = url
return true;
}
// [END handle_link]
// [START handle_universal_link]
@available(iOS 8.0, *)
func application(application: UIApplication,
continueUserActivity userActivity: NSUserActivity,
restorationHandler: ([AnyObject]?) -> Void) -> Bool {
currentDeepLink = userActivity.webpageURL
return true
}
// [END handle_universal_link]
}
| 31.135593 | 125 | 0.692978 |
469948255eb745219d04934ff7da327b46a2132c | 1,227 | //
// First.swift
// VirtualAssistantforiOSSideProject
//
// Created by Omar Yahya Alfawzan on 8/7/18.
// Copyright © 2018 IBM. All rights reserved.
//
import UIKit
class First: UIViewController {
@IBOutlet weak var gifimageview: UIImageView!
@IBOutlet weak var load: UIView!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor(patternImage: UIImage(named: "food1")!)
gifimageview.image = UIImage.gif(name: "logo")
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(2000)) {
self.load.isHidden = true
}
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 27.266667 | 106 | 0.657702 |
f875e756f7c0b64f242b8b6a2505f3022792b2ed | 1,082 | import Foundation
import XCTest
import Accounts
import RxSwift
import RxCocoa
@testable import Tweetie
class TwitterTestAPI: TwitterAPIProtocol {
static func reset() {
lastMethodCall = nil
objects = PublishSubject<[JSONObject]>()
}
static var objects = PublishSubject<[JSONObject]>()
static var lastMethodCall: String?
static func timeline(of username: String) -> (AccessToken, TimelineCursor) -> Observable<[JSONObject]> {
return { account, cursor in
lastMethodCall = #function
return objects.asObservable()
}
}
static func timeline(of list: ListIdentifier) -> (AccessToken, TimelineCursor) -> Observable<[JSONObject]> {
return { account, cursor in
lastMethodCall = #function
return objects.asObservable()
}
}
static func members(of list: ListIdentifier) -> (AccessToken) -> Observable<[JSONObject]> {
return { list in
lastMethodCall = #function
return objects.asObservable()
}
}
}
| 27.05 | 112 | 0.631238 |
1c19515fe3837b048fb8023639faae2d44b788ea | 1,920 | //
// QueueSummaryCell.swift
// Stampede
//
// Created by David House on 8/30/20.
// Copyright © 2020 David House. All rights reserved.
//
import SwiftUI
struct QueueSummaryCell: View {
let queueSummary: QueueSummary
var body: some View {
HStack {
switch queueSummary.stats.waiting {
case 0..<3:
CurrentTheme.Icons.okStatus.image().font(Font.system(size: 32, weight: .regular))
case 3..<6:
CurrentTheme.Icons.warningStatus.image().font(Font.system(size: 32, weight: .regular))
default:
CurrentTheme.Icons.errorStatus.image().font(Font.system(size: 32, weight: .regular))
}
VStack(alignment: .leading) {
PrimaryLabel(queueSummary.queue)
}
Spacer()
switch queueSummary.stats.waiting {
case 0:
ValueLabel("No waiting tasks")
case 1:
ValueLabel("1 waiting task")
default:
ValueLabel("\(queueSummary.stats.waiting) waiting tasks")
}
}
}
}
#if DEBUG
struct QueueSummaryCell_Previews: PreviewProvider, Previewable {
static var previews: some View {
QueueSummaryCell_Previews.debugPreviews
}
static var defaultViewModel: PreviewData<QueueSummary> {
PreviewData(id: "oneWaiting", viewModel: QueueSummary.oneWaiting)
}
static var alternateViewModels: [PreviewData<QueueSummary>] {
[
PreviewData(id: "noWaiting", viewModel: QueueSummary.noWaiting),
PreviewData(id: "moreWaiting", viewModel: QueueSummary.moreWaiting),
PreviewData(id: "alotWaiting", viewModel: QueueSummary.alotWaiting)
]
}
static func create(from viewModel: QueueSummary) -> some View {
return QueueSummaryCell(queueSummary: viewModel)
}
}
#endif
| 29.538462 | 102 | 0.606771 |
160e78e6bdf61053bb153788fb9950281dacfcc5 | 613 | //
// LocationTableViewCell.swift
// WeatherInfo
//
// Created by Alok Choudhary on 8/3/18.
// Copyright © 2018 Mt Aden LLC. All rights reserved.
//
import UIKit
class LocationTableViewCell: UITableViewCell {
// MARK: - Type Properties
static let reuseIdentifier = "LocationCell"
// MARK: - Properties
@IBOutlet var mainLabel: UILabel!
// MARK: - Initialization
override func awakeFromNib() {
super.awakeFromNib()
}
// MARK: - Configuration
func configure(withViewModel viewModel: LocationRepresentable) {
mainLabel.text = viewModel.text
}
}
| 18.029412 | 68 | 0.66721 |
4b8c75208f21647781e04bea55d05129b3392c34 | 909 | import Foundation
import SwiftyJSON
open class PutioTrashFile: PutioBaseFile {
open var deletedAt: Date
open var expiresOn: Date
override init(json: JSON) {
let formatter = ISO8601DateFormatter()
self.deletedAt = formatter.date(from: json["deleted_at"].stringValue) ?? formatter.date(from: "\(json["deleted_at"].stringValue)+00:00")!
self.expiresOn = formatter.date(from: json["expiration_date"].stringValue) ?? formatter.date(from: "\(json["expiration_date"].stringValue)+00:00")!
super.init(json: json)
}
}
open class PutioListTrashResponse {
open var cursor: String
open var trash_size: Int64
open var files: [PutioTrashFile]
init(json: JSON) {
self.cursor = json["cursor"].stringValue
self.trash_size = json["trash_size"].int64Value
self.files = json["files"].arrayValue.map { PutioTrashFile(json: $0) }
}
}
| 32.464286 | 155 | 0.679868 |
469b94b1284b2b6dd61bdb0b418e48e5b2667177 | 274 | //
// C2StrokeCount+Parsing.swift
// Pods
//
// Created by Jesse Curry on 10/27/15.
// Edited by Paul Aschmann on 08/06/2020
//
extension C2StrokeCount {
/**
*/
init(strokeCountWithLow low:UInt16, high:UInt16) {
self = C2StrokeCount(low | (high << 8))
}
}
| 17.125 | 52 | 0.635036 |
ddbb263655bd0e9db6d5b9c18ab59b31ef3ee991 | 370 | //
// weatherData.swift
// weather app
//
// Created by Swamita on 29/05/20.
// Copyright © 2020 Swamita. All rights reserved.
//
import Foundation
struct WeatherData: Codable {
let weather: [Weather]
let main: Main
let name: String
}
struct Main: Codable{
let temp: Double
}
struct Weather: Codable{
let description: String
let id: Int
}
| 15.416667 | 50 | 0.664865 |
db7eecfd07e152ddb733999057e58cbf81887c8a | 154 | import XCTest
@testable import UIPreviewCatalog
final class UIPreviewCatalogTests: XCTestCase {
func testExample() {
}
}
| 19.25 | 51 | 0.636364 |
4b593a2c27e1fed72604c226a874e6aee5ee30df | 1,642 | //
// UIExtensions.swift
// MyStampWallet
//
// Created by Admin on 19/06/2019.
// Copyright © 2019 Cowboy. All rights reserved.
//
import UIKit
@IBDesignable
class RotationView: UIImageView {
@IBInspectable
var angle: CGFloat = 0.0;
override func layoutSubviews() {
super.layoutSubviews()
self.transform = CGAffineTransform.identity.rotated(by: angle/180*CGFloat.pi)
}
}
@IBDesignable
class RoundButton: UIButton {
@IBInspectable var radius: CGFloat = 0
override func layoutSubviews() {
super.layoutSubviews()
layer.masksToBounds = false
layer.cornerRadius = radius
}
}
@IBDesignable
class RoundView: UIView {
@IBInspectable var radius: CGFloat = 0
override func layoutSubviews() {
super.layoutSubviews()
layer.masksToBounds = false
layer.cornerRadius = radius
}
}
extension UIImage {
func imageWithColor(color1: UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
color1.setFill()
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(origin: .zero, size: CGSize(width: self.size.width, height: self.size.height))
context?.clip(to: rect, mask: self.cgImage!)
context?.fill(rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
}
| 24.878788 | 104 | 0.6419 |
4b61da9820fa944180d39a68e1cdec9a6c2c8dc3 | 1,114 | //
// Project+CoreDataClass.swift
// MyList
//
// Created by Samuel Folledo on 6/29/20.
// Copyright © 2020 SamuelFolledo. All rights reserved.
//
//
import Foundation
import CoreData
@objc(Project)
public class Project: NSManagedObject {
}
extension Project {
///to section each project by day of lastOpenedDate
@objc var isoDate: String {
get {
let formatter = DateFormatter()
formatter.dateFormat = "d MMMM yyyy"
// insert settings for TimeZone and Calendar here
return formatter.string(from: self.lastOpenedDate)
}
}
@objc var toDoTasks: [Task] {
get {
guard let tasks = self.tasks.array as? [Task] else { return [] } //convert tasks to array of tasks
return tasks.filter() { !$0.isDone } //return unfinished tasks
}
}
@objc var doneTasks: [Task] {
get {
guard let tasks = self.tasks.array as? [Task] else { return [] } //convert tasks to array of tasks
return tasks.filter() { $0.isDone } //return finished tasks
}
}
}
| 25.906977 | 110 | 0.596948 |
21072ad364d3fa802026a2985853ced3026cab56 | 1,296 | //
// OpenWeatherMapServiceURLRequestBuilderTests.swift
// WeatherKitTests
//
// Created by David Messing on 6/1/18.
// Copyright © 2018 davemess. All rights reserved.
//
import XCTest
@testable import WeatherKit
class OpenWeatherMapServiceURLRequestBuilderTests: XCTestCase {
func testReturnsNilRequestIfUrlBuilderReturnsNilUrl() {
let urlBuilder = MockOpenWeatherMapServiceURLBuilder(url: nil)
let requestBuilder = OpenWeatherMapServiceURLRequestBuilderImpl(urlBuilder: urlBuilder)
let operation = OpenWeatherMapOperation.getCurrentByCityId(id: "Austin")
let request = requestBuilder.build(for: operation)
XCTAssertNil(request)
}
func testReturnsNonNilRequestIfUrlBuilderReturnsNonNilUrl() {
let url = URL(string: "https://openweathermap.org")!
let urlBuilder = MockOpenWeatherMapServiceURLBuilder(url: url)
let requestBuilder = OpenWeatherMapServiceURLRequestBuilderImpl(urlBuilder: urlBuilder)
let operation = OpenWeatherMapOperation.getCurrentByCityId(id: "Austin")
let request = requestBuilder.build(for: operation)
XCTAssertNotNil(request)
XCTAssertEqual(request?.httpMethod, "GET")
XCTAssertEqual(request?.url, url)
}
}
| 35.027027 | 95 | 0.722994 |
fef960b88eaeede585acd712eb6293c8e76f1757 | 9,004 | //
// HSCutomProgress.swift
// HSCustomView
//
// Created by haisheng huang on 2017/1/4.
// Copyright © 2017年 haisheng huang. All rights reserved.
//
import Foundation
import UIKit
import CoreFoundation
//MARK:渐变效果的方向
public enum GradientChangeDirection {
case right
case left
case bottom
case top
case topLeftToBottomRight
case topRightToBottomLeft
case bottomLeftToTopRight
case bottomRightToTopLeft
}
public class HSCustomProgress: UIView {
//MARK:进度条百分比,默认为0.0
public var value: CGFloat = 0.0 {
willSet {
//do something
}
didSet {
self.createGradientView()
if self.isAnimated == true {
self.addAnimation(duration: self.duration)
}
}
}
//MARK:渐变的深色,默认为黑色
public var deepColor: UIColor = UIColor.black
//MARK:渐变的浅色,默认为白色
public var lightColor: UIColor = UIColor.white
//Mark:当前值的深色
private var valueColor: UIColor?
//GradientChangeDirection default direction is right
public var direction: GradientChangeDirection = GradientChangeDirection.right
//MARK:是否是圆角,默认是true
public var isCornerRadius: Bool = true
//MARK:是否动态加载,默认是false
var isAnimated: Bool = false
//MARK:渐变的Layer
var gradientLayer: CAGradientLayer?
//MARK:渐变的view,由于caanimation的frame实现不了动画,所以采用了UIView的Animation
var gradientView: UIView?
//MARK:动画的持续时间, 默认时间为1.5秒
public var duration: TimeInterval = 1.5
override init(frame: CGRect) {
super.init(frame: frame)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
convenience init(frame: CGRect, deepColor: UIColor?, lightColor: UIColor?, backgroundColor: UIColor?, value: CGFloat, isCornerRadius: Bool, direction: GradientChangeDirection?, isAnimated: Bool?, duration: TimeInterval?) {
self.init(frame: frame)
if deepColor != nil {
self.deepColor = deepColor!
}
if lightColor != nil {
self.lightColor = lightColor!
}
if backgroundColor != nil {
self.backgroundColor = backgroundColor
}
if isCornerRadius == false {
self.isCornerRadius = false
} else {
self.layer.cornerRadius = self.frame.height / 2.0
}
if direction != nil {
self.direction = direction!
}
self.createGradientView()
if isAnimated == true {
self.isAnimated = true
}
if duration != nil {
self.duration = duration!
}
self.value = value
//TODO: 由于不知道什么原因,value的willset和didset方法在初始化方法中没有执行
//所以需要执行一次一下的刷新,需要优化
self.createGradientView()
if self.isAnimated == true {
self.addAnimation(duration: self.duration)
}
}
@discardableResult
class func create(at superView: UIView, frame: CGRect, deepColor: UIColor?, lightColor: UIColor?, backgroundColor: UIColor?, value: CGFloat, isCornerRadius: Bool, direction: GradientChangeDirection?, isAnimated: Bool?, duration: TimeInterval) -> HSCustomProgress {
let progress: HSCustomProgress = HSCustomProgress.init(frame: frame, deepColor: deepColor, lightColor: lightColor, backgroundColor: backgroundColor, value: value, isCornerRadius: isCornerRadius, direction: direction, isAnimated: isAnimated, duration: duration)
superView.addSubview(progress)
return progress
}
private func createGradientLayer() -> Void {
if self.value < 1.0 && self.value > 0.0 {
self.getCurrentDeepColor(deepColor: self.deepColor, lightColor: self.lightColor, value: self.value)
}
let gradientColors: [CGColor] = [self.lightColor.cgColor, self.deepColor.cgColor]
if self.gradientLayer == nil {
let gradientLayer: CAGradientLayer = CAGradientLayer()
self.setChangeDirection(gradientLayer: gradientLayer, direction: self.direction)
if self.isCornerRadius == true {
gradientLayer.cornerRadius = self.frame.height / 2.0
}
self.gradientLayer = gradientLayer
}
self.gradientLayer!.frame = CGRect.init(x: 0.0, y: 0.0, width: self.frame.width * self.value, height: self.frame.height)
self.gradientLayer!.colors = gradientColors
}
private func createGradientView() -> Void {
self.createGradientLayer()
if self.gradientView == nil {
let view: UIView = UIView()
view.backgroundColor = UIColor.clear
view.layer.masksToBounds = true //TODO: 有可能需要优化,否则多个使用后有可能会出现离屏渲染影响性能效果
view.layer.cornerRadius = self.frame.height / 2.0
view.frame = CGRect.init(x: 0.0, y: 0.0, width: 0.0, height: self.frame.height)
self.addSubview(view)
view.layer.addSublayer(self.gradientLayer!)
self.gradientView = view
}
}
private func getCurrentDeepColor(deepColor: UIColor, lightColor: UIColor, value: CGFloat) -> Void {
let deepColorComponents: [CGFloat] = deepColor.cgColor.components!
let lightColorComponents: [CGFloat] = lightColor.cgColor.components!
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
if deepColorComponents[0] == 1.0 && deepColorComponents[0] == lightColorComponents[0] {
red = 1.0
} else if deepColorComponents[0] > lightColorComponents[0] {
red = lightColorComponents[0] + (deepColorComponents[0] - lightColorComponents[0]) * value
} else if deepColorComponents[0] < lightColorComponents[0] {
red = lightColorComponents[0] - (lightColorComponents[0] - deepColorComponents[0]) * value
}
if deepColorComponents[1] == 1.0 && deepColorComponents[1] == lightColorComponents[1] {
green = 1.0
} else if deepColorComponents[1] > lightColorComponents[1] {
green = lightColorComponents[1] + (deepColorComponents[1] - lightColorComponents[1]) * value
} else if deepColorComponents[1] < lightColorComponents[1] {
green = lightColorComponents[1] - (lightColorComponents[1] - deepColorComponents[1]) * value
}
if deepColorComponents[2] == 1.0 && deepColorComponents[2] == lightColorComponents[2] {
blue = 1.0
} else if deepColorComponents[2] > lightColorComponents[2] {
blue = lightColorComponents[2] + (deepColorComponents[2] - lightColorComponents[2]) * value
} else if deepColorComponents[2] < lightColorComponents[2] {
blue = lightColorComponents[2] - (lightColorComponents[2] - deepColorComponents[2]) * value
}
self.valueColor = UIColor.init(red: red, green: green, blue: blue, alpha: 1.0)
}
private func setChangeDirection(gradientLayer: CAGradientLayer, direction: GradientChangeDirection) -> Void {
switch direction {
case .right:
gradientLayer.startPoint = CGPoint.init(x: 0.0, y: 0.5)
gradientLayer.endPoint = CGPoint.init(x: 1.0, y: 0.5)
case .left:
gradientLayer.startPoint = CGPoint.init(x: 1.0, y: 0.5)
gradientLayer.endPoint = CGPoint.init(x: 0.0, y: 0.5)
case .bottom:
gradientLayer.startPoint = CGPoint.init(x: 0.5, y: 0.0)
gradientLayer.endPoint = CGPoint.init(x: 0.5, y: 1.0)
case .top:
gradientLayer.startPoint = CGPoint.init(x: 0.5, y: 1.0)
gradientLayer.endPoint = CGPoint.init(x: 0.5, y: 0.0)
case .topLeftToBottomRight:
gradientLayer.startPoint = CGPoint.init(x: 0.0, y: 0.0)
gradientLayer.endPoint = CGPoint.init(x: 1.0, y: 1.0)
case .topRightToBottomLeft:
gradientLayer.startPoint = CGPoint.init(x: 1.0, y: 0.0)
gradientLayer.endPoint = CGPoint.init(x: 0.0, y: 1.0)
case .bottomLeftToTopRight:
gradientLayer.startPoint = CGPoint.init(x: 0.0, y: 1.0)
gradientLayer.endPoint = CGPoint.init(x: 1.0, y: 0.0)
default:
gradientLayer.startPoint = CGPoint.init(x: 1.0, y: 1.0)
gradientLayer.endPoint = CGPoint.init(x: 0.0, y: 0.0)
}
}
func addAnimation(duration: TimeInterval) -> Void {
UIView.animate(withDuration: duration, animations: { [unowned self] in
self.gradientView?.frame.size.width = self.frame.width * self.value
}, completion: { finish in
})
}
}
| 35.171875 | 268 | 0.60562 |
b904104b35ed04c8177ce3f9cdf56f8f7c99d7a1 | 3,225 | //
// CourseCatalogAPI.swift
// edX
//
// Created by Anna Callahan on 10/14/15.
// Copyright © 2015 edX. All rights reserved.
//
import edXCore
public struct CourseCatalogAPI {
static func coursesDeserializer(response : HTTPURLResponse, json : JSON) -> Result<[OEXCourse]> {
return (json.array?.flatMap {item in
item.dictionaryObject.map { OEXCourse(dictionary: $0) }
}).toResult()
}
static func courseDeserializer(response : HTTPURLResponse, json : JSON) -> Result<OEXCourse> {
return json.dictionaryObject.map { OEXCourse(dictionary: $0) }.toResult()
}
static func enrollmentDeserializer(response: HTTPURLResponse, json: JSON) -> Result<UserCourseEnrollment> {
return UserCourseEnrollment(json: json).toResult()
}
private enum Params : String {
case User = "username"
case CourseDetails = "course_details"
case CourseID = "course_id"
case EmailOptIn = "email_opt_in"
case Mobile = "mobile"
case Org = "org"
}
public static func getCourseCatalog(categoryID: Int, userID: String, page: Int, organizationCode: String?) -> NetworkRequest<Paginated<[OEXCourse]>> {
var query = [Params.Mobile.rawValue: JSON(true), Params.User.rawValue: JSON(userID)]
if let orgCode = organizationCode {
query[Params.Org.rawValue] = JSON(orgCode)
}
return NetworkRequest(
method: .GET,
path : "api/courses/v1/courses/?course_category_id=\(categoryID)",
requiresAuth : true,
query : query,
deserializer: .jsonResponse(coursesDeserializer)
).paginated(page: page)
}
public static func getCourseCatalog(userID: String, page : Int, organizationCode: String?) -> NetworkRequest<Paginated<[OEXCourse]>> {
var query = [Params.Mobile.rawValue: JSON(true), Params.User.rawValue: JSON(userID)]
if let orgCode = organizationCode {
query[Params.Org.rawValue] = JSON(orgCode)
}
return NetworkRequest(
method: .GET,
path : "api/courses/v1/courses/",
requiresAuth : true,
query : query,
deserializer: .jsonResponse(coursesDeserializer)
).paginated(page: page)
}
public static func getCourse(courseID: String) -> NetworkRequest<OEXCourse> {
return NetworkRequest(
method: .GET,
path: "api/courses/v1/courses/{courseID}".oex_format(withParameters: ["courseID" : courseID]),
deserializer: .jsonResponse(courseDeserializer))
}
public static func enroll(courseID: String, emailOptIn: Bool = true) -> NetworkRequest<UserCourseEnrollment> {
return NetworkRequest(
method: .POST,
path: "api/enrollment/v1/enrollment",
requiresAuth: true,
body: .jsonBody(JSON([
"course_details" : [
"course_id": courseID,
"email_opt_in": emailOptIn
]
])),
deserializer: .jsonResponse(enrollmentDeserializer)
)
}
}
| 35.43956 | 155 | 0.603101 |
48f973757b98c5a9f94a14c5cb10fe79d7d4eea7 | 2,040 | //
// JXPhotoBrowserAnimatedTransitioning.swift
// JXPhotoBrowser
//
// Created by JiongXing on 2019/11/25.
// Copyright © 2019 JiongXing. All rights reserved.
//
import UIKit
public protocol JXPhotoBrowserAnimatedTransitioning: UIViewControllerAnimatedTransitioning {
var isForShow: Bool { get set }
var photoBrowser: JXPhotoBrowser? { get set }
var isNavigationAnimation: Bool { get set }
}
private var isForShowKey: Int8?
private var photoBrowserKey: Int8?
extension JXPhotoBrowserAnimatedTransitioning {
public var isForShow: Bool {
get {
if let value = objc_getAssociatedObject(self, &isForShowKey) as? Bool {
return value
}
return true
}
set {
objc_setAssociatedObject(self, &isForShowKey, newValue, .OBJC_ASSOCIATION_ASSIGN)
}
}
public var photoBrowser: JXPhotoBrowser? {
get {
objc_getAssociatedObject(self, &photoBrowserKey) as? JXPhotoBrowser
}
set {
objc_setAssociatedObject(self, &photoBrowserKey, newValue, .OBJC_ASSOCIATION_ASSIGN)
}
}
public var isNavigationAnimation: Bool {
get { false }
set { }
}
public func fastSnapshot(with view: UIView) -> UIView? {
UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, UIScreen.main.scale)
view.drawHierarchy(in: view.bounds, afterScreenUpdates: false)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return UIImageView(image: image)
}
public func snapshot(with view: UIView) -> UIView? {
UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, UIScreen.main.scale)
guard let context = UIGraphicsGetCurrentContext() else { return nil }
view.layer.render(in: context)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return UIImageView(image: image)
}
}
| 31.384615 | 96 | 0.668627 |
28c7fe3865b2278cf9293720d6eec39b56d4cf61 | 7,930 | //
// ShareImageInstagram.swift
// DemoProject(ChoosePicture)
//
// Created by Swapnil Patel on 25/06/19.
// Copyright © 2019 Swapnil Patel. All rights reserved.
//
import Foundation
import UIKit
import Photos
public protocol ShareStoriesDelegate {
func error(message: String)
func success()
}
open class ShareImageInstagram {
private let instagramURL = URL(string: "instagram://app")
private let instagramStoriesURL = URL(string: "instagram-stories://share")
var delegate: ShareStoriesDelegate?
public init() {
}
func alert (with message :String,title :String = "" , appStoreurl : String , parentVC : UIViewController) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let OKAction = UIAlertAction(title: "OK", style: .default) { action in
if let url = URL(string: appStoreurl),
UIApplication.shared.canOpenURL(url)
{
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url)
}
}
}
let CancelAction = UIAlertAction(title: "Cancel", style: .default) { action in
print("You've pressed Cancel Button")
}
alertController.addAction(OKAction)
alertController.addAction(CancelAction)
parentVC.present(alertController, animated: true, completion: nil)
}
public func postToInstagramFeed(image: UIImage, caption: String, bounds: CGRect, view: UIView) {
PHPhotoLibrary.shared().performChanges({
PHAssetChangeRequest.creationRequestForAsset(from: image)
}, completionHandler: { success, error in
if success {
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
let fetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions)
if let lastAsset = fetchResult.firstObject {
let localIdentifier = lastAsset.localIdentifier
let urlFeed = "instagram://library?LocalIdentifier=" + localIdentifier
guard let url = URL(string: urlFeed) else {
self.delegate?.error(message: "Could not open url")
return
}
DispatchQueue.main.async {
if UIApplication.shared.canOpenURL(url) {
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:], completionHandler: { (success) in
self.delegate?.success()
})
} else {
UIApplication.shared.openURL(url)
self.delegate?.success()
}
} else {
self.delegate?.error(message: "Instagram not found")
}
}
}
} else if let error = error {
self.delegate?.error(message: error.localizedDescription)
}
else {
self.delegate?.error(message: "Could not save the photo")
}
})
}
public func postToInstagramStories(data: NSData, image: UIImage, backgroundTopColorHex: String, backgroundBottomColorHex: String, deepLink: String) {
DispatchQueue.main.async {
guard let url = self.instagramURL else {
self.delegate?.error(message: "URL not valid")
return
}
if UIApplication.shared.canOpenURL(url) {
guard let urlScheme = self.instagramStoriesURL else {
self.delegate?.error(message: "URL not valid")
return
}
let pasteboardItems = ["com.instagram.sharedSticker.stickerImage": image,
"com.instagram.sharedSticker.backgroundTopColor" : backgroundTopColorHex,
"com.instagram.sharedSticker.backgroundBottomColor" : backgroundBottomColorHex,
"com.instagram.sharedSticker.backgroundVideo": data,
"com.instagram.sharedSticker.contentURL": deepLink] as [String : Any]
if #available(iOS 10.0, *) {
let pasteboardOptions = [UIPasteboard.OptionsKey.expirationDate : NSDate().addingTimeInterval(60 * 5)]
UIPasteboard.general.setItems([pasteboardItems], options: pasteboardOptions)
} else {
UIPasteboard.general.items = [pasteboardItems]
}
if #available(iOS 10.0, *) {
UIApplication.shared.open(urlScheme, options: [:], completionHandler: { (success) in
self.delegate?.success()
})
} else {
UIApplication.shared.openURL(urlScheme)
self.delegate?.success()
}
} else {
self.delegate?.error(message: "Could not open instagram URL. Check if you have instagram installed and you configured your LSApplicationQueriesSchemes to enable instagram's url")
}
}
}
public func postToInstagramStories(image: UIImage, backgroundTopColorHex: String, backgroundBottomColorHex: String, deepLink: String) {
DispatchQueue.main.async {
guard let url = self.instagramURL else {
self.delegate?.error(message: "URL not valid")
return
}
if UIApplication.shared.canOpenURL(url) {
guard let urlScheme = self.instagramStoriesURL else {
self.delegate?.error(message: "URL not valid")
return
}
let pasteboardItems = ["com.instagram.sharedSticker.stickerImage": image,
"com.instagram.sharedSticker.backgroundTopColor" : backgroundTopColorHex,
"com.instagram.sharedSticker.backgroundBottomColor" : backgroundBottomColorHex,
"com.instagram.sharedSticker.contentURL": deepLink] as [String : Any]
if #available(iOS 10.0, *) {
let pasteboardOptions = [UIPasteboard.OptionsKey.expirationDate : NSDate().addingTimeInterval(60 * 5)]
UIPasteboard.general.setItems([pasteboardItems], options: pasteboardOptions)
} else {
UIPasteboard.general.items = [pasteboardItems]
}
if #available(iOS 10.0, *) {
UIApplication.shared.open(urlScheme, options: [:], completionHandler: { (success) in
self.delegate?.success()
})
} else {
UIApplication.shared.openURL(urlScheme)
self.delegate?.success()
}
} else {
self.delegate?.error(message: "Could not open instagram URL. Check if you have instagram installed and you configured your LSApplicationQueriesSchemes to enable instagram's url")
}
}
}
}
| 44.055556 | 194 | 0.52459 |
8a8c2dd3df0befd9d14c1e06c608994d9d6531b9 | 496 | //
// TimeInterval.swift
// ReSwift
//
// Created by Miha Herblan on 26/01/2017.
// Copyright © 2017 Miha Herblan. All rights reserved.
//
import Foundation
extension TimeInterval {
var minutesAndSeconds:String{
return minutesAndSeconds()
}
func minutesAndSeconds(separator:String = ":")->String{
let min = Int(self) >= 60 ? Int(self) / 60 : 0
let sec = Int(self) >= 60 ? Int(self) - min*60 : Int(self)
return "\(min)\(separator)\(sec)"
}
}
| 22.545455 | 66 | 0.610887 |
39b40dcf8aff4f7075604c8706bd9210be2a195e | 446 | //
// Operation+.swift
// Celio
//
// Created by MP-11 on 07/08/18.
// Copyright © 2018 Jatin. All rights reserved.
//
import Foundation
extension Operation {
func addCompletionBlock(block: @escaping () -> Void) {
if let existingBlock = completionBlock {
completionBlock = {
existingBlock()
block()
}
} else {
completionBlock = block
}
}
}
| 19.391304 | 58 | 0.533632 |
fea63f12cbb807e03142fb4be7bcf7e11c227419 | 5,867 | //
// Copyright 2017 Mobile Jazz SL
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
// ------------ Basic Foundation Types ------------ //
// MARK: Collections
public extension Array {
func toFuture() -> Future<[Element]> {
return Future(self)
}
}
public extension Dictionary {
func toFuture() -> Future<[Key:Value]> {
return Future(self)
}
}
public extension Set {
func toFuture() -> Future<Set<Element>> {
return Future(self)
}
}
public extension IndexPath {
func toFuture() -> Future<IndexPath> {
return Future(self)
}
}
public extension IndexSet {
func toFuture() -> Future<IndexSet> {
return Future(self)
}
}
public extension NSCountedSet {
func toFuture() -> Future<NSCountedSet> {
return Future(self)
}
}
public extension NSOrderedSet {
func toFuture() -> Future<NSOrderedSet> {
return Future(self)
}
}
public extension NSMutableOrderedSet {
func toFuture() -> Future<NSMutableOrderedSet> {
return Future(self)
}
}
public extension NSPurgeableData {
func toFuture() -> Future<NSPurgeableData> {
return Future(self)
}
}
public extension NSPointerArray {
func toFuture() -> Future<NSPointerArray> {
return Future(self)
}
}
public extension NSNull {
func toFuture() -> Future<NSNull> {
return Future(self)
}
}
// MARK: Strings and Text
public extension String {
func toFuture() -> Future<String> {
return Future(self)
}
}
public extension NSAttributedString {
func toFuture() -> Future<NSAttributedString> {
return Future(self)
}
}
public extension NSMutableAttributedString {
func toFuture() -> Future<NSMutableAttributedString> {
return Future(self)
}
}
public extension CharacterSet {
func toFuture() -> Future<CharacterSet> {
return Future(self)
}
}
// ------------ Number, Data and Basic Values ------------ //
// MARK: Numbers
public extension Bool {
func toFuture() -> Future<Bool> {
return Future(self)
}
}
public extension UInt {
func toFuture() -> Future<UInt> {
return Future(self)
}
}
public extension Int {
func toFuture() -> Future<Int> {
return Future(self)
}
}
public extension Decimal {
func toFuture() -> Future<Decimal> {
return Future(self)
}
}
public extension Float {
func toFuture() -> Future<Float> {
return Future(self)
}
}
public extension Double {
func toFuture() -> Future<Double> {
return Future(self)
}
}
public extension NumberFormatter {
func toFuture() -> Future<NumberFormatter> {
return Future(self)
}
}
// MARK: Binary Data
public extension Data {
func toFuture() -> Future<Data> {
return Future(self)
}
}
// MARK: URLs
public extension URL {
func toFuture() -> Future<URL> {
return Future(self)
}
}
public extension URLComponents {
func toFuture() -> Future<URLComponents> {
return Future(self)
}
}
public extension URLQueryItem {
func toFuture() -> Future<URLQueryItem> {
return Future(self)
}
}
// MARK: Unique Identifiers
public extension UUID {
func toFuture() -> Future<UUID> {
return Future(self)
}
}
// MARK: Geometry
public extension CGFloat {
func toFuture() -> Future<CGFloat> {
return Future(self)
}
}
public extension CGAffineTransform {
func toFuture() -> Future<CGAffineTransform> {
return Future(self)
}
}
// MARK: Ranges
public extension NSRange {
func toFuture() -> Future<NSRange> {
return Future(self)
}
}
// ------------ Dates and Times ------------ //
// MARK: Dates
public extension Date {
func toFuture() -> Future<Date> {
return Future(self)
}
}
@available(iOS 10.0, *)
public extension DateInterval {
func toFuture() -> Future<DateInterval> {
return Future(self)
}
}
public extension DateComponents {
func toFuture() -> Future<DateComponents> {
return Future(self)
}
}
public extension Calendar {
func toFuture() -> Future<Calendar> {
return Future(self)
}
}
public extension TimeZone {
func toFuture() -> Future<TimeZone> {
return Future(self)
}
}
// MARK: Date Formatting
public extension DateFormatter {
func toFuture() -> Future<DateFormatter> {
return Future(self)
}
}
public extension DateComponentsFormatter {
func toFuture() -> Future<DateComponentsFormatter> {
return Future(self)
}
}
public extension DateIntervalFormatter {
func toFuture() -> Future<DateIntervalFormatter> {
return Future(self)
}
}
@available(iOS 10.0, *)
public extension ISO8601DateFormatter {
func toFuture() -> Future<ISO8601DateFormatter> {
return Future(self)
}
}
// MARK: Locale
public extension Locale {
func toFuture() -> Future<Locale> {
return Future(self)
}
}
// ------------ Filtering and Sorting ------------ //
// MARK: Filtering
public extension NSPredicate {
func toFuture() -> Future<NSPredicate> {
return Future(self)
}
}
// MARK: Sorting
public extension NSSortDescriptor {
func toFuture() -> Future<NSSortDescriptor> {
return Future(self)
}
}
| 19.173203 | 75 | 0.627237 |
fe5cf10c7f8db1ec7e840c5a4617dc7a84561c08 | 24,103 | import Prelude
// MARK: - Graph Response
public struct GraphResponse<T: Decodable>: Decodable {
let data: T
}
public struct GraphResponseErrorEnvelope: Decodable {
let errors: [GraphResponseError]?
}
// MARK: - Base Query Types
extension Never: CustomStringConvertible {
public var description: String {
fatalError()
}
}
public protocol QueryType: CustomStringConvertible, Hashable {}
public enum Connection<Q: QueryType> {
case pageInfo(NonEmptySet<PageInfo>)
case edges(NonEmptySet<Edges<Q>>)
case nodes(NonEmptySet<Q>)
case totalCount
}
public func == <Q: QueryType>(lhs: Q, rhs: Q) -> Bool {
return lhs.hashValue == rhs.hashValue
}
public func join<S: Sequence>(_ args: S, _ separator: String = " ") -> String
where S.Iterator.Element: QueryType {
return args.map { $0.description }.sorted().joined(separator: separator)
}
public func join<Q: QueryType>(_ nodes: NonEmptySet<Q>, _: String = " ") -> String {
return join(Array(nodes))
}
public func decodeBase64(_ input: String) -> String? {
return Data(base64Encoded: input)
.flatMap { String(data: $0, encoding: .utf8) }
}
public func decompose(id: String) -> Int? {
return decodeBase64(id)
.flatMap { id -> Int? in
let pair = id.split(separator: "-", maxSplits: 1)
return pair.last.flatMap { Int($0) }
}
}
public func encodeToBase64(_ input: String) -> String {
return Data(input.utf8).base64EncodedString()
}
public struct RelayId: Decodable {
let id: String
}
extension RelayId: ExpressibleByStringLiteral {
public init(unicodeScalarLiteral value: String) {
self.init(id: value)
}
public init(extendedGraphemeClusterLiteral value: String) {
self.init(id: value)
}
public init(stringLiteral value: String) {
self.init(id: value)
}
}
public enum QueryArg<T: CustomStringConvertible> {
case after(String)
case before(String)
case first(Int)
case last(Int)
case arg(T)
}
public enum EdgesContainerBody<Q: QueryType> {
case pageInfo(NonEmptySet<PageInfo>)
case edges(NonEmptySet<Edges<Q>>)
}
public enum PageInfo: String {
case endCursor
case hasNextPage
case hasPreviousPage
case startCursor
}
public enum Edges<Q: QueryType> {
case cursor
case node(NonEmptySet<Q>)
}
public enum Nodes<Q: QueryType> {
case nodes(NonEmptySet<Q>)
}
public struct GraphResponseError: Decodable {
public let message: String
}
public enum GraphError: Error {
case invalidInput
case invalidJson(responseString: String?)
case requestError(Error, URLResponse?)
case emptyResponse(URLResponse?)
case decodeError(GraphResponseError)
case jsonDecodingError(responseString: String?, error: Error?)
}
public enum Query {
case backing(id: String, NonEmptySet<Backing>)
case category(id: String, NonEmptySet<Category>)
case comment(id: String, NonEmptySet<Comment>)
case post(id: String, NonEmptySet<Project>)
case project(slug: String, NonEmptySet<Project>)
case rootCategories(NonEmptySet<Category>)
case user(NonEmptySet<User>)
public enum Category {
public enum ProjectsConnection {
public enum Argument {
case state(Project.State)
}
}
case analyticsName
case id
case name
case parentId
case parentCategory
case projects(Set<QueryArg<ProjectsConnection.Argument>>, NonEmptySet<Connection<Project>>)
case slug
indirect case subcategories(Set<QueryArg<Never>>, NonEmptySet<Connection<Category>>)
case totalProjectCount
case url
}
public indirect enum Comment {
case authorBadges
case author(NonEmptySet<Author>)
case id
case parentId
case body
case createdAt
case deleted
case replies(Set<QueryArg<Never>>, NonEmptySet<Connection<Comment>>)
public enum Author {
case id
case name
case imageURL(width: Int)
case isCreator
}
public enum CommentReplyCount: String {
case totalCount
}
}
public enum Conversation {
case id
}
public enum Location: String {
case country
case countryName
case displayableName
case id
case name
}
public enum NewsletterSubscriptions: String {
case alumniNewsletter
case artsCultureNewsletter
case filmNewsletter
case gamesNewsletter
case happeningNewsletter
case inventNewsletter
case promoNewsletter
case publishingNewsletter
case weeklyNewsletter
case musicNewsletter
}
public enum Notifications: String {
case email
case mobile
case topic
}
public indirect enum Project {
case actions(NonEmptySet<Actions>)
case addOns(Set<QueryArg<Never>>, NonEmptySet<Connection<Reward>>)
case backersCount
case backing(NonEmptySet<Backing>)
case category(NonEmptySet<Category>)
case comments(Set<QueryArg<Never>>, NonEmptySet<Connection<Comment>>)
case country(NonEmptySet<Country>)
case creator(NonEmptySet<User>)
case currency
case deadlineAt
case description
case finalCollectionDate
case fxRate
case goal(NonEmptySet<Money>)
case id
case image(NonEmptySet<Photo>)
case isProjectWeLove
case launchedAt
case location(NonEmptySet<Location>)
case name
case pid
case pledged(NonEmptySet<Money>)
case slug
case state
case stateChangedAt
case updates(Set<QueryArg<Never>>, NonEmptySet<Connection<Project.Update>>)
case url
case usdExchangeRate
public enum Actions: String {
case displayConvertAmount
}
// TODO: This should be reconciled with the global-scope Category
public indirect enum Category {
case analyticsName
case id
case name
case parentCategory(NonEmptySet<Category>)
}
public enum Country: String {
case code
case name
}
public enum State: String {
case failed = "FAILED"
case live = "LIVE"
case successful = "SUCCESSFUL"
}
public enum Photo {
case id
case url(width: Int)
}
public enum Update {
indirect case author(NonEmptySet<User>)
case id
case publishedAt
case title
}
}
public enum Reward {
public enum ShippingRulesExpandedConnection {
public enum Argument {
case locationId(String)
}
}
case amount(NonEmptySet<Money>)
case backersCount
case convertedAmount(NonEmptySet<Money>)
case description
case displayName
case endsAt
case estimatedDeliveryOn
case id
case isMaxPledge
case items(Set<QueryArg<Never>>, NonEmptySet<Connection<Item>>)
case limit
case limitPerBacker
case name
case remainingQuantity
case shippingPreference
case shippingRules(NonEmptySet<ShippingRule>)
case shippingRulesExpanded(
Set<QueryArg<ShippingRulesExpandedConnection.Argument>>,
NonEmptySet<Connection<ShippingRule>>
)
case startsAt
public enum Item: String {
case id
case name
}
}
public enum Backing {
case addOns(Set<QueryArg<Never>>, NonEmptySet<Connection<Reward>>)
case amount(NonEmptySet<Money>)
case backer(NonEmptySet<User>)
case backerCompleted
case bankAccount(NonEmptySet<BankAccount>)
case bonusAmount(NonEmptySet<Money>)
case cancelable
case creditCard(NonEmptySet<CreditCard>)
case errorReason
case id
case location(NonEmptySet<Location>)
case pledgedOn
case project(NonEmptySet<Project>)
case reward(NonEmptySet<Reward>)
case sequence
case shippingAmount(NonEmptySet<Money>)
case status
}
public indirect enum User {
case backedProjects(Set<QueryArg<Never>>, NonEmptySet<Connection<Project>>)
case backings(status: String, Set<QueryArg<Never>>, NonEmptySet<Connection<Backing>>)
case backingsCount
case biography
case chosenCurrency
case conversations(Set<QueryArg<Never>>, NonEmptySet<Connection<Conversation>>)
case createdProjects(Set<QueryArg<Never>>, NonEmptySet<Connection<Project>>)
case drop
case email
case followers(Set<QueryArg<Never>>, NonEmptySet<Connection<User>>)
case following(Set<QueryArg<Never>>, NonEmptySet<Connection<User>>)
case hasPassword
case hasUnreadMessages
case id
case image(alias: String, width: Int)
case imageUrl(alias: String, blur: Bool, width: Int)
case isAppleConnected
case isEmailDeliverable
case isEmailVerified
case isFollowing
case isSocializing
case launchedProjects(NonEmptySet<LaunchedProjects>)
case location(NonEmptySet<Location>)
case membershipProjects(Set<QueryArg<Never>>, NonEmptySet<Connection<Project>>)
case name
case needsFreshFacebookToken
case newletterSubscriptions(NonEmptySet<NewsletterSubscriptions>)
case notifications(NonEmptySet<Notifications>)
case optedOutOfRecommendations
case showPublicProfile
case savedProjects(Set<QueryArg<Never>>, NonEmptySet<Connection<Project>>)
case storedCards(Set<QueryArg<Never>>, NonEmptySet<Connection<CreditCard>>)
case slug
case uid
case url
case userId
public enum LaunchedProjects {
case totalCount
}
}
public enum CreditCard: String {
case expirationDate
case id
case lastFour
case paymentType
case state
case type
}
public enum BankAccount: String {
case bankName
case id
case lastFour
}
public enum Money: String {
case amount
case currency
case symbol
}
public enum ShippingRule {
case cost(NonEmptySet<Money>)
case id
case location(NonEmptySet<Location>)
}
}
extension Query {
public static func build(_ queries: NonEmptySet<Query>) -> String {
return "{ \(join(queries)) }"
}
}
extension Query: QueryType {
public var description: String {
switch self {
case let .backing(id, fields):
return "backing(id: \"\(id)\") { \(join(fields)) }"
case let .category(id, fields):
return "node(id: \"\(id)\") { ... on Category { \(join(fields)) } }"
case let .comment(id: id, fields):
return "comment: node(id: \"\(id)\") { ... on Comment { \(join(fields)) } }"
case let .post(id, fields):
return "post(id: \"\(id)\") { ... on FreeformPost { \(join(fields)) } }"
case let .project(slug, fields):
return "project(slug: \"\(slug)\") { \(join(fields)) }"
case let .rootCategories(fields):
return "rootCategories { \(join(fields)) }"
case let .user(fields):
return "me { \(join(fields)) }"
}
}
}
extension QueryArg: QueryType {
public var description: String {
switch self {
case let .after(cursor):
return "after: \"\(cursor)\""
case let .before(cursor):
return "before: \"\(cursor)\""
case let .first(count):
return "first: \(count)"
case let .last(count):
return "last: \(count)"
case let .arg(arg):
return arg.description
}
}
}
extension EdgesContainerBody: QueryType {
public var description: String {
switch self {
case let .edges(fields):
return "edges { \(join(fields)) }"
case let .pageInfo(pageInfo):
return "pageInfo { \(join(pageInfo)) }"
}
}
}
extension Edges: QueryType {
public var description: String {
switch self {
case .cursor: return "cursor"
case let .node(fields): return "node { \(join(fields)) }"
}
}
}
extension Nodes: QueryType {
public var description: String {
switch self {
case let .nodes(fields):
return "nodes { \(join(fields)) }"
}
}
}
extension PageInfo: QueryType {
public var description: String {
return rawValue
}
public static var all: NonEmptySet<PageInfo> {
return .endCursor +| [
.hasNextPage,
.hasPreviousPage,
.startCursor
]
}
}
extension Connection: QueryType {
public var description: String {
switch self {
case let .nodes(fields): return "nodes { \(join(fields)) }"
case let .pageInfo(pageInfo): return "pageInfo { \(join(pageInfo)) }"
case let .edges(fields): return "edges { \(join(fields)) }"
case .totalCount: return "totalCount"
}
}
}
// MARK: - Category
extension Query.Category: QueryType {
public var description: String {
switch self {
case .analyticsName: return "analyticsName"
case .id: return "id"
case .name: return "name"
case .parentCategory: return "parentCategory { analyticsName id name }"
case .parentId: return "parentId"
case let .projects(args, fields): return "projects" + connection(args, fields)
case .slug: return "slug"
case let .subcategories(args, fields): return "subcategories" + connection(args, fields)
case .totalProjectCount: return "totalProjectCount"
case .url: return "url"
}
}
}
extension Query.Category.ProjectsConnection.Argument: CustomStringConvertible {
public var description: String {
switch self {
case let .state(state): return "state: \(state.rawValue)"
}
}
}
// MARK: - Comment
extension Query.Comment: QueryType {
public var description: String {
switch self {
case .id: return "id"
case .authorBadges: return "authorBadges"
case .parentId: return "parentId"
case let .author(fields): return "author { \(join(fields)) }"
case .body: return "body"
case let .replies(args, fields): return "replies\(connection(args, fields))"
case .createdAt: return "createdAt"
case .deleted: return "deleted"
}
}
}
extension Query.Comment.Author: QueryType {
public var description: String {
switch self {
case .id: return "id"
case .name: return "name"
case .isCreator: return "isCreator"
case let .imageURL(width): return "imageUrl(width: \(width))"
}
}
}
extension Query.Comment.CommentReplyCount: QueryType {
public var description: String {
return self.rawValue
}
}
// MARK: - Project
extension Query.Project: QueryType {
public var description: String {
switch self {
case let .actions(fields): return "actions { \(join(fields)) }"
case let .addOns(args, fields): return "addOns\(connection(args, fields))"
case let .backing(fields): return "backing { \(join(fields)) }"
case .backersCount: return "backersCount"
case let .category(fields): return "category { \(join(fields)) }"
case let .comments(args, fields): return "comments\(connection(args, fields))"
case let .country(fields): return "country { \(join(fields)) }"
case let .creator(fields): return "creator { \(join(fields)) }"
case .currency: return "currency"
case .deadlineAt: return "deadlineAt"
case .description: return "description"
case .finalCollectionDate: return "finalCollectionDate"
case .fxRate: return "fxRate"
case let .goal(fields): return "goal { \(join(fields)) }"
case .id: return "id"
case .isProjectWeLove: return "isProjectWeLove"
case let .image(fields): return "image { \(join(fields)) }"
case .launchedAt: return "launchedAt"
case let .location(fields): return "location { \(join(fields)) }"
case .name: return "name"
case .pid: return "pid"
case let .pledged(fields): return "pledged { \(join(fields)) }"
case .slug: return "slug"
case .state: return "state"
case .stateChangedAt: return "stateChangedAt"
case let .updates(args, fields): return "updates\(connection(args, fields))"
case .url: return "url"
case .usdExchangeRate: return "usdExchangeRate"
}
}
}
// MARK: - Project.Category
extension Query.Project.Category: QueryType {
public var description: String {
switch self {
case .analyticsName: return "analyticsName"
case .id: return "id"
case .name: return "name"
case let .parentCategory(fields): return "parentCategory { \(join(fields)) }"
}
}
}
// MARK: - Project.Country
extension Query.Project.Country: QueryType {
public var description: String {
return self.rawValue
}
}
// MARK: - Project.Photo
extension Query.Project.Photo: QueryType {
public var description: String {
switch self {
case .id: return "id"
case let .url(width): return "url(width: \(width))"
}
}
}
// MARK: - Project.Actions
extension Query.Project.Actions: QueryType {
public var description: String {
return self.rawValue
}
}
// MARK: - Update
extension Query.Project.Update: QueryType {
public var description: String {
switch self {
case let .author(fields): return "author { \(join(fields)) }"
case .id: return "id"
case .publishedAt: return "publishedAt"
case .title: return "title"
}
}
}
// MARK: - User
extension Query.User: QueryType {
public var description: String {
switch self {
case let .backings(status, args, fields):
return "backings(status: \(status))\(connection(args, fields))"
case .backingsCount: return "backingsCount"
case .biography: return "biography"
case let .backedProjects(args, fields): return "backedProjects\(connection(args, fields))"
case let .conversations(args, fields): return "conversations\(connection(args, fields))"
case .chosenCurrency: return "chosenCurrency"
case let .createdProjects(args, fields): return "createdProjects\(connection(args, fields))"
case .drop: return "drop"
case .email: return "email"
case let .followers(args, fields): return "followers\(connection(args, fields))"
case let .following(args, fields): return "following\(connection(args, fields))"
case .hasPassword: return "hasPassword"
case .hasUnreadMessages: return "hasUnreadMessages"
case .id: return "id"
case let .image(alias, width): return "\(alias): imageUrl(width: \(width))"
case let .imageUrl(alias, blur, width): return "\(alias): imageUrl(blur: \(blur), width: \(width))"
case .isAppleConnected: return "isAppleConnected"
case .isEmailDeliverable: return "isDeliverable"
case .isEmailVerified: return "isEmailVerified"
case .isFollowing: return "isFollowing"
case .isSocializing: return "isSocializing"
case let .launchedProjects(fields): return "launchedProjects { \(join(fields)) }"
case let .location(fields): return "location { \(join(fields)) }"
case let .membershipProjects(args, fields): return "membershipProjects\(connection(args, fields))"
case .name: return "name"
case .needsFreshFacebookToken: return "needsFreshFacebookToken"
case let .newletterSubscriptions(fields): return "newslettersSubscriptions { \(join(fields)) }"
case let .notifications(fields): return "notifications { \(join(fields)) }"
case .optedOutOfRecommendations: return "optedOutOfRecommendations"
case let .savedProjects(args, fields): return "savedProjects\(connection(args, fields))"
case .showPublicProfile: return "showPublicProfile"
case let .storedCards(args, fields): return "storedCards\(connection(args, fields))"
case .slug: return "slug"
case .uid: return "uid"
case .url: return "url"
case .userId: return "uid"
}
}
}
extension Query.CreditCard: QueryType {
public var description: String {
return self.rawValue
}
}
// swiftformat:disable wrap
extension Query.Backing: QueryType {
public var description: String {
switch self {
case let .addOns(args, fields): return "addOns\(connection(args, fields))"
case let .amount(fields): return "amount { \(join(fields)) }"
case let .backer(fields): return "backer { \(join(fields)) }"
case .backerCompleted: return "backerCompleted"
case let .bankAccount(fields): return "bankAccount: paymentSource { ... on BankAccount { \(join(fields)) } }"
case let .bonusAmount(fields): return "bonusAmount { \(join(fields)) }"
case .cancelable: return "cancelable"
case let .creditCard(fields): return "creditCard: paymentSource { ... on CreditCard { \(join(fields)) } }"
case .errorReason: return "errorReason"
case .id: return "id"
case let .location(fields): return "location { \(join(fields)) }"
case .pledgedOn: return "pledgedOn"
case let .project(fields): return "project { \(join(fields)) }"
case let .reward(fields): return "reward { \(join(fields)) }"
case .sequence: return "sequence"
case let .shippingAmount(fields): return "shippingAmount { \(join(fields)) }"
case .status: return "status"
}
}
}
// swiftformat:enable wrap
extension Query.BankAccount: QueryType {
public var description: String {
return self.rawValue
}
}
extension Query.ShippingRule: QueryType {
public var description: String {
switch self {
case let .cost(fields): return "cost { \(join(fields)) }"
case .id: return "id"
case let .location(fields): return "location { \(join(fields)) }"
}
}
}
extension Query.Reward: QueryType {
public var description: String {
switch self {
case let .amount(fields): return "amount { \(join(fields)) }"
case .backersCount: return "backersCount"
case let .convertedAmount(fields): return "convertedAmount { \(join(fields)) }"
case .description: return "description"
case .displayName: return "displayName"
case .endsAt: return "endsAt"
case .estimatedDeliveryOn: return "estimatedDeliveryOn"
case .id: return "id"
case .isMaxPledge: return "isMaxPledge"
case let .items(args, fields): return "items" + connection(args, fields)
case .limit: return "limit"
case .limitPerBacker: return "limitPerBacker"
case .name: return "name"
case .remainingQuantity: return "remainingQuantity"
case .shippingPreference: return "shippingPreference"
case let .shippingRules(fields): return "shippingRules { \(join(fields)) }"
case let .shippingRulesExpanded(args, fields): return "shippingRulesExpanded" + connection(args, fields)
case .startsAt: return "startsAt"
}
}
}
extension Query.Reward.Item: QueryType {
public var description: String {
return self.rawValue
}
}
extension Query.Reward.ShippingRulesExpandedConnection.Argument: CustomStringConvertible {
public var description: String {
switch self {
case let .locationId(id): return "forLocation: \"\(id)\""
}
}
}
extension Query.User.LaunchedProjects: QueryType {
public var description: String {
switch self {
case .totalCount: return "totalCount"
}
}
}
// MARK: - NewsletterSubscriptions
extension Query.NewsletterSubscriptions: QueryType {
public var description: String {
return self.rawValue
}
}
// MARK: - Notifications
extension Query.Notifications: QueryType {
public var description: String {
return self.rawValue
}
}
// MARK: - Location
extension Query.Location: QueryType {
public var description: String {
return self.rawValue
}
}
// MARK: - Money
extension Query.Money: QueryType {
public var description: String {
return self.rawValue
}
}
// MARK: - Conversation
extension Query.Conversation: QueryType {
public var description: String {
switch self {
case .id: return "id"
}
}
}
// MARK: - Helpers
private func connection<T, U>(_ args: Set<QueryArg<T>>, _ fields: NonEmptySet<Connection<U>>) -> String {
return "\(_args(args)) { \(join(fields)) }"
}
private func _args<T>(_ args: Set<QueryArg<T>>) -> String {
return !args.isEmpty ? "(\(join(args)))" : ""
}
// MARK: - Hashable
extension QueryType {
public func hash(into hasher: inout Hasher) {
hasher.combine(self.description)
}
}
extension Query.CreditCard {
public func hash(into hasher: inout Hasher) {
hasher.combine(self.description)
}
}
extension Query.Location {
public func hash(into hasher: inout Hasher) {
hasher.combine(self.description)
}
}
extension Query.NewsletterSubscriptions {
public func hash(into hasher: inout Hasher) {
hasher.combine(self.description)
}
}
extension PageInfo {
public func hash(into hasher: inout Hasher) {
hasher.combine(self.description)
}
}
extension Query.Notifications {
public func hash(into hasher: inout Hasher) {
hasher.combine(self.description)
}
}
// MARK: - Schema Constants
public extension Query {
static let defaultPaginationCount: Int = 25
static let repliesPaginationCount: Int = 7
}
| 27.389773 | 114 | 0.684853 |
1e5e3107578b35ab12a2d00f022b638419c26a01 | 6,883 | //===----------------------------------------------------------------------===//
//
// This source file is part of the RediStack open source project
//
// Copyright (c) 2020 RediStack project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of RediStack project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIO
import Logging
@testable import RediStack
import RediStackTestUtils
import XCTest
final class RedisConnectionPoolTests: RediStackConnectionPoolIntegrationTestCase {
func test_basicPooledOperation() throws {
// We're going to insert a bunch of elements into a set, and then when all is done confirm that every
// element exists.
let operations = (0..<50).map { number in
self.pool.send(.sadd([number], to: #function))
}
let results = try EventLoopFuture<Int>.whenAllSucceed(operations, on: self.eventLoopGroup.next()).wait()
XCTAssertEqual(results, Array(repeating: 1, count: 50))
let whatRedisThinks = try self.pool
.send(.smembers(of: #function))
.flatMapThrowing { result in try result.map { try $0.map(to: Int.self) } }
.wait()
XCTAssertEqual(whatRedisThinks.compactMap { $0 }.sorted(), Array(0..<50))
}
func test_closedPoolDoesNothing() throws {
self.pool.close()
XCTAssertThrowsError(try self.pool.send(.incr(#function)).wait()) { error in
XCTAssertEqual(error as? RedisConnectionPoolError, .poolClosed)
}
}
func test_nilConnectionRetryTimeoutStillWorks() throws {
let pool = try self.makeNewPool(connectionRetryTimeout: nil)
defer { pool.close() }
XCTAssertNoThrow(try pool.get(#function).wait())
}
func test_noConnectionAttemptsUntilAddressesArePresent() throws {
// Note the config here: we have no initial addresses, the connecton backoff delay is 10 seconds, and the retry timeout is only 5 seconds.
// The effect of this config is that if we fail a connection attempt, we'll fail it forever.
let pool = try self.makeNewPool(initialAddresses: [], initialConnectionBackoffDelay: .seconds(10), connectionRetryTimeout: .seconds(5), minimumConnectionCount: 0)
defer { pool.close() }
// As above we're gonna try to insert a bunch of elements into a set. This time,
// the pool has no addresses yet. We expect that when we add an address later everything will work nicely.
// We do fewer here.
let operations = (0..<10).map { number in
pool.send(.sadd([number], to: #function))
}
// Now that we've kicked those off, let's hand over a new address.
try pool.updateConnectionAddresses([SocketAddress.makeAddressResolvingHost(self.redisHostname, port: self.redisPort)])
// We should get the results.
let results = try EventLoopFuture<Int>.whenAllSucceed(operations, on: self.eventLoopGroup.next()).wait()
XCTAssertEqual(results, Array(repeating: 1, count: 10))
}
func testDelayedConnectionsFailOnClose() throws {
// Note the config here: we have no initial addresses, the connecton backoff delay is 10 seconds, and the retry timeout is only 5 seconds.
// The effect of this config is that if we fail a connection attempt, we'll fail it forever.
let pool = try self.makeNewPool(initialAddresses: [], initialConnectionBackoffDelay: .seconds(10), connectionRetryTimeout: .seconds(5), minimumConnectionCount: 0)
defer { pool.close() }
// As above we're gonna try to insert a bunch of elements into a set. This time,
// the pool has no addresses yet. We expect that when we add an address later everything will work nicely.
// We do fewer here.
let operations = (0..<10).map { number in
pool.send(.sadd([number], to: #function))
}
// Now that we've kicked those off, let's close.
pool.close()
let results = try EventLoopFuture<Int>.whenAllComplete(operations, on: self.eventLoopGroup.next()).wait()
for result in results {
switch result {
case .success:
XCTFail("Request succeeded")
case .failure(let error) where error as? RedisConnectionPoolError == .poolClosed:
() // Pass
case .failure(let error):
XCTFail("Unexpected failure: \(error)")
}
}
}
}
// MARK: Leasing a connection
extension RedisConnectionPoolTests {
func test_borrowedConnectionStillReturnsOnError() throws {
enum TestError: Error { case expected }
let maxConnectionCount = 4
let pool = try self.makeNewPool(minimumConnectionCount: maxConnectionCount)
defer { pool.close() }
_ = try pool.ping().wait()
let promise = pool.eventLoop.makePromise(of: Void.self)
XCTAssertEqual(pool.availableConnectionCount, maxConnectionCount)
defer { XCTAssertEqual(pool.availableConnectionCount, maxConnectionCount) }
let future = pool.leaseConnection { _ in promise.futureResult }
promise.fail(TestError.expected)
XCTAssertThrowsError(try future.wait()) {
XCTAssertTrue($0 is TestError)
}
}
func test_borrowedConnectionClosureHasExclusiveAccess() throws {
let maxConnectionCount = 4
let pool = try self.makeNewPool(minimumConnectionCount: maxConnectionCount)
defer { pool.close() }
// populate the connection pool
_ = try pool.ping().wait()
// assert that we have the max number of connections available,
XCTAssertEqual(pool.availableConnectionCount, maxConnectionCount)
// borrow a connection, asserting that we've taken the connection out of the pool while we do "something" with it
// and then assert afterwards that it's back in the pool
let promises: [EventLoopPromise<Void>] = [pool.eventLoop.makePromise(), pool.eventLoop.makePromise()]
let futures = promises.indices
.map { index in
return pool
.leaseConnection { connection -> EventLoopFuture<Void> in
XCTAssertTrue(pool.availableConnectionCount < maxConnectionCount)
return promises[index].futureResult
}
}
promises.forEach { $0.succeed(()) }
_ = try EventLoopFuture<Void>
.whenAllSucceed(futures, on: pool.eventLoop)
.always { _ in
XCTAssertEqual(pool.availableConnectionCount, maxConnectionCount)
}
.wait()
}
}
| 43.563291 | 170 | 0.634171 |
56f10251ec28c978b6d967498b6827f226a5d90d | 1,064 | import Foundation
struct Device: Decodable {
var id: String
var initialInterestSet: Set<String>?
private static let userDefaults = UserDefaults(suiteName: Constants.UserDefaults.suiteName)
static func persist(_ deviceId: String) {
userDefaults?.set(deviceId, forKey: Constants.UserDefaults.deviceId)
}
static func delete() {
userDefaults?.removeObject(forKey: Constants.UserDefaults.deviceId)
}
static func persistAPNsToken(token: String) {
userDefaults?.set(token, forKey: Constants.UserDefaults.deviceAPNsToken)
}
static func deleteAPNsToken() {
userDefaults?.removeObject(forKey: Constants.UserDefaults.deviceAPNsToken)
}
static func getDeviceId() -> String? {
return userDefaults?.string(forKey: Constants.UserDefaults.deviceId)
}
static func getAPNsToken() -> String? {
return userDefaults?.string(forKey: Constants.UserDefaults.deviceAPNsToken)
}
static func idAlreadyPresent() -> Bool {
return self.getDeviceId() != nil
}
}
| 28.756757 | 95 | 0.701128 |
03a8f9e5e8b3fb832b4c272b9bc9e43dde795573 | 3,087 | //
// UIViewExtension.swift
// akb48mail_ios
//
// Created by DUONG VAN HOP on 2017/06/01.
// Copyright © 2017年 DUONG VANHOP. All rights reserved.
//
import UIKit
extension UIView {
var interactionEnabled: Bool {
return alpha >= 1 && isHidden == false && isUserInteractionEnabled
}
// exp: view.roundedCorners([.TopRight, .TopLeft], radius: 10)
func roundedCorners(_ corners: UIRectCorner, radius: CGFloat) {
let maskLayer = CAShapeLayer()
let size = CGSize(width: radius, height: radius)
maskLayer.frame = bounds
maskLayer.path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: size).cgPath
layer.mask = maskLayer
}
func createImage() -> UIImage? {
UIGraphicsBeginImageContextWithOptions(bounds.size, false, 0)
guard let context = UIGraphicsGetCurrentContext() else {
log?.debug("guard")
return nil
}
context.translateBy(x: -bounds.origin.x, y: -bounds.origin.y)
layer.render(in: context)
defer {
UIGraphicsEndImageContext()
}
return UIGraphicsGetImageFromCurrentImageContext()
}
func viewFromNib() -> UIView {
let nib = UINib(nibName: self.className, bundle: nil)
guard let view = nib.instantiate(withOwner: self, options: nil).first as? UIView else {
log?.debug("guard")
return UIView()
}
return view
}
// func setConstrainEdges(_ targetView: UIView) {
// constrain(targetView, self) { targetView, view in
// targetView.edges == view.edges
// }
// }
//
// func addConstrainEdges(_ view: UIView) {
// addSubview(view)
// constrain(view, self) { view, superview in
// view.edges == superview.edges
// }
// }
//
// func insertConstrainEdges(_ view: UIView, atIndex index: Int) {
// insertSubview(view, at: index)
// constrain(view, self) { view, superview in
// view.edges == superview.edges
// }
// }
// func insertConstrainEdges(_ view: UIView, belowSubview siblingSubview: UIView) {
// insertSubview(view, belowSubview: siblingSubview)
// constrain(view, self) { view, superview in
// view.edges == superview.edges
// }
// }
}
extension UIView {
class func animateWithDuration(_ duration: TimeInterval, delay: TimeInterval, options: UIViewAnimationOptions = [], animations: @escaping () -> Void) {
animate(withDuration: duration, delay: delay, options: options, animations: animations, completion: nil)
}
class func animateWithDuration(_ duration: TimeInterval, delay: TimeInterval, usingSpringWithDamping dampingRatio: CGFloat, initialSpringVelocity velocity: CGFloat, options: UIViewAnimationOptions = [], animations: @escaping () -> Void) {
animate(withDuration: duration, delay: delay, usingSpringWithDamping: dampingRatio, initialSpringVelocity: velocity, options: options, animations: animations, completion: nil)
}
}
| 35.079545 | 242 | 0.643667 |
2fe52389a2e54e873adab5de3bc98c93b3200080 | 1,185 | import Gen
import SharedModels
extension Gen {
public var three: Gen<Three<Value>> {
zip(self, self, self).map(Three.init)
}
}
public func randomCubes(for letter: Gen<String>) -> Gen<Puzzle> {
zip(letter, letter, letter)
.map { left, right, top in
Cube(
left: .init(letter: left, side: .left),
right: .init(letter: right, side: .right),
top: .init(letter: top, side: .top)
)
}
.three
.three
.three
}
// MARK: - Letter distributions
// https://boardgamegeek.com/geeklist/182883/letter-distributions-word-games/page/1
public let isowordsLetter = Gen.frequency(
(16, .always("A")),
(4, .always("B")),
(6, .always("C")),
(8, .always("D")),
(24, .always("E")),
(4, .always("F")),
(5, .always("G")),
(5, .always("H")),
(13, .always("I")),
(2, .always("J")),
(2, .always("K")),
(7, .always("L")),
(6, .always("M")),
(13, .always("N")),
(15, .always("O")),
(4, .always("P")),
(2, .always("QU")),
(13, .always("R")),
(10, .always("S")),
(15, .always("T")),
(7, .always("U")),
(3, .always("V")),
(4, .always("W")),
(2, .always("X")),
(4, .always("Y")),
(2, .always("Z"))
)
| 21.545455 | 83 | 0.522363 |
16e5017bf503e575e6f71e1de30b40f19f6ce8f8 | 1,132 | //
// CoreDataManager.swift
// Covid-Tracker
//
// Created by Алексей Воронов on 11.04.2020.
// Copyright © 2020 Алексей Воронов. All rights reserved.
//
import Foundation
import CoreData
final class CoreDataManager {
static let shared = CoreDataManager()
private init() { }
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "Covid_Tracker")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
var managedObjectContext: NSManagedObjectContext {
return persistentContainer.viewContext
}
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| 26.325581 | 88 | 0.606007 |
692e36073bfaa48c74631b3a7644099963073cb6 | 1,371 | // Automatically generated by the Fast Binary Encoding compiler, do not modify!
// https://github.com/chronoxor/FastBinaryEncoding
// Source: protoex.fbe
// Version: 1.4.0.0
import ChronoxorFbe
// Fast Binary Encoding OrderSide final model
public class FinalModelOrderSide: FinalModel {
public var _buffer: Buffer
public var _offset: Int
// Final size
public let fbeSize: Int = 1
public init(buffer: Buffer = Buffer(), offset: Int = 0) {
_buffer = buffer
_offset = offset
}
// Get the allocation size
public func fbeAllocationSize(value: OrderSide) -> Int { fbeSize }
public func verify() -> Int {
if _buffer.offset + fbeOffset + fbeSize > _buffer.size {
return Int.max
}
return fbeSize
}
// Get the value
public func get(size: inout Size) -> OrderSide {
if _buffer.offset + fbeOffset + fbeSize > _buffer.size {
return OrderSide()
}
size.value = fbeSize
return OrderSide(value: readByte(offset: fbeOffset))
}
// Set the value
public func set(value: OrderSide) throws -> Int {
if _buffer.offset + fbeOffset + fbeSize > _buffer.size {
assertionFailure("Model is broken!")
return 0
}
write(offset: fbeOffset, value: value.raw)
return fbeSize
}
}
| 25.388889 | 79 | 0.620715 |
01b42e1f237e23b98bddbbaf46f19e13c45283f0 | 884 | /**
* Question Link: https://leetcode.com/problems/subsets-ii/
* Primary idea: Classic Depth-first Search, avoid duplicates by adopting the first occurrence
*
* Time Complexity: O(n!), Space Complexity: O(n)
*
*/
class SubsetsII {
func subsetsWithDup(nums: [Int]) -> [[Int]] {
var res = [[Int]]()
var path = [Int]()
let nums = nums.sorted(by: <)
_dfs(&res, &path, nums, 0)
return res
}
private func _dfs(inout res: [[Int]], inout _ path:[Int], _ nums: [Int], _ index: Int) {
res.append(Array(path))
for i in index..<nums.count {
if i > 0 && nums[i] == nums[i - 1] && i != index {
continue
}
path.append(nums[i])
_dfs(&res, &path, nums, i + 1)
path.removeLast()
}
}
} | 26 | 94 | 0.485294 |
626e1b8cd7d40b916c52bbdaddaedfda7cb448fb | 773 | import UIKit
public struct FPNCountry: Equatable {
public var code: FPNCountryCode
public var name: String
public var phoneCode: String
var flag: String = ""
init(code: String, name: String, phoneCode: String) {
self.name = name
self.phoneCode = phoneCode
self.code = FPNCountryCode(rawValue: code)!
flag = getFlag(country: code)
}
static public func ==(lhs: FPNCountry, rhs: FPNCountry) -> Bool {
return lhs.code == rhs.code
}
func getFlag(country:String) -> String {
let base : UInt32 = 127397
var s = ""
for v in country.unicodeScalars {
s.unicodeScalars.append(UnicodeScalar(base + v.value)!)
}
return String(s)
}
}
| 25.766667 | 69 | 0.591203 |
01a2c9f0821fdd841c9d01fd751fb81c0cc8db9b | 3,737 | //
// AppDelegate.swift
// SmartRate
//
// Created by korrolion on 07/17/2017.
// Copyright (c) 2017 korrolion. All rights reserved.
//
import UIKit
import SmartRate
import StoreKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
//Configure SmartRate
SMBlocker.shared.minTimeAfterInstalled = 60 //Will not fire 60 seconds after first launch
SMBlocker.shared.minTimeAfterLaunch = 10 //Will not fire 10 seconds after launch
SMBlocker.shared.minTimeAfterFire = 60 //Will not fire 60 seconds after fire 😀
SMBlocker.shared.showRatingForEveryVersion = true //Will reset block if the app version will change
//Create triggers for SmartRate
let countTrigger = SMTriggerCounterType(notificationName: ViewController.duplicateActionNotificationName, repeatTimes: 4, uniqName: "press4TimesTrigger")
//For every trigger you can provide custom fire function, or use default
countTrigger.customFireCompletion = {
if #available(iOS 10.3, *) {
SKStoreReviewController.requestReview()
}
}
//Will fire on 4-th button press
SMTriggersStore.shared.addTrigger(countTrigger)
let chainTrigger = SMTriggerChainType(notificationNames: [
ViewController.step1NotificationName, //provide sequence of steps
ViewController.step2NotificationName,
ViewController.step3NotificationName,
],
breakNotificationName: ViewController.breakNotificationName, //You can break chain on any other action, or set nil
uniqName: "pressButtons123Trigger"
)
//Will fire after correct sequence of 3 steps. Will not fire if sequence will be broken
SMTriggersStore.shared.addTrigger(chainTrigger)
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 48.532468 | 285 | 0.723575 |
4a51b2025a5bdb6d0729da9adcd02ac1dac02207 | 941 | //
// TemporaryUtils.swift
//
//
// Created by NGUYEN CHI CONG on 4/7/17.
// Copyright © 2017 [iF] Solution Co., Ltd. All rights reserved.
//
import Foundation
import SiFUtilities
public struct TemporaryUtils {
public static func temporaryPath(fileName: String? = nil, fileExtension: String = "file") -> String {
let temp = NSTemporaryDirectory() as NSString
var fname = fileName ?? String.random(length: 10)
let dateText = Date().toString(format: "_yyyy_MM_dd_hh_mm_ss_SSSS")
fname += dateText
let name = fileExtension.isEmpty ? fname : fname + "." + fileExtension
let path = temp.appendingPathComponent(name)
return path as String
}
public static func temporaryURL(fileName: String? = nil, fileExtension: String = "") -> URL {
let path = temporaryPath(fileName: fileName, fileExtension: fileExtension)
return URL(fileURLWithPath: path)
}
}
| 33.607143 | 105 | 0.668438 |
ebc07676a236a543cc45ea3aa525f7cf56f87787 | 582 | // Copyright DApps Platform Inc. All rights reserved.
import Foundation
final class DeviceChecker: JailbreakChecker {
func isJailbroken() -> Bool {
if TARGET_IPHONE_SIMULATOR == 1 {
return false
}
let list: [String] = [
"/Applications/Cydia.app",
"/Library/MobileSubstrate/MobileSubstrate.dylib",
"/bin/bash",
"/usr/sbin/sshd",
"/etc/apt",
"/private/var/lib/apt/",
]
return !list.filter { FileManager.default.fileExists(atPath: $0) }.isEmpty
}
}
| 25.304348 | 82 | 0.561856 |
6a4652b17c70923e373d4c09948a988fb75ec6ce | 1,496 | //
// ViewController.swift
// UtilsDemo
//
// Created by ldy on 17/3/21.
// Copyright © 2017年 BJYN. All rights reserved.
//
import UIKit
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
var titles:[String] = ["Lgoin Text Field","Img title vertical button"]
var segueIDs:[String] = ["LgoinTextFieldSegueID","VerticalBtnSegueID"]
@IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
tableView.tableFooterView = UIView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK:- UITableViewDelegate,UITableViewDataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return titles.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = titles[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.performSegue(withIdentifier: segueIDs[indexPath.row], sender: self)
}
}
| 31.829787 | 99 | 0.694519 |
763ab6d8eac5a590d465fb9e5d2ad36fbeb81638 | 1,769 | //
// Copyright © 2019 Essential Developer. All rights reserved.
//
import XCTest
import MVC
import FeedFeature
extension FeedUIIntegrationTests {
func assertThat(_ sut: FeedViewController, isRendering feed: [FeedImage], file: StaticString = #file, line: UInt = #line) {
guard sut.numberOfRenderedFeedImageViews() == feed.count else {
return XCTFail("Expected \(feed.count) images, got \(sut.numberOfRenderedFeedImageViews()) instead.", file: file, line: line)
}
feed.enumerated().forEach { index, image in
assertThat(sut, hasViewConfiguredFor: image, at: index, file: file, line: line)
}
}
func assertThat(_ sut: FeedViewController, hasViewConfiguredFor image: FeedImage, at index: Int, file: StaticString = #file, line: UInt = #line) {
let view = sut.feedImageView(at: index)
guard let cell = view as? FeedImageCell else {
return XCTFail("Expected \(FeedImageCell.self) instance, got \(String(describing: view)) instead", file: file, line: line)
}
let shouldLocationBeVisible = (image.location != nil)
XCTAssertEqual(cell.isShowingLocation, shouldLocationBeVisible, "Expected `isShowingLocation` to be \(shouldLocationBeVisible) for image view at index (\(index))", file: file, line: line)
XCTAssertEqual(cell.locationText, image.location, "Expected location text to be \(String(describing: image.location)) for image view at index (\(index))", file: file, line: line)
XCTAssertEqual(cell.descriptionText, image.description, "Expected description text to be \(String(describing: image.description)) for image view at index (\(index)", file: file, line: line)
}
}
| 47.810811 | 197 | 0.674958 |
722baa30854a0efb5929b6111f211a6404c9c939 | 2,355 | // Combos benchmark
//
// Description: Generates every combination of every element in two sequences
// Source: https://gist.github.com/airspeedswift/34251f2ddb1b038c5d88
import TestsUtils
public var Combos = BenchmarkInfo(
name: "Combos",
runFunction: run_Combos,
tags: [.validation, .abstraction]
)
@inline(never)
public func run_Combos(_ N: Int) {
let firstRef = [Character("A"), Character("0")]
let lastRef = [Character("J"), Character("9")]
var combos = [[Character]]()
for _ in 1...10*N {
combos = combinations("ABCDEFGHIJ", "0123456789").map {
return [$0] + [$1]
}
if combos.first! != firstRef || combos.last! != lastRef {
break
}
}
CheckResults(combos.first! == firstRef && combos.last! == lastRef)
}
func combinations
<First: Sequence, Second: Collection>
(_ first: First, _ second: Second)
-> AnyIterator<(First.Iterator.Element, Second.Iterator.Element)> {
var first_gen = first.makeIterator()
var second_gen = second.makeIterator()
var current_first = first_gen.next()
return AnyIterator {
// check if there's more of first to consume
if let this_first = current_first {
// if so, is there more of this go-around
// of second to consume?
if let this_second = second_gen.next() {
return (this_first, this_second)
}
// if second used up, reset it
else {
// go back to the beginning of second
second_gen = second.makeIterator()
// and take the first element of it
let next_second = second_gen.next()
// was there a first element?
if let this_second = next_second {
// move on to the next element of first
current_first = first_gen.next()
// is there such an element?
if let this_first = current_first {
return (this_first, this_second)
}
// if not, we've reached the end of
// the first sequence
else {
// so we've finished
return nil
}
}
// if not, second is empty
else {
// so we need to guard against
// infinite looping in that case
return nil
}
}
}
// if not, we've reached the end of
// the first sequence
else {
// so we've finished
return nil
}
}
}
| 27.705882 | 77 | 0.601699 |
146c0df28e6a9fea2b8b067ba5246f6dfb3ffd8a | 1,572 | import Prelude
import Prelude_UIKit
import UIKit
public let projectActivityBulletSeparatorViewStyle = roundedStyle(cornerRadius: 2.0)
<> UIView.lens.backgroundColor .~ .ksr_support_400
public let projectActivityDividerViewStyle = UIView.lens.backgroundColor .~ .ksr_support_300
public let projectActivityFooterButton =
UIButton.lens.titleColor(for: .normal) .~ .ksr_create_700
<> UIButton.lens.titleLabel.font .~ UIFont.ksr_footnote(size: 12).bolded
<> UIButton.lens.titleColor(for: .highlighted) .~ .ksr_support_100
public let projectActivityFooterStackViewStyle =
UIStackView.lens.layoutMargins .~ .init(topBottom: Styles.grid(3), leftRight: Styles.grid(2))
<> UIStackView.lens.isLayoutMarginsRelativeArrangement .~ true
<> UIStackView.lens.spacing .~ Styles.grid(2)
public let projectActivityHeaderStackViewStyle =
UIStackView.lens.layoutMargins .~ .init(all: Styles.grid(2))
<> UIStackView.lens.isLayoutMarginsRelativeArrangement .~ true
<> UIStackView.lens.spacing .~ Styles.grid(1)
public let projectActivityRegularRegularLeftRight = Styles.grid(30)
public let projectActivityRegularRegularLayoutMargins: UIEdgeInsets =
.init(topBottom: Styles.grid(4), leftRight: projectActivityRegularRegularLeftRight)
// Use `.ksr_body` for font.
public let projectActivityStateChangeLabelStyle = UILabel.lens.numberOfLines .~ 0
<> UILabel.lens.textAlignment .~ .center
// Use `.ksr_title3(size: 14)` for font.
public let projectActivityTitleLabelStyle = UILabel.lens.textColor .~ .ksr_support_700
<> UILabel.lens.numberOfLines .~ 2
| 42.486486 | 95 | 0.788168 |
e8becb0d2800e56d7f203482c1d859f789f7c899 | 243 | //
// LazyView.swift
// Expenses
//
// Created by Nominalista on 17/01/2022.
//
import SwiftUI
struct LazyView<Content: View>: View {
@ViewBuilder var content: () -> Content
var body: Content {
content()
}
}
| 13.5 | 43 | 0.584362 |
919b0cffe660e3d628ddc241201229084e571d7d | 5,020 | import Vapor
import Fluent
public struct MachineController: RouteCollection {
// Register the websocket endpoint as an endpoint
public func boot(routes: RoutesBuilder) {
let machine = routes.grouped("machine")
machine.get(use: getMachines)
machine.put(use: putIngredient)
machine.webSocket(":name",
onUpgrade: register)
}
// Tells the system, a machine has a given ingredient
func putIngredient(req: Request) throws -> EventLoopFuture<HTTPStatus> {
try req.content.decode(MachineDrink.self)
.toPivot()
.save(on: req.db)
.map { .created }
}
struct MachineDrink: Decodable {
let machineID: UUID
let ingredientID: UUID
func toPivot() -> MachineDrinkPivot {
.init(machineID: machineID, ingredientID: ingredientID)
}
}
// List all machines
func getMachines(req: Request) -> EventLoopFuture<[Machine]> {
Machine.query(on: req.db)
.all()
}
// Struct to store the essentials for a websocket connection
public struct MachineProvider {
let webSocket: WebSocket
let req: Request // The request can also use request for e.g. DB
}
// Register a new machine on the system
func register(req: Request, ws: WebSocket) {
// Not entirely type safe, but get name from URL
// Name should probably be the name of the location
// or something unique to the machine
let name = req.parameters.get("name")!
// Save the machine to the Database
_ = Machine(name: name)
.save(on: req.db)
// The save function doesn't return machine, and we need the UUID later
_ = Machine.query(on: req.db)
.filter(\.$name == name) // Get the newly created machine
.first() // Get the first with the name, we don't have other parameters to base this off.
.unwrap(or: Abort(.internalServerError)) // We just created the machine, if it doesn't exist, then something wrong happened
.map { machine in
// Register the machine to memory, so we can retrieve it later and elsewhere
machines[machine.id!] = .init(webSocket: ws, req: req)
// For debug purposes, print the machine name. Also nice to know which machines are registered at runtime without needing debugger
print(machine.name)
// Set delegate as the function to handle received texts
machines[machine.id!]?.webSocket.onText(self.websocketDelegate)
// When all is good, tell the machine what's it's ID is. This is needed for some requests.
machines[machine.id!]?.webSocket.send("\(machine.id!)")
}
}
// Delegate for handling incomming messages from a machine
func websocketDelegate(ws: WebSocket, body: String) {
// Print the message - no privacy
print(body)
// If the message is a registration form, print the mail.
body.evalBody(type: User.UserContent.self) { user in
print(user.mail)
}
// Evaluate liquor which ran out.
body.evalBody(type: RanOut.self) { liquor in
let machineID = liquor.machineID
let liquorID = liquor.liqourID
// Delete the given liquor - only on the given machine, tell the machine it has been done.
// This will use the machines db,
// this has the interesting side affect, that we can have different db's for different machines.
MachineDrinkPivot.query(on: machines[machineID]!.req.db)
.filter(\.$ingredient.$id == liquorID)
.filter(\.$machine.$id == machineID)
.delete()
.map{
ws.send("Ingredient removed")
}
}
}
// The websocketDelegate doesn't have knowledge about which machine makes the call, so we make the machine tell it, itself.
struct RanOut: Decodable {
let liqourID: UUID
let machineID: UUID
}
}
// All registered machines in memory.
public var machines: [UUID: MachineController.MachineProvider] = [:]
// Extend String only for this file
private extension String {
func evalBody<T>(type: T.Type, callback: (T) -> ()) where T: Decodable
{
let decoder = JSONDecoder()
let data = self.data(using: .utf8)!
// Call callback, if body can be decoded as T.
// Interesting quirk of how decodable and throwing works,
// allows us to callback only if it can be decoded safely,
// without explicitly checking, and having long try-catch chains.
if let decoded = try? decoder.decode(type, from: data) {
callback(decoded)
}
}
}
| 39.21875 | 146 | 0.591833 |
4a2ab30bbde462171a8117cf08206c47b12ec33e | 551 | //
// StageActivity+CoreDataProperties.swift
//
//
// Created by Pakpoom on 2/24/2560 BE.
//
//
import Foundation
import CoreData
extension StageActivity {
@nonobjc public class func fetchRequest() -> NSFetchRequest<StageActivity> {
return NSFetchRequest<StageActivity>(entityName: "StageActivity");
}
@NSManaged public var activityId: String?
@NSManaged public var stage: Int16
@NSManaged public var startDate: Date?
@NSManaged public var endDate: Date?
@NSManaged public var toActivity: ActivityData?
}
| 21.192308 | 80 | 0.715064 |
ef858e63b54d3aa79e01f8cbd3e5fec2bf1ebea4 | 4,509 | //
// RSStepTreeResultTransformValueTransformer.swift
// ResearchSuiteApplicationFramework
//
// Created by James Kizer on 7/1/17.
//
// Copyright Curiosity Health Company. All rights reserved.
//
import UIKit
import ResearchKit
import Gloss
import ResearchSuiteResultsProcessor
import LS2SDK
open class RSStepTreeResultTransformValueTransformer: RSValueTransformer {
public static func supportsType(type: String) -> Bool {
return "resultTransform" == type
}
public static func generateValue(jsonObject: JSON, state: RSState, context: [String: AnyObject]) -> ValueConvertible? {
//note that we do not do a recursive search for the childID
guard let taskResult = context["taskResult"] as? ORKTaskResult,
let stepResults = taskResult.results as? [ORKStepResult],
let node = context["node"] as? RSStepTreeBranchNode,
let childID: String = "childID" <~~ jsonObject,
let transformID: String = "transformID" <~~ jsonObject,
let child = node.child(withfullyQualified: childID) as? RSStepTreeBranchNode,
let resultTransform = child.resultTransforms[transformID] else {
return nil
}
//lets create a new task result that selects only the results below child and maps the identifiers
// debugPrint(child.fullyQualifiedIdentifier)
// debugPrint(stepResults)
// let fullyQualifiedChildIdentifier = child.fullyQualifiedIdentifier
//filter
let filteredStepResults = stepResults
.filter { stepResult in
return stepResult.identifier.hasPrefix(child.fullyQualifiedIdentifier)
}
.map { (stepResult) -> ORKStepResult in
let stepResultIdentifierComponents = stepResult.identifier.components(separatedBy: ".")
// debugPrint(stepResultIdentifierComponents)
//note that the "child" here is actually a parent of the step
let childIdentifierComponents = child.fullyQualifiedIdentifier.components(separatedBy: ".")
// debugPrint(childIdentifierComponents)
let remainingComponents = stepResultIdentifierComponents.dropFirst(childIdentifierComponents.count)
// debugPrint(remainingComponents)
//stepResult.results?.forEach { debugPrint($0) }
//NOTE: This copies the nested results, the Result object that inherits from
//ORKResult may need to override the copy method. See RSEnhancedMultipleChoiceResult in RSExtensions
let newStepResult = ORKStepResult(stepIdentifier: remainingComponents.joined(separator: "."), results: stepResult.results)
//newStepResult.results?.forEach { debugPrint($0) }
return newStepResult
}
//map -> step result w/ new identifier
let filteredTaskResult = ORKTaskResult(taskIdentifier: taskResult.identifier, taskRun: taskResult.taskRunUUID, outputDirectory: nil)
filteredTaskResult.results = filteredStepResults
// debugPrint(filteredTaskResult)
let result = RSRPFrontEndService.processResult(
taskResult: filteredTaskResult,
resultTransform: resultTransform,
frontEndTransformers: RSApplicationDelegate.appDelegate.frontEndResultTransformers
)
if let convertToJSON: Bool = "convertToJSON" <~~ jsonObject,
convertToJSON {
if let convertible = result as? LS2DatapointConvertible,
let json = convertible.toDatapoint(builder: LS2ConcreteDatapoint.self)?.toJSON() {
return RSValueConvertible(value: json as AnyObject)
}
else if let encodable = result?.evaluate() as? Gloss.JSONEncodable,
let json = encodable.toJSON() {
return RSValueConvertible(value: json as AnyObject)
}
else if let encodableArray: [Gloss.JSONEncodable] = result?.evaluate() as? [Gloss.JSONEncodable] {
let jsonArray = encodableArray.compactMap({ $0.toJSON() })
return RSValueConvertible(value: jsonArray as AnyObject)
}
else {
return nil
}
}
else {
return result
}
}
}
| 42.140187 | 140 | 0.632291 |
61d68160102974b1582f1041d15ab3631cd6c4bc | 1,295 | //
// KittensViewModel.swift
// TextureExamples
//
// Created by YYKJ0048 on 2021/7/13.
//
import Foundation
import RxSwift
import RxCocoa
protocol KittensViewModelInputs {
func reloadItems()
}
protocol KittensViewModelOutputs {
var items: Driver<[CGSize]> { get }
}
protocol KittensViewModelTypes {
var inputs: KittensViewModelInputs { get }
var outputs: KittensViewModelOutputs { get }
}
class KittensViewModel: KittensViewModelInputs, KittensViewModelOutputs, KittensViewModelTypes {
init() {
let items = reloadSubject.map(filterDataSource)
// inputs
// outputs
self.items = items.asDriverOnErrorJustComplete()
}
// MARK: subjects
let reloadSubject = PublishSubject<Void>()
// MARK: inputs
func reloadItems() {
reloadSubject.onNext(())
}
// MARK: outputs
let items: Driver<[CGSize]>
var inputs: KittensViewModelInputs { self }
var outputs: KittensViewModelOutputs { self }
}
private func filterDataSource() -> [CGSize] {
var items: [CGSize] = []
for _ in 0...19 {
let width = Int(arc4random_uniform(300) + 100)
let height = Int(arc4random_uniform(350) + 100)
items.append(CGSize(width: width, height: height))
}
return items
}
| 21.229508 | 96 | 0.661776 |
e4a4123948796ccd4af015f7438237847be96e6f | 6,175 | ///
/// Various extensions to make Wlroots a bit more pleasant to use in Swift.
///
import Wlroots
// MARK: Wlroots compatibility structures
public struct float_rgba {
public var r: Float
public var g: Float
public var b: Float
public var a: Float
mutating func withPtr<Result>(_ body: (UnsafePointer<Float>) -> Result) -> Result {
withUnsafePointer(to: &self) {
$0.withMemoryRebound(to: Float.self, capacity: 4, body)
}
}
}
typealias matrix9 = (Float, Float, Float, Float, Float, Float, Float, Float, Float)
// MARK: Wlroots convenience extensions
// Swift version of `wl_container_of`
internal func wlContainer<R>(of: UnsafeMutableRawPointer, _ path: PartialKeyPath<R>) -> UnsafeMutablePointer<R> {
(of - MemoryLayout<R>.offset(of: path)!).bindMemory(to: R.self, capacity: 1)
}
internal func toString<T>(array: T) -> String {
withUnsafePointer(to: array) {
$0.withMemoryRebound(to: UInt8.self, capacity: MemoryLayout.size(ofValue: $0)) {
String(cString: $0)
}
}
}
extension wlr_box {
func contains(x: Int, y: Int) -> Bool {
self.x <= x && x < self.x + self.width && self.y <= y && y < self.y + self.height
}
func scale(_ factor: Double) -> wlr_box {
let scaledX = Double(self.x) * factor
let scaledY = Double(self.y) * factor
return wlr_box(
x: Int32(round(scaledX)),
y: Int32(round(scaledY)),
width: Int32(round(Double(self.x + self.width) * factor - scaledX)),
height: Int32(round(Double(self.y + self.height) * factor - scaledY))
)
}
}
extension UnsafeMutablePointer where Pointee == wlr_surface {
func popup(of parent: UnsafeMutablePointer<wlr_surface>) -> Bool {
if wlr_surface_is_xdg_surface(parent) {
return wlr_xdg_surface_from_wlr_surface(parent)!.pointee.popups.contains(
\wlr_xdg_popup.link,
where: { $0.pointee.parent == self }
)
} else {
return false
}
}
func subsurface(of parent: UnsafeMutablePointer<wlr_surface>) -> Bool {
#if WLROOTS13
parent.pointee.subsurfaces.contains(\wlr_subsurface.parent_link, where: { $0.pointee.surface == self })
#else
parent.pointee.subsurfaces_above.contains(
\wlr_subsurface.parent_link, where: { $0.pointee.surface == self }
) || parent.pointee.subsurfaces_below.contains(
\wlr_subsurface.parent_link, where: { $0.pointee.surface == self }
)
#endif
}
func surfaces() -> [(UnsafeMutablePointer<wlr_surface>, Int32, Int32)] {
var surfaces: [(UnsafeMutablePointer<wlr_surface>, Int32, Int32)] = []
withUnsafeMutablePointer(to: &surfaces) { (surfacesPtr) in
wlr_surface_for_each_surface(
self,
{
$3!.bindMemory(to: [(UnsafeMutablePointer < wlr_surface>, Int32, Int32)].self, capacity: 1)
.pointee
.append(($0!, $1, $2))
},
surfacesPtr
)
}
return surfaces
}
}
struct WlListIterator<T>: IteratorProtocol {
private let start: UnsafePointer<wl_list>
private var current: UnsafeMutablePointer<T>
private let path: WritableKeyPath<T, wl_list>
private var exhausted: Bool = false
init(_ start: UnsafePointer<wl_list>, _ path: WritableKeyPath<T, wl_list>) {
self.start = start
self.current = wlContainer(of: UnsafeMutableRawPointer(start.pointee.next), path)
self.path = path
}
mutating func next() -> UnsafeMutablePointer<T>? {
guard !exhausted else { return nil }
if withUnsafePointer(to: ¤t.pointee[keyPath: path], { $0 != start }) {
defer {
current = wlContainer(
of: UnsafeMutableRawPointer(current.pointee[keyPath: path].next),
path
)
}
return current
} else {
exhausted = true
return nil
}
}
}
struct WlListSequence<T>: Sequence {
private let list: UnsafeMutablePointer<wl_list>
private let path: WritableKeyPath<T, wl_list>
init(_ list: UnsafeMutablePointer<wl_list>, _ path: WritableKeyPath<T, wl_list>) {
self.list = list
self.path = path
}
func makeIterator() -> WlListIterator<T> {
return WlListIterator(list, path)
}
}
extension wl_list {
/// Returns whether the given predicate holds for some element. Doesn't mutate the list, even though the method
/// is marked as mutating.
mutating func contains<T>(_ path: WritableKeyPath<T, wl_list>, where: (UnsafeMutablePointer<T>) -> Bool) -> Bool {
var pos = wlContainer(of: UnsafeMutableRawPointer(self.next), path)
while withUnsafePointer(to: &pos.pointee[keyPath: path], { $0 != &self }) {
if `where`(pos) {
return true
}
pos = wlContainer(of: UnsafeMutableRawPointer(pos.pointee[keyPath: path].next), path)
}
return false
}
mutating func sequence<T>(_ path: WritableKeyPath<T, wl_list>) -> WlListSequence<T> {
return WlListSequence(&self, path)
}
}
extension UnsafeMutablePointer where Pointee == wlr_subsurface {
func parentToplevel() -> UnsafeMutablePointer<wlr_xdg_surface>? {
guard wlr_surface_is_xdg_surface(self.pointee.parent) else { return nil }
var xdgSurface = wlr_xdg_surface_from_wlr_surface(self.pointee.parent)
while xdgSurface != nil && xdgSurface?.pointee.role == WLR_XDG_SURFACE_ROLE_POPUP {
xdgSurface = wlr_xdg_surface_from_wlr_surface(xdgSurface?.pointee.popup.pointee.parent)
}
return xdgSurface
}
}
extension UnsafeMutablePointer where Pointee == wlr_surface {
func isXdgPopup() -> Bool {
if wlr_surface_is_xdg_surface(self) {
let xdgSurface = wlr_xdg_surface_from_wlr_surface(self)!
return xdgSurface.pointee.role == WLR_XDG_SURFACE_ROLE_POPUP
}
return false
}
}
| 33.02139 | 118 | 0.619271 |
79e3d971a87bed6aa2b2fd2284ebf969c92028f0 | 539 | //
// ArrowPattern.swift
// Arrow
//
// Created by David Williams on 12/2/20.
// Copyright © 2020 David Williams. All rights reserved.
//
import SwiftUI
class ArrowPattern : ObservableObject {
var frames: [Int32]
init(frames: [Int32]) {
self.frames = frames
}
func BulbIsLit(bulb: Int, tick: Int) -> Bool {
return self.frames[tick % self.frames.count] & (1<<bulb) != 0
}
}
/**
Arrow annimation frame to display
*/
class ArrowFrame: ObservableObject {
@Published var tick: Int = 0
}
| 18.586207 | 69 | 0.625232 |
de730c8da08890694e075f792b5d76721e630b52 | 871 | //
// Copyright © 2019 Essential Developer. All rights reserved.
//
import Combine
import EssentialFeed
import EssentialFeediOS
final class FeedLoaderPresentationAdapter: FeedViewControllerDelegate {
private let feedLoader: () -> FeedLoader.Publisher
private var cancellable: Cancellable?
var presenter: FeedPresenter?
init(feedLoader: @escaping () -> FeedLoader.Publisher) {
self.feedLoader = feedLoader
}
func didRequestFeedRefresh() {
presenter?.didStartLoadingFeed()
cancellable = feedLoader()
.dispatchOnMainQueue()
.sink(
receiveCompletion: { [weak self] completion in
switch completion {
case .finished: break
case let .failure(error):
self?.presenter?.didFinishLoadingFeed(with: error)
}
}, receiveValue: { [weak self] feed in
self?.presenter?.didFinishLoadingFeed(with: feed)
})
}
}
| 24.194444 | 71 | 0.71527 |
6a69a73c2ed53e44f34f049545aa7c7e37db2015 | 624 | //
// TabSlideManager.swift
// bold
//
// Created by Afshawn Lotfi on 2/20/18.
// Copyright © 2018 Afshawn Lotfi. All rights reserved.
//
import UIKit
class TabSlideManager:OptionSlideManager{
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
let option = selectionManager.items[indexPath.section][indexPath.row]
if let gCell = tableView.cellForRow(at: indexPath) as? GTableViewCell, let webView = self.bottomView as? TabWebView{
option.delegate?.sliderOption(didSelectCell: gCell, webView: webView)
}
}
}
| 24 | 128 | 0.668269 |
67cb6c1e2cb8422748be47e3a0068ea3a0770a0c | 3,602 | //
// LocalMessageFactory.swift
// CHPlugin
//
// Created by Haeun Chung on 23/02/2017.
// Copyright © 2017 ZOYI. All rights reserved.
//
import UIKit
struct LocalMessageFactory {
static func generate(
type: MessageType,
messages: [CHMessage] = [],
userChat: CHUserChat? = nil,
text: String? = nil) -> [CHMessage] {
switch type {
case .DateDivider:
let msgs = insertDateDividers(messages: messages)
return msgs
case .NewAlertMessage:
let msgs = insertNewMessage(messages: messages, userChat: userChat!)
return msgs
case .UserMessage:
let msg = getUserMessage(msg: text ?? "", userChat: userChat)
return messages + [msg]
case .WelcomeMessage:
if let msg = getWelcomeMessage() {
return [msg] + messages
}
return messages
default:
return messages
}
}
private static func insertDateDividers(messages: [CHMessage]) -> [CHMessage] {
var indexes: [(Int, String)] = []
var newMessages = messages
var lastDateMsg: CHMessage? = nil
var chatId = ""
for index in (0..<messages.count).reversed() {
let msg = messages[index]
if index == messages.count - 1 {
indexes.append((index, msg.readableDate))
lastDateMsg = msg
chatId = msg.chatId
} else if lastDateMsg?.isSameDate(other: msg) == false {
indexes.append((index, msg.readableDate))
lastDateMsg = msg
}
}
for element in indexes {
let createdAt = messages[element.0].createdAt
let date = Calendar.current.date(byAdding: .nanosecond, value: -100, to: createdAt)
let msg = CHMessage(
chatId:chatId,
message:element.1,
type: .DateDivider,
createdAt: date,
id: element.1)
newMessages.insert(msg, at: element.0 + 1)
}
return newMessages
}
private static func getWelcomeMessage() -> CHMessage? {
let user = mainStore.state.user
guard var block = user.getWelcomeBlock() else {
return nil
}
block.displayText = user.getWelcome(
with: CHMessageParserConfig(font: UIFont.systemFont(ofSize: 15))
)
return CHMessage(
chatId: "welcome_dummy",
blocks: [block],
type: .WelcomeMessage,
entity: botSelector(state: mainStore.state) ?? mainStore.state.channel,
id: "welcome_dummy"
)
}
//insert new message model into proper position
private static func insertNewMessage(
messages: [CHMessage],
userChat: CHUserChat) -> [CHMessage] {
guard let session = userChat.session else { return messages }
guard let lastReadAt = session.readAt else { return messages }
var newMessages = messages
var position = -1
for (index, message) in messages.enumerated() {
if Int(message.createdAt.timeIntervalSince1970) <= Int(lastReadAt.timeIntervalSince1970) {
break
}
position = index
}
if position >= 0 {
let createdAt = messages[position].createdAt
let date = Calendar.current.date(byAdding: .nanosecond, value: -100, to: createdAt)
let msg = CHMessage(chatId: userChat.id,
message: CHAssets.localized("ch.unread_divider"),
type: .NewAlertMessage,
createdAt: date,
id: "new_dummy")
newMessages.insert(msg, at: position)
}
return newMessages
}
private static func getUserMessage(msg: String, userChat: CHUserChat?) -> CHMessage {
return CHMessage(chatId:userChat?.id ?? "dummy", message:msg, type: .UserMessage)
}
}
| 27.707692 | 96 | 0.629095 |
fbfd0d32ac3deb2d339642907e50511788673f7b | 4,218 | //
// StartBackupCardLinkingTask.swift
// TangemSdk
//
// Created by Alexander Osokin on 09.09.2021.
// Copyright © 2021 Tangem AG. All rights reserved.
//
import Foundation
import Combine
@available(iOS 13.0, *)
final class StartBackupCardLinkingTask: CardSessionRunnable {
private let primaryCard: PrimaryCard
private let addedBackupCards: [String]
private let onlineCardVerifier = OnlineCardVerifier()
private var cancellable: AnyCancellable? = nil
private var linkingCommand: StartBackupCardLinkingCommand? = nil
init(primaryCard: PrimaryCard, addedBackupCards: [String]) {
self.primaryCard = primaryCard
self.addedBackupCards = addedBackupCards
}
deinit {
Log.debug("StartBackupCardLinkingTask deinit")
}
func run(in session: CardSession, completion: @escaping CompletionResult<BackupCard>) {
if session.environment.config.handleErrors {
guard let card = session.environment.card else {
completion(.failure(.missingPreflightRead))
return
}
let primaryWalletCurves = Set(primaryCard.walletCurves)
let backupCardSupportedCurves = Set(card.supportedCurves)
if card.issuer.publicKey != primaryCard.issuer.publicKey {
completion(.failure(.backupFailedWrongIssuer))
return
}
if card.settings.isHDWalletAllowed != primaryCard.isHDWalletAllowed {
completion(.failure(.backupFailedHDWalletSettings))
return
}
if !primaryWalletCurves.isSubset(of: backupCardSupportedCurves) {
completion(.failure(.backupFailedNotEnoughCurves))
return
}
if primaryCard.existingWalletsCount > card.settings.maxWalletsCount {
completion(.failure(.backupFailedNotEnoughWallets))
return
}
if card.cardId.lowercased() == primaryCard.cardId.lowercased() {
completion(.failure(.backupCardRequired))
return
}
if addedBackupCards.contains(card.cardId) {
completion(.failure(.backupCardAlreadyAdded))
return
}
}
linkingCommand = StartBackupCardLinkingCommand(primaryCardLinkingKey: primaryCard.linkingKey)
linkingCommand!.run(in: session) { result in
switch result {
case .success(let rawCard):
self.loadIssuerSignature(rawCard, session, completion)
case .failure(let error):
completion(.failure(error))
}
}
}
private func loadIssuerSignature(_ rawCard: RawBackupCard, _ session: CardSession, _ completion: @escaping CompletionResult<BackupCard>) {
if session.environment.card?.firmwareVersion.type == .sdk {
let issuerPrivateKey = Data(hexString: "11121314151617184771ED81F2BACF57479E4735EB1405083927372D40DA9E92")
do {
let issuerSignature = try rawCard.cardPublicKey.sign(privateKey: issuerPrivateKey)
completion(.success(BackupCard(rawCard, issuerSignature: issuerSignature)))
} catch {
completion(.failure(error.toTangemSdkError()))
}
return
}
cancellable = onlineCardVerifier
.getCardData(cardId: rawCard.cardId, cardPublicKey: rawCard.cardPublicKey)
.sink(receiveCompletion: { receivedCompletion in
if case .failure = receivedCompletion {
completion(.failure(.issuerSignatureLoadingFailed))
}
}, receiveValue: { response in
guard let signature = response.issuerSignature else {
completion(.failure(.issuerSignatureLoadingFailed))
return
}
let backupCard = BackupCard(rawCard, issuerSignature: signature)
completion(.success(backupCard))
})
}
}
| 38.345455 | 142 | 0.602181 |
4602bff868aa65067f6382c21e75724dc51dd36a | 1,180 | //
// Reachability.swift
// SmartZip
//
// Created by Pawan Dhawan on 09/08/16.
// Copyright © 2016 Pawan Kumar. All rights reserved.
//
import SystemConfiguration
public enum ReachabilityType {
case WWAN,
WiFi,
NotConnected
}
public class Reachability {
/**
:see: Original post - http://www.chrisdanielson.com/2009/07/22/iphone-network-connectivity-test-example/
*/
class func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
}
var flags = SCNetworkReachabilityFlags()
if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
return false
}
let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
return (isReachable && !needsConnection)
}
} | 29.5 | 109 | 0.671186 |
8af8b30c7fb11eba261d89904418bff787f48c83 | 1,864 | /**
* Copyright (c) 2021 Dustin Collins (Strega's Gate)
* All Rights Reserved.
* Licensed under Apache License v2.0
*
* Find me on https://www.YouTube.com/STREGAsGate, or social media @STREGAsGate
*/
import WinSDK
/// Identifies whether conservative rasterization is on or off.
public enum D3DConservativeRasterizationMode {
public typealias RawValue = WinSDK.D3D12_CONSERVATIVE_RASTERIZATION_MODE
/// Conservative rasterization is off.
case off
/// Conservative rasterization is on.
case on
/// This Swift Package had no implementation, this can happen if the Base API is expanded.
case _unimplemented(RawValue)
public var rawValue: RawValue {
switch self {
case .off:
return WinSDK.D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF
case .on:
return WinSDK.D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON
case let ._unimplemented(rawValue):
return rawValue
}
}
public init(_ rawValue: RawValue) {
switch rawValue {
case WinSDK.D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF:
self = .off
case WinSDK.D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON:
self = .on
default:
self = ._unimplemented(rawValue)
}
}
}
//MARK: - Original Style API
#if !Direct3D12ExcludeOriginalStyleAPI
@available(*, deprecated, renamed: "D3DConservativeRasterizationMode")
public typealias D3D12_CONSERVATIVE_RASTERIZATION_MODE = D3DConservativeRasterizationMode
@available(*, deprecated, renamed: "D3DConservativeRasterizationMode.off")
public let D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF = D3DConservativeRasterizationMode.off
@available(*, deprecated, renamed: "D3DConservativeRasterizationMode.on")
public let D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON = D3DConservativeRasterizationMode.on
#endif
| 30.557377 | 94 | 0.729077 |
8a988eece177d2ca00de1e60fab18cc80c37c7b0 | 3,566 | //
// SKPhotoBrowserDelegate.swift
// SKPhotoBrowser
//
// Created by 鈴木 啓司 on 2016/08/09.
// Copyright © 2016年 suzuki_keishi. All rights reserved.
//
import Foundation
@objc public protocol SKPhotoBrowserDelegate {
/**
Tells the delegate that the browser begin dragging scrollView
*/
@objc optional func scrollViewWillBeginDragging()
/**
Tells the delegate that the browser started displaying a new photo
- Parameter index: the index of the new photo
*/
@objc optional func didShowPhotoAtIndex(_ browser: SKPhotoBrowser, index: Int)
/**
Tells the delegate the browser will start to dismiss
- Parameter index: the index of the current photo
*/
@objc optional func willDismissAtPageIndex(_ index: Int)
/**
Tells the delegate that the browser will start showing the `UIActionSheet`
- Parameter photoIndex: the index of the current photo
*/
@objc optional func willShowActionSheet(_ photoIndex: Int)
/**
Tells the delegate that the browser has been dismissed
- Parameter index: the index of the current photo
*/
@objc optional func didDismissAtPageIndex(_ index: Int)
/**
Tells the delegate that the browser did dismiss the UIActionSheet
- Parameter buttonIndex: the index of the pressed button
- Parameter photoIndex: the index of the current photo
*/
@objc optional func didDismissActionSheetWithButtonIndex(_ buttonIndex: Int, photoIndex: Int)
/**
Tells the delegate that the browser did scroll to index
- Parameter index: the index of the photo where the user had scroll
*/
@objc optional func didScrollToIndex(_ browser: SKPhotoBrowser, index: Int)
/**
Tells the delegate the user removed a photo, when implementing this call, be sure to call reload to finish the deletion process
- Parameter browser: reference to the calling SKPhotoBrowser
- Parameter index: the index of the removed photo
- Parameter reload: function that needs to be called after finishing syncing up
*/
@objc optional func removePhoto(_ browser: SKPhotoBrowser, index: Int, reload: @escaping (() -> Void))
/**
Asks the delegate for the view for a certain photo. Needed to detemine the animation when presenting/closing the browser.
- Parameter browser: reference to the calling SKPhotoBrowser
- Parameter index: the index of the removed photo
- Returns: the view to animate to
*/
@objc optional func viewForPhoto(_ browser: SKPhotoBrowser, index: Int) -> UIView?
/**
Tells the delegate that the controls view toggled visibility
- Parameter browser: reference to the calling SKPhotoBrowser
- Parameter hidden: the status of visibility control
*/
@objc optional func controlsVisibilityToggled(_ browser: SKPhotoBrowser, hidden: Bool)
/**
Allows the delegate to create its own caption view
- Parameter index: the index of the photo
*/
@objc optional func captionViewForPhotoAtIndex(index: Int) -> SKCaptionView?
/**
Hanlde single tap on image
*/
@objc optional func singleTapOnImage()
/**
Hanlde direction of scrollview and index
*/
@objc optional func didScrollDirection(isLeft: Bool, index: Int)
/**
Hanlde pan gesture with offet Y
*/
@objc optional func didPanGestureRecognized(withOffsetY offsetY: CGFloat)
}
| 31.839286 | 132 | 0.678351 |
5b849dc81350bc258f05907c773142dd274139c0 | 26,411 | /*
Copyright 2016-present the Material Components for iOS 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.
*/
// swiftlint:disable file_length
// swiftlint:disable type_body_length
// swiftlint:disable function_body_length
import UIKit
import MaterialComponents.MaterialTextFields
import MaterialComponents.MaterialAppBar
import MaterialComponents.MaterialButtons
import MaterialComponents.MaterialTypography
final class TextFieldKitchenSinkSwiftExample: UIViewController {
let scrollView = UIScrollView()
let controlLabel: UILabel = {
let controlLabel = UILabel()
controlLabel.translatesAutoresizingMaskIntoConstraints = false
controlLabel.text = "Options"
controlLabel.font = UIFont.preferredFont(forTextStyle: .headline)
controlLabel.textColor = UIColor(white: 0, alpha: MDCTypography.headlineFontOpacity())
return controlLabel
}()
let singleLabel: UILabel = {
let singleLabel = UILabel()
singleLabel.translatesAutoresizingMaskIntoConstraints = false
singleLabel.text = "Single-line Text Fields"
singleLabel.font = UIFont.preferredFont(forTextStyle: .headline)
singleLabel.textColor = UIColor(white: 0, alpha: MDCTypography.headlineFontOpacity())
singleLabel.numberOfLines = 0
return singleLabel
}()
let multiLabel: UILabel = {
let multiLabel = UILabel()
multiLabel.translatesAutoresizingMaskIntoConstraints = false
multiLabel.text = "Multi-line Text Fields"
multiLabel.font = UIFont.preferredFont(forTextStyle: .headline)
multiLabel.textColor = UIColor(white: 0, alpha: MDCTypography.headlineFontOpacity())
multiLabel.numberOfLines = 0
return multiLabel
}()
let errorLabel: UILabel = {
let errorLabel = UILabel()
errorLabel.translatesAutoresizingMaskIntoConstraints = false
errorLabel.text = "In Error:"
errorLabel.font = UIFont.preferredFont(forTextStyle: .subheadline)
errorLabel.textColor = UIColor(white: 0, alpha: MDCTypography.subheadFontOpacity())
errorLabel.numberOfLines = 0
return errorLabel
}()
let helperLabel: UILabel = {
let helperLabel = UILabel()
helperLabel.translatesAutoresizingMaskIntoConstraints = false
helperLabel.text = "Show Helper Text:"
helperLabel.font = UIFont.preferredFont(forTextStyle: .subheadline)
helperLabel.textColor = UIColor(white: 0, alpha: MDCTypography.subheadFontOpacity())
helperLabel.numberOfLines = 0
return helperLabel
}()
var allInputControllers = [MDCTextInputController]()
var allTextFieldControllers = [MDCTextInputController]()
var allMultilineTextFieldControllers = [MDCTextInputController]()
var controllersWithCharacterCount = [MDCTextInputController]()
var controllersFullWidth = [MDCTextInputControllerFullWidth]()
let unstyledTextField = MDCTextField()
let unstyledMultilineTextField = MDCMultilineTextField()
lazy var textInsetsModeButton: MDCButton = self.setupButton()
lazy var characterModeButton: MDCButton = self.setupButton()
lazy var clearModeButton: MDCButton = self.setupButton()
lazy var underlineButton: MDCButton = self.setupButton()
deinit {
NotificationCenter.default.removeObserver(self)
}
override func viewDidLoad() {
super.viewDidLoad()
setupExampleViews()
}
func setupFilledTextFields() -> [MDCTextInputControllerFilled] {
let textFieldFilled = MDCTextField()
textFieldFilled.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(textFieldFilled)
textFieldFilled.delegate = self
textFieldFilled.placeholder = "This is a filled text field"
let textFieldControllerFilled = MDCTextInputControllerFilled(textInput: textFieldFilled)
textFieldControllerFilled.isFloatingEnabled = false
let textFieldFilledFloating = MDCTextField()
textFieldFilledFloating.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(textFieldFilledFloating)
textFieldFilledFloating.delegate = self
textFieldFilledFloating.placeholder = "This is filled and floating"
let textFieldControllerFilledFloating = MDCTextInputControllerFilled(textInput: textFieldFilledFloating)
return [textFieldControllerFilled, textFieldControllerFilledFloating]
}
func setupDefaultTextFields() -> [MDCTextInputControllerDefault] {
let textFieldDefault = MDCTextField()
textFieldDefault.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(textFieldDefault)
textFieldDefault.delegate = self
textFieldDefault.clearButtonMode = .whileEditing
let textFieldControllerDefault = MDCTextInputControllerDefault(textInput: textFieldDefault)
textFieldControllerDefault.isFloatingEnabled = false
let textFieldDefaultPlaceholder = MDCTextField()
textFieldDefaultPlaceholder.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(textFieldDefaultPlaceholder)
textFieldDefaultPlaceholder.placeholder = "This is a text field w/ inline placeholder"
textFieldDefaultPlaceholder.delegate = self
textFieldDefaultPlaceholder.clearButtonMode = .whileEditing
let textFieldControllerDefaultPlaceholder =
MDCTextInputControllerDefault(textInput: textFieldDefaultPlaceholder)
textFieldControllerDefaultPlaceholder.isFloatingEnabled = false
let textFieldDefaultCharMax = MDCTextField()
textFieldDefaultCharMax.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(textFieldDefaultCharMax)
textFieldDefaultCharMax.placeholder = "This is a text field w/ character count"
textFieldDefaultCharMax.delegate = self
textFieldDefaultCharMax.clearButtonMode = .whileEditing
let textFieldControllerDefaultCharMax =
MDCTextInputControllerDefault(textInput: textFieldDefaultCharMax)
textFieldControllerDefaultCharMax.characterCountMax = 50
textFieldControllerDefaultCharMax.isFloatingEnabled = false
controllersWithCharacterCount.append(textFieldControllerDefaultCharMax)
return [textFieldControllerDefault, textFieldControllerDefaultPlaceholder,
textFieldControllerDefaultCharMax]
}
func setupFullWidthTextFields() -> [MDCTextInputControllerFullWidth] {
let textFieldFullWidthPlaceholder = MDCTextField()
textFieldFullWidthPlaceholder.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(textFieldFullWidthPlaceholder)
textFieldFullWidthPlaceholder.placeholder = "This is a full width text field"
textFieldFullWidthPlaceholder.delegate = self
textFieldFullWidthPlaceholder.clearButtonMode = .whileEditing
let textFieldControllerFullWidthPlaceholder =
MDCTextInputControllerFullWidth(textInput: textFieldFullWidthPlaceholder)
let textFieldFullWidthCharMax = MDCTextField()
textFieldFullWidthCharMax.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(textFieldFullWidthCharMax)
textFieldFullWidthCharMax.placeholder =
"This is a full width text field with character count and a very long placeholder"
textFieldFullWidthCharMax.delegate = self
textFieldFullWidthCharMax.clearButtonMode = .whileEditing
let textFieldControllerFullWidthCharMax =
MDCTextInputControllerFullWidth(textInput: textFieldFullWidthCharMax)
textFieldControllerFullWidthCharMax.characterCountMax = 50
controllersWithCharacterCount.append(textFieldControllerFullWidthCharMax)
return [textFieldControllerFullWidthPlaceholder,
textFieldControllerFullWidthCharMax]
}
func setupFloatingTextFields() -> [MDCTextInputControllerDefault] {
let textFieldFloating = MDCTextField()
textFieldFloating.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(textFieldFloating)
textFieldFloating.placeholder = "This is a text field w/ floating placeholder"
textFieldFloating.delegate = self
textFieldFloating.clearButtonMode = .whileEditing
let textFieldControllerFloating = MDCTextInputControllerDefault(textInput: textFieldFloating)
let textFieldFloatingCharMax = MDCTextField()
textFieldFloatingCharMax.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(textFieldFloatingCharMax)
textFieldFloatingCharMax.placeholder = "This is floating with character count"
textFieldFloatingCharMax.delegate = self
textFieldFloatingCharMax.clearButtonMode = .whileEditing
let textFieldControllerFloatingCharMax =
MDCTextInputControllerDefault(textInput: textFieldFloatingCharMax)
textFieldControllerFloatingCharMax.characterCountMax = 50
controllersWithCharacterCount.append(textFieldControllerFloatingCharMax)
return [textFieldControllerFloating, textFieldControllerFloatingCharMax]
}
func setupSpecialTextFields() -> [MDCTextInputControllerDefault] {
let textFieldDisabled = MDCTextField()
textFieldDisabled.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(textFieldDisabled)
textFieldDisabled.placeholder = "This is a disabled text field"
textFieldDisabled.delegate = self
textFieldDisabled.isEnabled = false
let textFieldControllerDefaultDisabled =
MDCTextInputControllerDefault(textInput: textFieldDisabled)
textFieldControllerDefaultDisabled.isFloatingEnabled = false
let textFieldCustomFont = MDCTextField()
textFieldCustomFont.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(textFieldCustomFont)
textFieldCustomFont.font = UIFont.preferredFont(forTextStyle: .headline)
textFieldCustomFont.placeholder = "This is a custom font"
textFieldCustomFont.delegate = self
textFieldCustomFont.clearButtonMode = .whileEditing
let textFieldControllerDefaultCustomFont =
MDCTextInputControllerDefault(textInput: textFieldCustomFont)
textFieldControllerDefaultCustomFont.inlinePlaceholderFont = UIFont.preferredFont(forTextStyle: .headline)
textFieldControllerDefaultCustomFont.isFloatingEnabled = false
let textFieldCustomFontFloating = MDCTextField()
textFieldCustomFontFloating.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(textFieldCustomFontFloating)
textFieldCustomFontFloating.font = UIFont.preferredFont(forTextStyle: .headline)
textFieldCustomFontFloating.placeholder = "This is a custom font with the works"
textFieldCustomFontFloating.delegate = self
textFieldCustomFontFloating.clearButtonMode = .whileEditing
let textFieldControllerDefaultCustomFontFloating =
MDCTextInputControllerDefault(textInput: textFieldCustomFontFloating)
textFieldControllerDefaultCustomFontFloating.characterCountMax = 40
textFieldControllerDefaultCustomFontFloating.helperText = "Custom Font"
textFieldControllerDefaultCustomFontFloating.activeColor = .green
textFieldControllerDefaultCustomFontFloating.normalColor = .purple
textFieldControllerDefaultCustomFontFloating.leadingUnderlineLabelTextColor = .cyan
textFieldControllerDefaultCustomFontFloating.trailingUnderlineLabelTextColor = .magenta
textFieldControllerDefaultCustomFontFloating.leadingUnderlineLabelFont =
UIFont.preferredFont(forTextStyle: .headline)
textFieldControllerDefaultCustomFontFloating.inlinePlaceholderFont =
UIFont.preferredFont(forTextStyle: .headline)
textFieldControllerDefaultCustomFontFloating.trailingUnderlineLabelFont =
UIFont.preferredFont(forTextStyle: .subheadline)
textFieldCustomFontFloating.clearButton.tintColor = MDCPalette.red.accent400
let bundle = Bundle(for: TextFieldKitchenSinkSwiftExample.self)
let leftViewImage = UIImage(named: "ic_search", in: bundle, compatibleWith: nil)!
let textFieldLeftView = MDCTextField()
textFieldLeftView.leftViewMode = .always
textFieldLeftView.leftView = UIImageView(image:leftViewImage)
textFieldLeftView.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(textFieldLeftView)
textFieldLeftView.placeholder = "This has a left view"
textFieldLeftView.delegate = self
textFieldLeftView.clearButtonMode = .whileEditing
let textFieldControllerDefaultLeftView =
MDCTextInputControllerDefault(textInput: textFieldLeftView)
textFieldControllerDefaultLeftView.isFloatingEnabled = false
let textFieldLeftViewFloating = MDCTextField()
textFieldLeftViewFloating.leftViewMode = .always
textFieldLeftViewFloating.leftView = UIImageView(image:leftViewImage)
textFieldLeftViewFloating.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(textFieldLeftViewFloating)
textFieldLeftViewFloating.placeholder = "This has a left view and floats"
textFieldLeftViewFloating.delegate = self
textFieldLeftViewFloating.clearButtonMode = .whileEditing
let textFieldControllerDefaultLeftViewFloating =
MDCTextInputControllerDefault(textInput: textFieldLeftViewFloating)
let rightViewImage = UIImage(named: "ic_done", in: bundle, compatibleWith: nil)!
let textFieldRightView = MDCTextField()
textFieldRightView.rightViewMode = .always
textFieldRightView.rightView = UIImageView(image:rightViewImage)
textFieldRightView.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(textFieldRightView)
textFieldRightView.placeholder = "This has a right view"
textFieldRightView.delegate = self
textFieldRightView.clearButtonMode = .whileEditing
let textFieldControllerDefaultRightView =
MDCTextInputControllerDefault(textInput: textFieldRightView)
textFieldControllerDefaultRightView.isFloatingEnabled = false
let textFieldRightViewFloating = MDCTextField()
textFieldRightViewFloating.rightViewMode = .always
textFieldRightViewFloating.rightView = UIImageView(image:rightViewImage)
textFieldRightViewFloating.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(textFieldRightViewFloating)
textFieldRightViewFloating.placeholder = "This has a right view and floats"
textFieldRightViewFloating.delegate = self
textFieldRightViewFloating.clearButtonMode = .whileEditing
let textFieldControllerDefaultRightViewFloating =
MDCTextInputControllerDefault(textInput: textFieldRightViewFloating)
let textFieldLeftRightView = MDCTextField()
textFieldLeftRightView.leftViewMode = .whileEditing
textFieldLeftRightView.leftView = UIImageView(image: leftViewImage)
textFieldLeftRightView.rightViewMode = .unlessEditing
textFieldLeftRightView.rightView = UIImageView(image:rightViewImage)
textFieldLeftRightView.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(textFieldLeftRightView)
textFieldLeftRightView.placeholder =
"This has left & right views and a very long placeholder that should be truncated"
textFieldLeftRightView.delegate = self
textFieldLeftRightView.clearButtonMode = .whileEditing
let textFieldControllerDefaultLeftRightView =
MDCTextInputControllerDefault(textInput: textFieldLeftRightView)
textFieldControllerDefaultLeftRightView.isFloatingEnabled = false
let textFieldLeftRightViewFloating = MDCTextField()
textFieldLeftRightViewFloating.leftViewMode = .always
textFieldLeftRightViewFloating.leftView = UIImageView(image: leftViewImage)
textFieldLeftRightViewFloating.rightViewMode = .whileEditing
textFieldLeftRightViewFloating.rightView = UIImageView(image:rightViewImage)
textFieldLeftRightViewFloating.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(textFieldLeftRightViewFloating)
textFieldLeftRightViewFloating.placeholder =
"This has left & right views and floats and a very long placeholder that should be truncated"
textFieldLeftRightViewFloating.delegate = self
textFieldLeftRightViewFloating.clearButtonMode = .whileEditing
let textFieldControllerDefaultLeftRightViewFloating =
MDCTextInputControllerDefault(textInput: textFieldLeftRightViewFloating)
unstyledTextField.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(unstyledTextField)
unstyledTextField.placeholder = "This is an unstyled text field (no controller)"
unstyledTextField.leadingUnderlineLabel.text = "Leading label"
unstyledTextField.trailingUnderlineLabel.text = "Trailing label"
unstyledTextField.delegate = self
unstyledTextField.clearButtonMode = .whileEditing
unstyledTextField.leftView = UIImageView(image: leftViewImage)
unstyledTextField.leftViewMode = .always
unstyledTextField.rightView = UIImageView(image: rightViewImage)
unstyledTextField.rightViewMode = .always
return [textFieldControllerDefaultDisabled,
textFieldControllerDefaultCustomFont, textFieldControllerDefaultCustomFontFloating,
textFieldControllerDefaultLeftView, textFieldControllerDefaultLeftViewFloating,
textFieldControllerDefaultRightView, textFieldControllerDefaultRightViewFloating,
textFieldControllerDefaultLeftRightView,
textFieldControllerDefaultLeftRightViewFloating]
}
// MARK: - Multi-line
func setupAreaTextFields() -> [MDCTextInputControllerOutlinedTextArea] {
let textFieldArea = MDCMultilineTextField()
textFieldArea.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(textFieldArea)
textFieldArea.textView?.delegate = self
textFieldArea.placeholder = "This is a text area"
let textFieldControllerArea = MDCTextInputControllerOutlinedTextArea(textInput: textFieldArea)
return [textFieldControllerArea]
}
func setupDefaultMultilineTextFields() -> [MDCTextInputControllerDefault] {
let multilineTextFieldDefault = MDCMultilineTextField()
multilineTextFieldDefault.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(multilineTextFieldDefault)
multilineTextFieldDefault.textView?.delegate = self
let multilineTextFieldControllerDefault =
MDCTextInputControllerDefault(textInput: multilineTextFieldDefault)
multilineTextFieldControllerDefault.isFloatingEnabled = false
let multilineTextFieldDefaultPlaceholder = MDCMultilineTextField()
multilineTextFieldDefaultPlaceholder.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(multilineTextFieldDefaultPlaceholder)
multilineTextFieldDefaultPlaceholder.placeholder =
"This is a multi-line text field with placeholder"
multilineTextFieldDefaultPlaceholder.textView?.delegate = self
let multilineTextFieldControllerDefaultPlaceholder =
MDCTextInputControllerDefault(textInput: multilineTextFieldDefaultPlaceholder)
multilineTextFieldControllerDefaultPlaceholder.isFloatingEnabled = false
let multilineTextFieldDefaultCharMax = MDCMultilineTextField()
multilineTextFieldDefaultCharMax.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(multilineTextFieldDefaultCharMax)
multilineTextFieldDefaultCharMax.placeholder = "This is a multi-line text field with placeholder"
multilineTextFieldDefaultCharMax.textView?.delegate = self
let multilineTextFieldControllerDefaultCharMax =
MDCTextInputControllerDefault(textInput: multilineTextFieldDefaultCharMax)
multilineTextFieldControllerDefaultCharMax.characterCountMax = 140
multilineTextFieldControllerDefaultCharMax.isFloatingEnabled = false
controllersWithCharacterCount.append(multilineTextFieldControllerDefaultCharMax)
return [multilineTextFieldControllerDefault, multilineTextFieldControllerDefaultPlaceholder,
multilineTextFieldControllerDefaultCharMax]
}
func setupFullWidthMultilineTextFields() -> [MDCTextInputControllerFullWidth] {
let multilineTextFieldFullWidth = MDCMultilineTextField()
multilineTextFieldFullWidth.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(multilineTextFieldFullWidth)
multilineTextFieldFullWidth.placeholder = "This is a full width multi-line text field"
multilineTextFieldFullWidth.textView?.delegate = self
let multilineTextFieldControllerFullWidth =
MDCTextInputControllerFullWidth(textInput: multilineTextFieldFullWidth)
let multilineTextFieldFullWidthCharMax = MDCMultilineTextField()
multilineTextFieldFullWidthCharMax.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(multilineTextFieldFullWidthCharMax)
multilineTextFieldFullWidthCharMax.placeholder =
"This is a full width multi-line text field with character count"
multilineTextFieldFullWidthCharMax.textView?.delegate = self
let multilineTextFieldControllerFullWidthCharMax =
MDCTextInputControllerFullWidth(textInput: multilineTextFieldFullWidthCharMax)
controllersWithCharacterCount.append(multilineTextFieldControllerFullWidthCharMax)
multilineTextFieldControllerFullWidthCharMax.characterCountMax = 140
return [multilineTextFieldControllerFullWidth, multilineTextFieldControllerFullWidthCharMax]
}
func setupFloatingMultilineTextFields() -> [MDCTextInputControllerDefault] {
let multilineTextFieldFloating = MDCMultilineTextField()
multilineTextFieldFloating.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(multilineTextFieldFloating)
multilineTextFieldFloating.textView?.delegate = self
multilineTextFieldFloating.placeholder =
"This is a multi-line text field with a floating placeholder"
let multilineTextFieldControllerFloating =
MDCTextInputControllerDefault(textInput: multilineTextFieldFloating)
let multilineTextFieldFloatingCharMax = MDCMultilineTextField()
multilineTextFieldFloatingCharMax.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(multilineTextFieldFloatingCharMax)
multilineTextFieldFloatingCharMax.textView?.delegate = self
multilineTextFieldFloatingCharMax.placeholder =
"This is a multi-line text field with a floating placeholder and character count"
let multilineTextFieldControllerFloatingCharMax =
MDCTextInputControllerDefault(textInput: multilineTextFieldFloatingCharMax)
controllersWithCharacterCount.append(multilineTextFieldControllerFloatingCharMax)
return [multilineTextFieldControllerFloating, multilineTextFieldControllerFloatingCharMax]
}
func setupSpecialMultilineTextFields() -> [MDCTextInputController] {
let bundle = Bundle(for: TextFieldKitchenSinkSwiftExample.self)
let rightViewImage = UIImage(named: "ic_done", in: bundle, compatibleWith: nil)!
let multilineTextFieldTrailingView = MDCMultilineTextField()
multilineTextFieldTrailingView.trailingViewMode = .always
multilineTextFieldTrailingView.trailingView = UIImageView(image:rightViewImage)
multilineTextFieldTrailingView.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(multilineTextFieldTrailingView)
multilineTextFieldTrailingView.placeholder = "This has a trailing view"
multilineTextFieldTrailingView.textView?.delegate = self
multilineTextFieldTrailingView.clearButtonMode = .whileEditing
let multilineTextFieldControllerDefaultTrailingView =
MDCTextInputControllerDefault(textInput: multilineTextFieldTrailingView)
multilineTextFieldControllerDefaultTrailingView.isFloatingEnabled = false
let multilineTextFieldCustomFont = MDCMultilineTextField()
multilineTextFieldCustomFont.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(multilineTextFieldCustomFont)
multilineTextFieldCustomFont.placeholder = "This has a custom font"
let multilineTextFieldControllerDefaultCustomFont =
MDCTextInputControllerDefault(textInput: multilineTextFieldCustomFont)
multilineTextFieldCustomFont.placeholderLabel.font = UIFont.preferredFont(forTextStyle: .headline)
multilineTextFieldCustomFont.font = UIFont.preferredFont(forTextStyle: .headline)
scrollView.addSubview(unstyledMultilineTextField)
unstyledMultilineTextField.translatesAutoresizingMaskIntoConstraints = false
unstyledMultilineTextField.placeholder =
"This multi-line text field has no controller (unstyled)"
unstyledMultilineTextField.leadingUnderlineLabel.text = "Leading label"
unstyledMultilineTextField.trailingUnderlineLabel.text = "Trailing label"
unstyledMultilineTextField.textView?.delegate = self
return [multilineTextFieldControllerDefaultTrailingView,
multilineTextFieldControllerDefaultCustomFont]
}
@objc func tapDidTouch(sender: Any) {
self.view.endEditing(true)
}
@objc func errorSwitchDidChange(errorSwitch: UISwitch) {
allInputControllers.forEach { controller in
if errorSwitch.isOn {
controller.setErrorText("Uh oh! Try something else.", errorAccessibilityValue: nil)
} else {
controller.setErrorText(nil, errorAccessibilityValue: nil)
}
}
}
@objc func helperSwitchDidChange(helperSwitch: UISwitch) {
allInputControllers.forEach { controller in
controller.helperText = helperSwitch.isOn ? "This is helper text." : nil
}
}
}
extension TextFieldKitchenSinkSwiftExample: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return false
}
}
extension TextFieldKitchenSinkSwiftExample: UITextViewDelegate {
func textViewDidChange(_ textView: UITextView) {
print(textView.text)
}
}
extension TextFieldKitchenSinkSwiftExample {
@objc func contentSizeCategoryDidChange(notif: Notification) {
controlLabel.font = UIFont.preferredFont(forTextStyle: .headline)
singleLabel.font = UIFont.preferredFont(forTextStyle: .headline)
errorLabel.font = UIFont.preferredFont(forTextStyle: .subheadline)
helperLabel.font = UIFont.preferredFont(forTextStyle: .subheadline)
}
}
| 44.018333 | 110 | 0.812843 |
0a7fa3f8f6670fd29872be4d35272719aa6d965c | 1,838 | // The MIT License (MIT)
// Copyright © 2022 Sparrow Code LTD (https://sparrowcode.io, [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.
extension SafeSFSymbol {
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public static var laptopcomputer: Laptopcomputer { .init(name: "laptopcomputer") }
open class Laptopcomputer: SafeSFSymbol {
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
open var andArrowDown: SafeSFSymbol { ext(.start + ".and.arrow.down") }
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
open var andIphone: SafeSFSymbol { ext(.start + ".and.iphone") }
@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
open var trianglebadgeExclamationmark: SafeSFSymbol { ext(.start + ".trianglebadge.exclamationmark") }
}
} | 49.675676 | 104 | 0.740479 |
e54039f88a1437991ea6a7caa75a70bf7a10360a | 955 | //
// Copyright 2014 Scott Logic
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
@IBDesignable
class PaddedLabel: UILabel {
@IBInspectable
var horizontalPadding: CGFloat = 16
@IBInspectable
var verticalPadding: CGFloat = 16
override func intrinsicContentSize() -> CGSize {
var size = super.intrinsicContentSize()
size.height += verticalPadding
size.width += horizontalPadding
return size
}
}
| 26.527778 | 75 | 0.73089 |
d7a91bdb17a091e56eb9728878ed67a6a72f33ca | 1,092 | // Copyright 2018-2020 Amazon.com, Inc. or its affiliates. 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.
// A copy of the License is located at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// or in the "license" file accompanying this file. This file 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.
//
// GlobalDispatchQueueAsyncInvocationStrategy.swift
// SmokeInvocation
//
import Foundation
/**
An InvocationStrategy that will invocate the handler on
DispatchQueue.global(), not waiting for it to complete.
*/
public struct GlobalDispatchQueueAsyncInvocationStrategy: InvocationStrategy {
let queue = DispatchQueue.global()
public init() {
}
public func invoke(handler: @escaping () -> ()) {
queue.async {
handler()
}
}
}
| 29.513514 | 79 | 0.700549 |
fc647c8f2c10b7221d6823a6ec3fc0ed4b346072 | 7,296 | //
// DO NOT EDIT.
//
// Generated by the protocol buffer compiler.
// Source: notes.proto
//
//
// Copyright 2018, gRPC Authors All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import GRPC
import NIO
import NIOHTTP1
import SwiftProtobuf
/// Usage: instantiate NotesServiceServiceClient, then call methods of this protocol to make API calls.
internal protocol NotesServiceService {
func createNote(_ request: CreateNoteRequest, callOptions: CallOptions?) -> UnaryCall<CreateNoteRequest, CreateNoteResponse>
func deleteNotes(callOptions: CallOptions?) -> ClientStreamingCall<DeleteNotesRequest, DeleteNotesResponse>
func getNotes(_ request: GetNotesRequest, callOptions: CallOptions?, handler: @escaping (GetNotesResponse) -> Void) -> ServerStreamingCall<GetNotesRequest, GetNotesResponse>
func switchTitleContent(callOptions: CallOptions?, handler: @escaping (SwitchTitleContentResponse) -> Void) -> BidirectionalStreamingCall<SwitchTitleContentRequest, SwitchTitleContentResponse>
}
internal final class NotesServiceServiceClient: GRPCClient, NotesServiceService {
internal let connection: ClientConnection
internal var defaultCallOptions: CallOptions
/// Creates a client for the NotesService service.
///
/// - Parameters:
/// - connection: `ClientConnection` to the service host.
/// - defaultCallOptions: Options to use for each service call if the user doesn't provide them.
internal init(connection: ClientConnection, defaultCallOptions: CallOptions = CallOptions()) {
self.connection = connection
self.defaultCallOptions = defaultCallOptions
}
/// Asynchronous unary call to CreateNote.
///
/// - Parameters:
/// - request: Request to send to CreateNote.
/// - callOptions: Call options; `self.defaultCallOptions` is used if `nil`.
/// - Returns: A `UnaryCall` with futures for the metadata, status and response.
internal func createNote(_ request: CreateNoteRequest, callOptions: CallOptions? = nil) -> UnaryCall<CreateNoteRequest, CreateNoteResponse> {
return self.makeUnaryCall(path: "/NotesService/CreateNote",
request: request,
callOptions: callOptions ?? self.defaultCallOptions)
}
/// Asynchronous client-streaming call to DeleteNotes.
///
/// Callers should use the `send` method on the returned object to send messages
/// to the server. The caller should send an `.end` after the final message has been sent.
///
/// - Parameters:
/// - callOptions: Call options; `self.defaultCallOptions` is used if `nil`.
/// - Returns: A `ClientStreamingCall` with futures for the metadata, status and response.
internal func deleteNotes(callOptions: CallOptions? = nil) -> ClientStreamingCall<DeleteNotesRequest, DeleteNotesResponse> {
return self.makeClientStreamingCall(path: "/NotesService/DeleteNotes",
callOptions: callOptions ?? self.defaultCallOptions)
}
/// Asynchronous server-streaming call to GetNotes.
///
/// - Parameters:
/// - request: Request to send to GetNotes.
/// - callOptions: Call options; `self.defaultCallOptions` is used if `nil`.
/// - handler: A closure called when each response is received from the server.
/// - Returns: A `ServerStreamingCall` with futures for the metadata and status.
internal func getNotes(_ request: GetNotesRequest, callOptions: CallOptions? = nil, handler: @escaping (GetNotesResponse) -> Void) -> ServerStreamingCall<GetNotesRequest, GetNotesResponse> {
return self.makeServerStreamingCall(path: "/NotesService/GetNotes",
request: request,
callOptions: callOptions ?? self.defaultCallOptions,
handler: handler)
}
/// Asynchronous bidirectional-streaming call to SwitchTitleContent.
///
/// Callers should use the `send` method on the returned object to send messages
/// to the server. The caller should send an `.end` after the final message has been sent.
///
/// - Parameters:
/// - callOptions: Call options; `self.defaultCallOptions` is used if `nil`.
/// - handler: A closure called when each response is received from the server.
/// - Returns: A `ClientStreamingCall` with futures for the metadata and status.
internal func switchTitleContent(callOptions: CallOptions? = nil, handler: @escaping (SwitchTitleContentResponse) -> Void) -> BidirectionalStreamingCall<SwitchTitleContentRequest, SwitchTitleContentResponse> {
return self.makeBidirectionalStreamingCall(path: "/NotesService/SwitchTitleContent",
callOptions: callOptions ?? self.defaultCallOptions,
handler: handler)
}
}
/// To build a server, implement a class that conforms to this protocol.
internal protocol NotesServiceProvider: CallHandlerProvider {
func createNote(request: CreateNoteRequest, context: StatusOnlyCallContext) -> EventLoopFuture<CreateNoteResponse>
func deleteNotes(context: UnaryResponseCallContext<DeleteNotesResponse>) -> EventLoopFuture<(StreamEvent<DeleteNotesRequest>) -> Void>
func getNotes(request: GetNotesRequest, context: StreamingResponseCallContext<GetNotesResponse>) -> EventLoopFuture<GRPCStatus>
func switchTitleContent(context: StreamingResponseCallContext<SwitchTitleContentResponse>) -> EventLoopFuture<(StreamEvent<SwitchTitleContentRequest>) -> Void>
}
extension NotesServiceProvider {
internal var serviceName: String { return "NotesService" }
/// Determines, calls and returns the appropriate request handler, depending on the request's method.
/// Returns nil for methods not handled by this service.
internal func handleMethod(_ methodName: String, callHandlerContext: CallHandlerContext) -> GRPCCallHandler? {
switch methodName {
case "CreateNote":
return UnaryCallHandler(callHandlerContext: callHandlerContext) { context in
return { request in
self.createNote(request: request, context: context)
}
}
case "DeleteNotes":
return ClientStreamingCallHandler(callHandlerContext: callHandlerContext) { context in
return self.deleteNotes(context: context)
}
case "GetNotes":
return ServerStreamingCallHandler(callHandlerContext: callHandlerContext) { context in
return { request in
self.getNotes(request: request, context: context)
}
}
case "SwitchTitleContent":
return BidirectionalStreamingCallHandler(callHandlerContext: callHandlerContext) { context in
return self.switchTitleContent(context: context)
}
default: return nil
}
}
}
| 48 | 211 | 0.721354 |
f7f70302a7ac39b52acd22747b2f5f070790b8df | 149 | // Header
/// Blah blah blah...
///
/// - Parameter one: A parameter documented the wrong way, so trigger.
func parameters(one: Bool, two: Bool) {}
| 21.285714 | 70 | 0.657718 |
1e202b91058ea6569dec8c52ec99342a5e73e4fe | 751 | // Copyright 2019 Kakao Corp.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
extension Data {
public func hexEncodedString() -> String {
return map { String(format: "%02hhx ", $0) }.joined()
}
}
| 34.136364 | 76 | 0.708389 |
69179760d33c5313f2e52f5a96c301afa565e420 | 246 | //
// GameViewController.swift
// Slappy Ball
//
// Created by Dulio Denis on 6/1/16.
// Copyright (c) 2016 Dulio Denis. All rights reserved.
//
import UIKit
import QuartzCore
import SceneKit
class GameViewController: UIViewController {
}
| 15.375 | 56 | 0.727642 |
76d78b2c1140a96772fd656c39579f05eb161437 | 582 | //
// MainAuthenticationScreen.swift
// GlobalCitizenComponents
//
// Created by Pedro Manfredi on 25/09/2019.
// Copyright © 2019 Pedro Manfredi. All rights reserved.
//
import Foundation
import UIKit
@IBDesignable
public class Page1Authentication: UIView, NibLoadable {
@IBOutlet weak var image: UIImageView!
@IBOutlet weak var text: RBody!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupFromNib()
}
override init(frame: CGRect) {
super.init(frame: frame)
setupFromNib()
}
}
| 20.785714 | 57 | 0.666667 |
0a61e0b173c90455ca360bb5171ef6969475fe87 | 10,354 | extension Publisher {
/// Combine elements from two other publishers and deliver groups of elements as tuples.
///
/// The returned publisher waits until all three publishers have emitted an event, then delivers the oldest unconsumed event from each publisher as a tuple to the subscriber.
/// For example, if publisher `P1` emits elements `a` and `b`, and publisher `P2` emits elements `c` and `d`, and publisher `P3` emits the event `e`, the zip publisher emits the tuple `(a, c, e)`. It won’t emit a tuple with elements `b` or `d` until `P3` emits another event.
/// If any upstream publisher finishes successfuly or fails with an error, the zipped publisher does the same.
///
/// - Parameters:
/// - publisher1: A second publisher.
/// - publisher2: A third publisher.
/// - Returns: A publisher that emits groups of elements from the upstream publishers as tuples.
public func zip<P, Q>(_ publisher1: P, _ publisher2: Q) -> Publishers.Zip3<Self, P, Q> where P : Publisher, Q : Publisher, Self.Failure == P.Failure, P.Failure == Q.Failure {
return .init(self, publisher1, publisher2)
}
/// Combine elements from two other publishers and deliver a transformed output.
///
/// The returned publisher waits until all three publishers have emitted an event, then delivers the oldest unconsumed event from each publisher as a tuple to the subscriber.
/// For example, if publisher `P1` emits elements `a` and `b`, and publisher `P2` emits elements `c` and `d`, and publisher `P3` emits the event `e`, the zip publisher emits the tuple `(a, c, e)`. It won’t emit a tuple with elements `b` or `d` until `P3` emits another event.
/// If any upstream publisher finishes successfuly or fails with an error, the zipped publisher does the same.
///
/// - Parameters:
/// - publisher1: A second publisher.
/// - publisher2: A third publisher.
/// - transform: A closure that receives the most recent value from each publisher and returns a new value to publish.
/// - Returns: A publisher that emits groups of elements from the upstream publishers as tuples.
public func zip<P, Q, T>(_ publisher1: P, _ publisher2: Q, _ transform: @escaping (Self.Output, P.Output, Q.Output) -> T) -> Publishers.Map<Publishers.Zip3<Self, P, Q>, T> where P : Publisher, Q : Publisher, Self.Failure == P.Failure, P.Failure == Q.Failure {
return self.zip(publisher1, publisher2).map(transform)
}
/// Combine elements from three other publishers and deliver groups of elements as tuples.
///
/// The returned publisher waits until all four publishers have emitted an event, then delivers the oldest unconsumed event from each publisher as a tuple to the subscriber.
/// For example, if publisher `P1` emits elements `a` and `b`, and publisher `P2` emits elements `c` and `d`, and publisher `P3` emits the elements `e` and `f`, and publisher `P4` emits the event `g`, the zip publisher emits the tuple `(a, c, e, g)`. It won’t emit a tuple with elements `b`, `d`, or `f` until `P4` emits another event.
/// If any upstream publisher finishes successfuly or fails with an error, the zipped publisher does the same.
///
/// - Parameters:
/// - publisher1: A second publisher.
/// - publisher2: A third publisher.
/// - publisher3: A fourth publisher.
/// - Returns: A publisher that emits groups of elements from the upstream publishers as tuples.
public func zip<P, Q, R>(_ publisher1: P, _ publisher2: Q, _ publisher3: R) -> Publishers.Zip4<Self, P, Q, R> where P : Publisher, Q : Publisher, R : Publisher, Self.Failure == P.Failure, P.Failure == Q.Failure, Q.Failure == R.Failure {
return .init(self, publisher1, publisher2, publisher3)
}
/// Combine elements from three other publishers and deliver a transformed output.
///
/// The returned publisher waits until all four publishers have emitted an event, then delivers the oldest unconsumed event from each publisher as a tuple to the subscriber.
/// For example, if publisher `P1` emits elements `a` and `b`, and publisher `P2` emits elements `c` and `d`, and publisher `P3` emits the elements `e` and `f`, and publisher `P4` emits the event `g`, the zip publisher emits the tuple `(a, c, e, g)`. It won’t emit a tuple with elements `b`, `d`, or `f` until `P4` emits another event.
/// If any upstream publisher finishes successfuly or fails with an error, the zipped publisher does the same.
///
/// - Parameters:
/// - publisher1: A second publisher.
/// - publisher2: A third publisher.
/// - publisher3: A fourth publisher.
/// - transform: A closure that receives the most recent value from each publisher and returns a new value to publish.
/// - Returns: A publisher that emits groups of elements from the upstream publishers as tuples.
public func zip<P, Q, R, T>(_ publisher1: P, _ publisher2: Q, _ publisher3: R, _ transform: @escaping (Self.Output, P.Output, Q.Output, R.Output) -> T) -> Publishers.Map<Publishers.Zip4<Self, P, Q, R>, T> where P : Publisher, Q : Publisher, R : Publisher, Self.Failure == P.Failure, P.Failure == Q.Failure, Q.Failure == R.Failure {
return self.zip(publisher1, publisher2, publisher3).map(transform)
}
}
/// Returns a Boolean value that indicates whether two publishers are equivalent.
///
/// - Parameters:
/// - lhs: A zip publisher to compare for equality.
/// - rhs: Another zip publisher to compare for equality.
/// - Returns: `true` if the corresponding upstream publishers of each zip publisher are equal, `false` otherwise.
extension Publishers.Zip3 : Equatable where A : Equatable, B : Equatable, C : Equatable {
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (lhs: Publishers.Zip3<A, B, C>, rhs: Publishers.Zip3<A, B, C>) -> Bool {
return lhs.a == rhs.a && lhs.b == rhs.b && lhs.c == rhs.c
}
}
/// Returns a Boolean value that indicates whether two publishers are equivalent.
///
/// - Parameters:
/// - lhs: A zip publisher to compare for equality.
/// - rhs: Another zip publisher to compare for equality.
/// - Returns: `true` if the corresponding upstream publishers of each zip publisher are equal, `false` otherwise.
extension Publishers.Zip4 : Equatable where A : Equatable, B : Equatable, C : Equatable, D : Equatable {
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (lhs: Publishers.Zip4<A, B, C, D>, rhs: Publishers.Zip4<A, B, C, D>) -> Bool {
return lhs.a == rhs.a && lhs.b == rhs.b && lhs.c == rhs.c && lhs.d == rhs.d
}
}
extension Publishers {
/// A publisher created by applying the zip function to three upstream publishers.
public struct Zip3<A, B, C> : Publisher where A : Publisher, B : Publisher, C : Publisher, A.Failure == B.Failure, B.Failure == C.Failure {
/// The kind of values published by this publisher.
public typealias Output = (A.Output, B.Output, C.Output)
/// The kind of errors this publisher might publish.
///
/// Use `Never` if this `Publisher` does not publish errors.
public typealias Failure = A.Failure
public let a: A
public let b: B
public let c: C
public init(_ a: A, _ b: B, _ c: C) {
self.a = a
self.b = b
self.c = c
}
/// This function is called to attach the specified `Subscriber` to this `Publisher` by `subscribe(_:)`
///
/// - SeeAlso: `subscribe(_:)`
/// - Parameters:
/// - subscriber: The subscriber to attach to this `Publisher`.
/// once attached it can begin to receive values.
public func receive<S>(subscriber: S) where S : Subscriber, C.Failure == S.Failure, S.Input == (A.Output, B.Output, C.Output) {
self.a.zip(self.b).zip(self.c)
.map {
($0.0, $0.1, $1)
}
.receive(subscriber: subscriber)
}
}
/// A publisher created by applying the zip function to four upstream publishers.
public struct Zip4<A, B, C, D> : Publisher where A : Publisher, B : Publisher, C : Publisher, D : Publisher, A.Failure == B.Failure, B.Failure == C.Failure, C.Failure == D.Failure {
/// The kind of values published by this publisher.
public typealias Output = (A.Output, B.Output, C.Output, D.Output)
/// The kind of errors this publisher might publish.
///
/// Use `Never` if this `Publisher` does not publish errors.
public typealias Failure = A.Failure
public let a: A
public let b: B
public let c: C
public let d: D
public init(_ a: A, _ b: B, _ c: C, _ d: D) {
self.a = a
self.b = b
self.c = c
self.d = d
}
/// This function is called to attach the specified `Subscriber` to this `Publisher` by `subscribe(_:)`
///
/// - SeeAlso: `subscribe(_:)`
/// - Parameters:
/// - subscriber: The subscriber to attach to this `Publisher`.
/// once attached it can begin to receive values.
public func receive<S>(subscriber: S) where S : Subscriber, D.Failure == S.Failure, S.Input == (A.Output, B.Output, C.Output, D.Output) {
self.a.zip(self.b).zip(self.c).zip(self.d)
.map {
($0.0.0, $0.0.1, $0.1, $1)
}
.receive(subscriber: subscriber)
}
}
}
| 54.783069 | 339 | 0.622754 |
28ed79004621c1b9baa8e82f0b78218090748d0d | 2,103 | //
// MIT License
//
// Copyright (c) 2020 Rotoscope GmbH
//
// 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 MediaType {
public enum VideoSubtype: String {
case avi = "x-msvideo"
case h261 = "H261"
case h263 = "H263"
case h264 = "H264"
case h265 = "H265"
case jpeg = "JPEG"
case jpeg2000 = "jpeg2000"
case mp4 = "mp4"
case mpeg = "mpeg"
case mpeg4Generic = "mpeg4-generic"
case ogg = "ogg"
case quicktime = "quicktime"
case raw = "raw"
case vp8 = "VP8"
case webm = "webm"
}
}
// MARK: -
extension MediaType {
/// Returns an text media type with the specified subtype.
///
/// - parameters:
/// - subtype: An text subtype.
public static func video(_ subtype: VideoSubtype) -> MediaType {
return video(subtype.rawValue)
}
/// Returns an text media type with the specified subtype string.
///
/// - parameters:
/// - subtype: An text subtype string.
public static func video(_ subtype: String) -> MediaType {
return MediaType(type: "video", subtype: subtype)
}
}
| 32.859375 | 81 | 0.694246 |
90c34bfce52471a1859255176cd3756e0269188a | 2,194 | //
// NewsTableViewController.swift
// GitHubKit
//
// Created by wujianguo on 16/7/21.
//
//
import UIKit
import GitHubKit
extension String {
static var newsTitle: String {
return NSLocalizedString("News", comment: "")
}
}
class NewsTableViewController: UITableViewController {
override init(style: UITableViewStyle) {
super.init(style: style)
tabBarItem = UITabBarItem(title: String.newsTitle, image: UIImage(named: "news"), tag: 0)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
title = String.newsTitle
refreshControl = UIRefreshControl()
refreshControl?.addTarget(self, action: #selector(refresh), forControlEvents: .ValueChanged)
refreshControl?.beginRefreshing()
tableView.dataSource = dataSource
tableView.registerClass(EventTableViewCell.self, forCellReuseIdentifier: EventTableViewCell.cellIdentifier)
dataSource.refresh(tableView)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(NewsTableViewController.handleCurrentUserInfoNotification(_:)), name: GitHubCurrentUserInfoNotificationName, object: nil)
}
func handleCurrentUserInfoNotification(notification: NSNotification) {
dataSource.firstRequest = GitHubKit.userReceivedEventsRequest(GitHubKit.currentUser!.login!)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self, name: GitHubCurrentUserInfoNotificationName, object: nil)
}
lazy var dataSource: EventsTableViewDataSource = {
var request: AuthorizationRequest?
if let user = GitHubKit.currentUser {
request = GitHubKit.userReceivedEventsRequest(GitHubKit.currentUser!.login!)
} else {
request = GitHubKit.publicEventsRequest()
}
let ds = EventsTableViewDataSource(cellIdentifier: EventTableViewCell.cellIdentifier, refreshable: self.refreshControl!, firstRequest: request!)
return ds
}()
func refresh() {
dataSource.refresh(tableView)
}
}
| 33.242424 | 204 | 0.704193 |
c12c932e9eb2237bb94a2b30aa946adfc4fca768 | 10,272 | //
// EpisodeCollectionViewCell.swift
// ShowTracker
//
// Created by Roman Madyanov on 16/11/2018.
// Copyright © 2018 Roman Madyanov. All rights reserved.
//
import UIKit
import Toolkit
protocol EpisodeCollectionViewCellDelegate: AnyObject
{
func didTapViewButton(in episodeCollectionViewCell: EpisodeCollectionViewCell)
}
final class EpisodeCollectionViewCell: UICollectionViewCell
{
weak var delegate: EpisodeCollectionViewCellDelegate?
var model: Episode? {
didSet {
if model != oldValue {
stillImageView.setImage(with: model?.stillURL,
placeholderURL: model?.show?.value.backdropURL ?? model?.show?.value.posterURL)
}
seasonAndEpisodeLabel.text = "S%02dE%02d".localized(comment: "Season & episode number",
model?.seasonNumber ?? 0,
model?.number ?? 0)
nameLabel.text = model?.name
overviewText.text = model?.overview
isViewed = model?.canView == true ? model?.isViewed == true : nil
if let localizedAirDate = model?.localizedAirDate {
airDateContainerView.isHidden = false
airDateLabel.text = localizedAirDate
} else {
airDateContainerView.isHidden = true
}
}
}
private lazy var contentStackView: UIStackView = {
let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .vertical
stackView.spacing = .standardSpacing * 2
return stackView
}()
private lazy var stillImageView: CachedImageView = {
let cachedImageView = CachedImageView()
cachedImageView.translatesAutoresizingMaskIntoConstraints = false
cachedImageView.backgroundColor = .clear
cachedImageView.layer.cornerRadius = .standardSpacing
cachedImageView.layer.masksToBounds = true
cachedImageView.contentMode = .scaleAspectFill
return cachedImageView
}()
private lazy var headerStackView: UIStackView = {
let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.spacing = .standardSpacing
stackView.alignment = .center
return stackView
}()
private lazy var nameStackView: UIStackView = {
let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .vertical
stackView.spacing = .standardSpacing / 2
return stackView
}()
private lazy var seasonAndEpisodeLabel: UILabel = {
let label = UILabel()
label.setTextStyle(.title3)
label.setContentCompressionResistancePriority(.highest, for: .vertical)
return label
}()
private lazy var nameLabel: UILabel = {
let label = UILabel()
label.setTextStyle(.headline)
label.setContentCompressionResistancePriority(.highest, for: .vertical)
return label
}()
private lazy var buttonContainerView = UIView()
private lazy var viewButton: Button = {
let button = Button()
button.translatesAutoresizingMaskIntoConstraints = false
button.alpha = 0
button.highlightedAlpha = 0.5
button.layer.borderWidth = 1
button.layer.cornerRadius = .standardSpacing
button.setImage(UIImage(named: "eye-20"), for: .normal)
button.addTarget(self, action: #selector(didTapViewButton), for: .touchUpInside)
return button
}()
private lazy var unseeButton: Button = {
let button = Button()
button.translatesAutoresizingMaskIntoConstraints = false
button.alpha = 0
button.highlightedAlpha = 0.5
button.setImage(UIImage(named: "check-20"), for: .normal)
return button
}()
private lazy var airDateContainerView: UIView = {
let view = UIView()
view.layer.cornerRadius = .standardSpacing / 2
return view
}()
private lazy var airDateStacKView: UIStackView = {
let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.alignment = .center
stackView.spacing = 6
return stackView
}()
private lazy var airDateImageView: UIImageView = {
let imageView = UIImageView(image: UIImage(named: "clock-18"))
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.setContentHuggingPriority(.required, for: .horizontal)
imageView.setContentCompressionResistancePriority(.required, for: .horizontal)
imageView.setContentCompressionResistancePriority(.highest, for: .vertical)
return imageView
}()
private lazy var airDateLabel: UILabel = {
let label = UILabel()
label.setTextStyle(.body)
return label
}()
private lazy var overviewText: CollapsedText = {
let collapsedText = CollapsedText()
collapsedText.onTapReadMoreButton = { [weak self] in
guard let self = self else {
return
}
UIView.animate(withDuration: 0.3) {
self.contentStackView.layoutIfNeeded()
UIView.animate(withDuration: 0.3) {
if self.stillImageView.alpha == 0 {
self.stillImageView.alpha = 1
} else if self.stillImageView.frame.height < self.stillImageView.layer.cornerRadius * 2 {
self.stillImageView.alpha = 0
}
}
}
}
return collapsedText
}()
private var isViewed: Bool? {
didSet {
let scaledTransform = CGAffineTransform.identity.scaledBy(x: 0.01, y: 0.01)
viewButton.layer.removeAllAnimations()
unseeButton.layer.removeAllAnimations()
UIView.animate(
withDuration: 0.3,
delay: 0,
options: .allowUserInteraction,
animations: {
if self.isViewed == true {
self.viewButton.alpha = 0
self.unseeButton.alpha = 1
self.viewButton.transform = scaledTransform
self.unseeButton.transform = .identity
} else if self.isViewed == false {
self.viewButton.alpha = 1
self.unseeButton.alpha = 0
self.viewButton.transform = .identity
self.unseeButton.transform = scaledTransform
} else {
self.viewButton.alpha = 0
self.unseeButton.alpha = 0
self.viewButton.transform = scaledTransform
self.unseeButton.transform = scaledTransform
}
},
completion: nil
)
}
}
private lazy var buttonSize = CGSize(width: .tappableSize, height: .tappableSize)
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(contentStackView)
contentStackView.addArrangedSubview(stillImageView)
contentStackView.addArrangedSubview(headerStackView)
headerStackView.addArrangedSubview(nameStackView)
nameStackView.addArrangedSubview(seasonAndEpisodeLabel)
nameStackView.addArrangedSubview(nameLabel)
headerStackView.addArrangedSubview(buttonContainerView)
buttonContainerView.addSubview(viewButton)
buttonContainerView.addSubview(unseeButton)
contentStackView.addArrangedSubview(airDateContainerView)
airDateContainerView.addSubview(airDateStacKView)
airDateStacKView.addArrangedSubview(airDateImageView)
airDateStacKView.addArrangedSubview(airDateLabel)
contentStackView.addArrangedSubview(overviewText)
airDateStacKView.snap(insets: UIEdgeInsets(.standardSpacing * 1.5), priority: .highest)
buttonContainerView.size(buttonSize)
unseeButton.snap()
NSLayoutConstraint.activate([
contentStackView.leftAnchor.constraint(equalTo: contentView.leftAnchor),
contentStackView.rightAnchor.constraint(equalTo: contentView.rightAnchor),
contentStackView.bottomAnchor.constraint(lessThanOrEqualTo: contentView.bottomAnchor),
stillImageView.heightAnchor.constraint(lessThanOrEqualTo: stillImageView.widthAnchor, multiplier: 0.4),
])
NSLayoutConstraint.activate([
contentStackView.topAnchor.constraint(equalTo: contentView.topAnchor),
], priority: .highest - 1)
NSLayoutConstraint.activate([
stillImageView.heightAnchor.constraint(equalTo: stillImageView.widthAnchor, multiplier: 0.4),
], priority: .defaultHigh)
startListenForThemeChange()
viewButton.snap()
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareForReuse() {
super.prepareForReuse()
overviewText.isCollapsed = true
stillImageView.alpha = 1
}
}
extension EpisodeCollectionViewCell: ThemeChanging
{
@objc
func didChangeTheme() {
seasonAndEpisodeLabel.textColor = Theme.current.primaryForegroundColor
nameLabel.textColor = Theme.current.primaryForegroundColor
unseeButton.tintColor = Theme.current.primaryBrandColor
airDateContainerView.backgroundColor = Theme.current.primaryBrandColor.withAlphaComponent(0.05)
airDateImageView.tintColor = Theme.current.primaryBrandColor
airDateLabel.textColor = Theme.current.primaryBrandColor
viewButton.tintColor = Theme.current.primaryBrandColor
viewButton.layer.borderColor = Theme.current.primaryBrandColor.cgColor
}
}
extension EpisodeCollectionViewCell
{
@objc
private func didTapViewButton() {
delegate?.didTapViewButton(in: self)
}
}
| 36.55516 | 119 | 0.636682 |
f58e38d956926eeb864ed3c0af6784740d50961c | 677 | //
// TimeTemplateEntity+Mapping.swift
// Timmee
//
// Created by Ilya Kharabet on 12.11.17.
// Copyright © 2017 Mesterra. All rights reserved.
//
import class Foundation.NSDate
public extension TimeTemplateEntity {
func map(from timeTemplate: TimeTemplate) {
id = timeTemplate.id
title = timeTemplate.title
hours = timeTemplate.time.flatMap { NSNumber(value: $0.hours) }
minutes = timeTemplate.time.flatMap { NSNumber(value: $0.minutes) }
notification = timeTemplate.notification.flatMap { NSNumber(value: $0.rawValue) }
notificationTime = timeTemplate.notificationTime.flatMap { "\($0.0):\($0.1)" }
}
}
| 29.434783 | 89 | 0.670606 |
9b61b88f852d848b6f31d1a098a516c7786cdc71 | 1,112 | //
// NewsFeedCell.swift
// HackerNewsClone
//
// Created by Chad Rutherford on 9/17/20.
//
import UIKit
protocol ReuseIdentifiable {
static var reuseIdentifier: String { get }
}
protocol NewsFeedCellActions {
func update(_ cell: NewsFeedCell)
}
class NewsFeedCell: UITableViewCell {
lazy var titleLabel = configure(UILabel()) {
addSubview($0)
$0.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
$0.topAnchor.constraint(equalTo: topAnchor, constant: 8),
$0.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 16),
$0.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -8),
$0.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -16)
])
$0.textColor = .label
$0.font = UIFont.systemFont(ofSize: 18, weight: .semibold)
$0.numberOfLines = 0
$0.lineBreakMode = .byWordWrapping
}
var delegate: NewsFeedCellActions!
var post: Post? {
didSet {
delegate.update(self)
}
}
var item: Item?
}
extension NewsFeedCell: ReuseIdentifiable {
static var reuseIdentifier: String {
String(describing: Self.self)
}
}
| 22.24 | 71 | 0.727518 |
296766a48ca7464252bdeebcea436d1402b8ca4b | 3,197 | // The MIT License (MIT)
// Copyright (c) 2016 Erik Little
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without
// limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
// Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
// Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
// BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
// EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
import Foundation
/// Represents the level of verbosity for the logger.
public enum DiscordLogLevel {
/// Log nothing.
case none
/// Log connecting, disconnecting, events (but not content), etc.
case info
/// Log content of events.
case verbose
/// Log everything.
case debug
}
/// Declares that a type will act as a logger.
public protocol DiscordLogger {
// MARK: Properties
/// Whether to log or not.
var level: DiscordLogLevel { get set }
// MARK: Methods
/// Normal log messages.
func log( _ message: @autoclosure () -> String, type: String)
/// More info on log messages.
func verbose(_ message: @autoclosure () -> String, type: String)
/// Debug messages.
func debug(_ message: @autoclosure () -> String, type: String)
/// Error Messages.
func error(_ message: @autoclosure () -> String, type: String)
}
public extension DiscordLogger {
/// Normal log messages.
func log(_ message: @autoclosure () -> String, type: String) {
guard level == .info || level == .verbose || level == .debug else { return }
abstractLog("LOG", message: message(), type: type)
}
/// More info on log messages.
func verbose(_ message: @autoclosure () -> String, type: String) {
guard level == .verbose || level == .debug else { return }
abstractLog("VERBOSE", message: message(), type: type)
}
/// Debug messages.
func debug(_ message: @autoclosure () -> String, type: String) {
guard level == .debug else { return }
abstractLog("DEBUG", message: message(), type: type)
}
/// Error Messages.
func error(_ message: @autoclosure () -> String, type: String) {
abstractLog("ERROR", message: message(), type: type)
}
private func abstractLog(_ logType: String, message: String, type: String) {
NSLog("\(logType): \(type): \(message)")
}
}
class DefaultDiscordLogger : DiscordLogger {
static var Logger: DiscordLogger = DefaultDiscordLogger()
var level = DiscordLogLevel.none
}
| 35.131868 | 119 | 0.677823 |
1ee1ee916e9299c529cbf4c56ce311a1a273590c | 34,548 | import Alamofire
import UIKit
final class DataService: NetworkService {
static let shared = DataService()
private override init() {
super.init()
}
}
extension DataService: DataServiceInput {
// MARK: Settings
func changeName(newName: String,
completion: @escaping (SingleResult<NetworkError>) -> Void) {
guard let login = getUserLogin() else { return }
let parametrs: [String: String] =
["login": login,
"new_name": newName,
"apikey": getApiKey()]
let url = getBaseURL() + "changeName"
var result = SingleResult<NetworkError>()
let request = AF.request(url, method: .post, parameters: parametrs)
guard NetworkReachabilityManager()?.isReachable ?? false else {
result.error = .networkNotReachable
completion(result)
return
}
request.response { response in
switch response.result {
case .success:
guard let statusCode = response.response?.statusCode else {
result.error = .unknownError
completion(result)
return
}
switch statusCode {
case ResponseCode.success.code:
completion(result)
case ResponseCode.error.code:
result.error = .networkNotReachable
completion(result)
return
default:
result.error = .unknownError
completion(result)
return
}
case .failure(let error):
if error.isInvalidURLError {
result.error = .connectionToServerError
} else {
result.error = .unknownError
}
}
}
}
func changePassword(newPassword: Int) {
}
func changePhoto(newPhotoData: Data,
completion: @escaping (Result<ResponseEditString, NetworkError>) -> Void) {
guard let user = getUserLogin() else { return }
let parameters: [String: String] = [
"login": "\(user)",
"apikey": getApiKey()
]
var result = Result<ResponseEditString, NetworkError>()
let url = getBaseURL() + "changeAvatar"
guard NetworkReachabilityManager()?.isReachable ?? false else {
result.error = .networkNotReachable
completion(result)
return
}
_ = AF.upload(multipartFormData: { multipartFormData in
multipartFormData.append(newPhotoData, withName: "file", fileName: "file.jpg", mimeType: "image/jpg")
for (key, value) in parameters {
if let valueData = value.data(using: String.Encoding.utf8) {
multipartFormData.append(valueData, withName: key)
}
}
},
to: url).responseDecodable(of: [ResponseEditString].self) { response in
switch response.result {
case .success(let url):
result.data = url.first
case .failure(let error):
if error.isInvalidURLError {
result.error = .connectionToServerError
} else {
result.error = .unknownError
}
}
completion(result)
}
}
// MARK: Wardrobe
func getUserWardrobes(completion: @escaping (Result<[WardrobeRaw], NetworkError>) -> Void) {
guard let login = getUserLogin() else { return }
let url = getBaseURL() + "getWardrobes?login=\(login)&apikey=\(getApiKey())"
let request = AF.request(url)
var result = Result<[WardrobeRaw], NetworkError>()
guard NetworkReachabilityManager()?.isReachable ?? false else {
result.error = .networkNotReachable
completion(result)
return
}
request.responseDecodable(of: [WardrobeRaw].self) { response in
switch response.result {
case .success(let wardrobe):
result.data = wardrobe
case .failure(let error):
if error.isInvalidURLError {
result.error = .connectionToServerError
} else {
result.error = .unknownError
}
}
completion(result)
}
}
func addWardrobe(login: String,
name: String,
description: String,
imageData: Data?,
completion: @escaping (SingleResult<NetworkError>) -> Void) {
let parameters: [String: String] = [
"login": "\(login)",
"wardrobe_name": "\(name)",
"wardrobe_description": "\(description)",
"apikey": "\(getApiKey())"
]
let url = getBaseURL() + "createWardrobe"
var result = SingleResult<NetworkError>()
guard NetworkReachabilityManager()?.isReachable ?? false else {
result.error = .networkNotReachable
completion(result)
return
}
_ = AF.upload(multipartFormData: { multipartFormData in
if let data = imageData {
multipartFormData.append(data, withName: "file", fileName: "file.jpg", mimeType: "image/jpg")
}
for (key, value) in parameters {
if let valueData = value.data(using: String.Encoding.utf8) {
multipartFormData.append(valueData, withName: key)
}
}
}, to: url).response(completionHandler: { (response) in
switch response.result {
case .success:
guard let statusCode = response.response?.statusCode else {
result.error = .unknownError
completion(result)
return
}
switch statusCode {
case ResponseCode.success.code:
completion(result)
case ResponseCode.error.code:
result.error = .networkNotReachable
completion(result)
return
default:
result.error = .unknownError
completion(result)
return
}
case .failure(let error):
if error.isInvalidURLError {
result.error = .connectionToServerError
} else {
result.error = .unknownError
}
completion(result)
}
})
}
func deleteWardrobe(with id: Int,
completion: @escaping (SingleResult<NetworkError>) -> Void) {
let url = getBaseURL() + "deleteWardrobe?wardrobe_id=\(id)&apikey=\(getApiKey())"
var result = SingleResult<NetworkError>()
guard NetworkReachabilityManager()?.isReachable ?? false else {
result.error = .networkNotReachable
completion(result)
return
}
let request = AF.request(url)
request.response { response in
switch response.result {
case .success:
guard let statusCode = response.response?.statusCode else {
result.error = .unknownError
completion(result)
return
}
switch statusCode {
case ResponseCode.success.code:
completion(result)
case ResponseCode.error.code:
result.error = .networkNotReachable
completion(result)
return
default:
result.error = .unknownError
completion(result)
return
}
case .failure(let error):
if error.isInvalidURLError {
result.error = .connectionToServerError
} else {
result.error = .unknownError
}
}
}
}
// MARK: Wardrobe detail
func deleteLook(lookId: Int,
completion: @escaping (SingleResult<NetworkError>) -> Void) {
let url = getBaseURL() + "removeLook?look_id=\(lookId)&apikey=\(getApiKey())"
var result = SingleResult<NetworkError>()
guard NetworkReachabilityManager()?.isReachable ?? false else {
result.error = .networkNotReachable
completion(result)
return
}
let request = AF.request(url)
request.response { response in
switch response.result {
case .success:
guard let statusCode = response.response?.statusCode else {
result.error = .unknownError
completion(result)
return
}
switch statusCode {
case ResponseCode.success.code:
completion(result)
case ResponseCode.error.code:
result.error = .networkNotReachable
completion(result)
return
default:
result.error = .unknownError
completion(result)
return
}
case .failure(let error):
if error.isInvalidURLError {
result.error = .connectionToServerError
} else {
result.error = .unknownError
}
}
}
}
// MARK: Look screen
func getAllLookClothes(with id: Int,
completion: @escaping (Result<LookRaw, NetworkError>) -> Void) {
let request = AF.request(getBaseURL() + "getLook?" + "look_id=\(id)" + "&apikey=\(getApiKey())")
var result = Result<LookRaw, NetworkError>()
guard NetworkReachabilityManager()?.isReachable ?? false else {
result.error = .networkNotReachable
completion(result)
return
}
request.responseDecodable(of: [LookRaw].self) { (response) in
switch response.result {
case .success(let data):
guard let statusCode = response.response?.statusCode else {
result.error = .unknownError
completion(result)
return
}
switch statusCode {
case ResponseCode.success.code:
result.data = data.first
case ResponseCode.error.code:
result.error = .lookNotExist
completion(result)
return
default:
result.error = .unknownError
completion(result)
return
}
case .failure(let error):
if error.isInvalidURLError {
result.error = .connectionToServerError
} else {
result.error = .unknownError
}
}
completion(result)
}
}
func deleteItemFromLook(lookID: Int,
itemID: Int,
completion: @escaping (SingleResult<NetworkError>) -> Void) {
var result = SingleResult<NetworkError>()
guard NetworkReachabilityManager()?.isReachable ?? false else {
result.error = .networkNotReachable
completion(result)
return
}
let request = AF.request("\(getBaseURL())" + "deleteItemFromLook?look_id=\(lookID)&item_id=\(itemID)&apikey=\(getApiKey())")
request.response { (response) in
switch response.result {
case .success:
guard let statusCode = response.response?.statusCode else {
result.error = .unknownError
completion(result)
return
}
switch statusCode {
case ResponseCode.success.code:
completion(result)
case ResponseCode.error.code:
result.error = .networkNotReachable
completion(result)
return
default:
result.error = .unknownError
completion(result)
return
}
case .failure(let error):
if error.isInvalidURLError {
result.error = .connectionToServerError
} else {
result.error = .unknownError
}
completion(result)
}
}
}
func createLook(wardrobeID: Int,
name: String,
imageData: Data?,
choosedItems: [Int],
completion: @escaping (SingleResult<NetworkError>) -> Void) {
var result = SingleResult<NetworkError>()
guard NetworkReachabilityManager()?.isReachable ?? false else {
result.error = .networkNotReachable
completion(result)
return
}
let parameters: [String: String] = [
"look_name": name,
"wardrobe_id": "\(wardrobeID)",
"items_ids": "\(choosedItems)",
"apikey": "\(getApiKey())"
]
_ = AF.upload(multipartFormData: { multipartFormData in
for (key, value) in parameters {
if let valueData = value.data(using: String.Encoding.utf8) {
multipartFormData.append(valueData, withName: key)
}
}
if let data = imageData {
multipartFormData.append(data, withName: "file", fileName: "file.jpg", mimeType: "image/jpg")
}
},
to: "\(getBaseURL())" + "createLook").response { (response) in
switch response.result {
case .success:
guard let statusCode = response.response?.statusCode else {
result.error = .unknownError
completion(result)
return
}
switch statusCode {
case ResponseCode.success.code:
()
case ResponseCode.error.code:
result.error = .userAlreadyExist
completion(result)
return
default:
result.error = .unknownError
completion(result)
return
}
case .failure(let error):
if error.isInvalidURLError {
result.error = .connectionToServerError
} else {
result.error = .unknownError
}
completion(result)
}
completion(result)
}
}
func updateLook(lookID: Int,
itemIDs: [Int],
completion: @escaping (SingleResult<NetworkError>) -> Void) {
var result = SingleResult<NetworkError>()
guard NetworkReachabilityManager()?.isReachable ?? false else {
result.error = .networkNotReachable
completion(result)
return
}
let parameters: [String: String] = [
"items_ids": "\(itemIDs)",
"look_id": "\(lookID)",
"apikey": "\(getApiKey())"
]
let request = AF.request("\(getBaseURL())" + "updateLookItems", method: .post, parameters: parameters)
request.response { (response) in
switch response.result {
case .success:
guard let statusCode = response.response?.statusCode else {
result.error = .unknownError
completion(result)
return
}
switch statusCode {
case ResponseCode.success.code:
completion(result)
case ResponseCode.error.code:
result.error = .networkNotReachable
completion(result)
return
default:
result.error = .unknownError
completion(result)
return
}
case .failure(let error):
if error.isInvalidURLError {
result.error = .connectionToServerError
} else {
result.error = .unknownError
}
completion(result)
}
}
}
func getLooks(for wardrobeId: Int,
completion: @escaping (Result<[WardrobeDetailLookRaw], NetworkError>) -> Void) {
let request = AF.request(getBaseURL() + "getLookByWardrobe?" + "wardrobe_id=\(wardrobeId)" + "&apikey=\(getApiKey())")
var result = Result<[WardrobeDetailLookRaw], NetworkError>()
guard NetworkReachabilityManager()?.isReachable ?? false else {
result.error = .networkNotReachable
completion(result)
return
}
request.responseDecodable(of: [WardrobeDetailLookRaw].self) { (response) in
switch response.result {
case .success(let data):
guard let statusCode = response.response?.statusCode else {
result.error = .unknownError
completion(result)
return
}
switch statusCode {
case ResponseCode.success.code:
result.data = data
case ResponseCode.error.code:
result.error = .lookNotExist
completion(result)
return
default:
result.error = .unknownError
completion(result)
return
}
case .failure(let error):
if error.isInvalidURLError {
result.error = .connectionToServerError
} else {
result.error = .unknownError
}
}
completion(result)
}
}
// Словарь новых значений
func deleteClothesFromLook(with id: [Int]) {
}
// MARK: Wardrobe users
func getWardroeUsers(with wardrobeId: Int,
completion: @escaping (Result<[WardrobeUserRaw], NetworkError>) -> Void) {
let url = getBaseURL() + "getWardrobeUsers"
+ "?wardrobe_id=" + "\(wardrobeId)"
+ "&apikey=\(getApiKey())"
var result = Result<[WardrobeUserRaw], NetworkError>()
let request = AF.request(url)
request.responseDecodable(of: [WardrobeUserRaw].self) { (response) in
switch response.result {
case .success(let data):
guard let statusCode = response.response?.statusCode else {
result.error = .unknownError
completion(result)
return
}
switch statusCode {
case ResponseCode.success.code:
result.data = data
case ResponseCode.error.code:
result.error = .lookNotExist
completion(result)
return
default:
result.error = .unknownError
completion(result)
return
}
case .failure(let error):
if error.isInvalidURLError {
result.error = .connectionToServerError
} else {
result.error = .unknownError
}
}
completion(result)
}
}
func addUserToWardrobe(with login: String,
wardobeId: Int,
completion: @escaping (SingleResult<NetworkError>) -> Void) {
guard let userLogin = getUserLogin() else { return }
let url = getBaseURL() + "sendInvite" +
"?my_login=\(userLogin)" +
"&login_to_invite=\(login)" +
"&wardrobe_id=\(wardobeId)" +
"&apikey=\(getApiKey())"
var result = SingleResult<NetworkError>()
let request = AF.request(url)
request.response { response in
switch response.result {
case .success:
guard let statusCode = response.response?.statusCode else {
result.error = .unknownError
completion(result)
return
}
switch statusCode {
case ResponseCode.success.code:
completion(result)
case ResponseCode.error.code:
result.error = .networkNotReachable
completion(result)
return
default:
result.error = .unknownError
completion(result)
return
}
case .failure(let error):
if error.isInvalidURLError {
result.error = .connectionToServerError
} else {
result.error = .unknownError
}
}
}
}
func deleteUserFromWardrobe(wardrobeId: Int,
login: String,
completion: @escaping (SingleResult<NetworkError>) -> Void) {
let url = getBaseURL() + "removeUserFromWardrobe"
+ "?wardrobe_id=\(wardrobeId)"
+ "&remove_login=\(login)"
+ "&apikey=\(getApiKey())"
var result = SingleResult<NetworkError>()
let request = AF.request(url)
request.response { response in
switch response.result {
case .success:
guard let statusCode = response.response?.statusCode else {
result.error = .unknownError
completion(result)
return
}
switch statusCode {
case ResponseCode.success.code:
completion(result)
case ResponseCode.error.code:
result.error = .networkNotReachable
completion(result)
return
default:
result.error = .unknownError
completion(result)
return
}
case .failure(let error):
if error.isInvalidURLError {
result.error = .connectionToServerError
} else {
result.error = .unknownError
}
}
}
}
func wardrobeResponseInvite(inviteId: Int,
response: InviteWardrobeResponse,
completion: @escaping (SingleResult<NetworkError>) -> Void) {
let url = getBaseURL() + "handleInvite"
+ "?inviteId=\(inviteId)"
+ "&accepted=\(response.rawValue)"
+ "&apikey=\(getApiKey())"
var result = SingleResult<NetworkError>()
let request = AF.request(url)
request.response { response in
switch response.result {
case .success:
guard let statusCode = response.response?.statusCode else {
result.error = .unknownError
completion(result)
return
}
switch statusCode {
case ResponseCode.success.code:
completion(result)
case ResponseCode.error.code:
result.error = .networkNotReachable
completion(result)
return
default:
result.error = .unknownError
completion(result)
return
}
case .failure(let error):
if error.isInvalidURLError {
result.error = .connectionToServerError
} else {
result.error = .unknownError
}
}
}
}
func getUserInvites(completion: @escaping (Result<[InviteRaw], NetworkError>) -> Void) {
guard let login = getUserLogin() else { return }
let url = getBaseURL() +
"whoInvitesMe" +
"?login=\(login)&apikey=\(getApiKey())"
let request = AF.request(url)
var result = Result<[InviteRaw], NetworkError>()
guard NetworkReachabilityManager()?.isReachable ?? false else {
result.error = .networkNotReachable
completion(result)
return
}
request.responseDecodable(of: [InviteRaw].self) { response in
switch response.result {
case .success(let invites):
result.data = invites
case .failure(let error):
if error.isInvalidURLError {
result.error = .connectionToServerError
} else {
result.error = .unknownError
}
}
completion(result)
}
}
func newItem(userLogin: String,
name: String,
category: String,
imageData: Data?,
completion: @escaping (SingleResult<NetworkError>) -> Void) {
var result = SingleResult<NetworkError>()
guard NetworkReachabilityManager()?.isReachable ?? false else {
result.error = .networkNotReachable
completion(result)
return
}
let parameters: [String: String] = [
"new_name": "\(name)",
"login": "\(userLogin)",
"type": "\(category)",
"apikey": "\(getApiKey())"
]
_ = AF.upload(multipartFormData: { multipartFormData in
for (key, value) in parameters {
if let valueData = value.data(using: String.Encoding.utf8) {
multipartFormData.append(valueData, withName: key)
}
}
if let data = imageData {
multipartFormData.append(data, withName: "file", fileName: "file.jpg", mimeType: "image/jpg")
}
}, to: getBaseURL() + "addItem").response { (response) in
switch response.result {
case .success:
guard let statusCode = response.response?.statusCode else {
result.error = .unknownError
completion(result)
return
}
switch statusCode {
case ResponseCode.success.code:
()
default:
result.error = .unknownError
completion(result)
return
}
case .failure(let error):
if error.isInvalidURLError {
result.error = .connectionToServerError
} else {
result.error = .unknownError
}
completion(result)
}
completion(result)
}
}
func getAllItems(for login: String,
completion: @escaping (Result<AllItemsRaw, NetworkError>) -> Void) {
let request = AF.request(getBaseURL() + "getAllItems?login=\(login)&apikey=\(getApiKey())")
var result = Result<AllItemsRaw, NetworkError>()
guard NetworkReachabilityManager()?.isReachable ?? false else {
result.error = .networkNotReachable
completion(result)
return
}
request.responseDecodable(of: [AllItemsRaw].self) { (response) in
switch response.result {
case .success(let data):
guard let statusCode = response.response?.statusCode else {
result.error = .unknownError
completion(result)
return
}
switch statusCode {
case ResponseCode.success.code:
result.data = data.first
case ResponseCode.error.code:
result.error = .itemsNotExist
completion(result)
return
default:
result.error = .unknownError
completion(result)
return
}
case .failure(let error):
if error.isInvalidURLError {
result.error = .connectionToServerError
} else {
result.error = .unknownError
}
}
completion(result)
}
}
func getItem(id: Int,
completion: @escaping (Result<EditItemRaw, NetworkError>) -> Void) {
let request = AF.request(getBaseURL() + "getItemById?item_id=\(id)&apikey=\(getApiKey())")
var result = Result<EditItemRaw, NetworkError>()
guard NetworkReachabilityManager()?.isReachable ?? false else {
result.error = .networkNotReachable
completion(result)
return
}
request.responseDecodable(of: [EditItemRaw].self) { (response) in
switch response.result {
case .success(let data):
guard let statusCode = response.response?.statusCode else {
result.error = .unknownError
completion(result)
return
}
switch statusCode {
case ResponseCode.success.code:
result.data = data.first
default:
result.error = .unknownError
completion(result)
return
}
case .failure(let error):
if error.isInvalidURLError {
result.error = .connectionToServerError
} else {
result.error = .unknownError
}
completion(result)
}
completion(result)
}
}
func updateItem(id: Int,
name: String?,
imageData: Data?,
completion: @escaping (SingleResult<NetworkError>) -> Void) {
var result = SingleResult<NetworkError>()
guard NetworkReachabilityManager()?.isReachable ?? false else {
result.error = .networkNotReachable
completion(result)
return
}
let parameters: [String: String] = [
"item_id": "\(id)",
"apikey": "\(getApiKey())"
]
_ = AF.upload(multipartFormData: { multipartFormData in
for (key, value) in parameters {
if let valueData = value.data(using: String.Encoding.utf8) {
multipartFormData.append(valueData, withName: key)
}
}
if let newName = name,
let nameData = newName.data(using: String.Encoding.utf8) {
multipartFormData.append(nameData, withName: "new_name")
}
if let data = imageData {
multipartFormData.append(data, withName: "file", fileName: "file.jpg", mimeType: "image/jpg")
}
}, to: getBaseURL() + "updateItem").response { (response) in
switch response.result {
case .success:
guard let statusCode = response.response?.statusCode else {
result.error = .unknownError
completion(result)
return
}
switch statusCode {
case ResponseCode.success.code:
()
default:
result.error = .unknownError
completion(result)
return
}
case .failure(let error):
if error.isInvalidURLError {
result.error = .connectionToServerError
} else {
result.error = .unknownError
}
completion(result)
}
completion(result)
}
}
func removeItem(id: Int,
completion: @escaping (SingleResult<NetworkError>) -> Void) {
let request = AF.request(getBaseURL() + "removeItem?item_id=\(id)&apikey=\(getApiKey())")
var result = SingleResult<NetworkError>()
guard NetworkReachabilityManager()?.isReachable ?? false else {
result.error = .networkNotReachable
completion(result)
return
}
request.response { response in
switch response.result {
case .success:
guard let statusCode = response.response?.statusCode else {
result.error = .unknownError
completion(result)
return
}
switch statusCode {
case ResponseCode.success.code:
completion(result)
default:
result.error = .unknownError
completion(result)
return
}
case .failure(let error):
if error.isInvalidURLError {
result.error = .connectionToServerError
} else {
result.error = .unknownError
}
completion(result)
}
completion(result)
}
}
func setNewUserName(newName: String) {
UserDefaults.standard.setValue(newName, forKey: Constants.userNameKey)
}
}
| 34.037438 | 132 | 0.486801 |
3a959f446cf9f2531363713bc33baf487c672bd7 | 5,962 |
import Foundation
import Alamofire
import WoWonderTimelineSDK
class TwoFactorManager {
static let instance = TwoFactorManager()
func verifyCode (code : String, UserID : String, completionBlock : @escaping (_ Success:TwoFactorModel.TwoFactorSuccessModel?, _ AuthError : TwoFactorModel.TwoFactorErrorModel?, Error?)->()) {
let params = [APIClient.Params.serverKey : APIClient.SERVER_KEY.Server_Key,APIClient.Params.code : code, APIClient.Params.userId :UserID]
AF.request(APIClient.TwoFactorAuthentication.TwoFactorAuthApi, method: .post, parameters: params, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
if response.value != nil {
guard let res = response.value as? [String:Any] else {return}
guard let apiStatusCode = res["api_status"] as? Any else {return}
let apiCode = apiStatusCode as? Int
if apiCode == 200 {
guard let allData = try? JSONSerialization.data(withJSONObject: response.value, options: [])else {return}
guard let result = try? JSONDecoder().decode(TwoFactorModel.TwoFactorSuccessModel.self, from: allData) else {return}
completionBlock(result,nil,nil)
}
else {
guard let allData = try? JSONSerialization.data(withJSONObject: response.value, options: [])else {return}
guard let result = try? JSONDecoder().decode(TwoFactorModel.TwoFactorErrorModel.self, from: allData) else {return}
completionBlock(nil,result,nil)
}
}
else {
print(response.error?.localizedDescription)
completionBlock(nil,nil,response.error)
}
}
}
func updateTwoFactor ( completionBlock : @escaping (_ Success:UpdateTwoFactorModel.UpdateTwoFactorSuccessModel?, _ AuthError : UpdateTwoFactorModel.UpdateTwoFactorErrorModel?, Error?)->()) {
let params = [APIClient.Params.serverKey : APIClient.SERVER_KEY.Server_Key]
let access_token = "\("?")\("access_token")\("=")\(UserData.getAccess_Token()!)"
AF.request(APIClient.UpdateTwoFactor.updateTwoFactorApi + access_token, method: .post, parameters: params, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
if response.value != nil {
guard let res = response.value as? [String:Any] else {return}
guard let apiStatusCode = res["api_status"] as? Any else {return}
let apiCode = apiStatusCode as? Int
if apiCode == 200 {
guard let allData = try? JSONSerialization.data(withJSONObject: response.value, options: [])else {return}
guard let result = try? JSONDecoder().decode(UpdateTwoFactorModel.UpdateTwoFactorSuccessModel.self, from: allData) else {return}
completionBlock(result,nil,nil)
}
else {
guard let allData = try? JSONSerialization.data(withJSONObject: response.value, options: [])else {return}
guard let result = try? JSONDecoder().decode(UpdateTwoFactorModel.UpdateTwoFactorErrorModel.self, from: allData) else {return}
completionBlock(nil,result,nil)
}
}
else {
print(response.error?.localizedDescription)
completionBlock(nil,nil,response.error)
}
}
}
func updateVerifyTwoFactor ( code:String,Type:String,completionBlock : @escaping (_ Success:UpdateTwoFactorModel.UpdateTwoFactorSuccessModel?, _ AuthError : UpdateTwoFactorModel.UpdateTwoFactorErrorModel?, Error?)->()) {
let params = [APIClient.Params.serverKey : APIClient.SERVER_KEY.Server_Key,
APIClient.Params.code:code,
APIClient.Params.type:Type,
]
let access_token = "\("?")\("access_token")\("=")\(UserData.getAccess_Token()!)"
AF.request(APIClient.UpdateTwoFactor.updateTwoFactorApi + access_token, method: .post, parameters: params, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
if response.value != nil {
guard let res = response.value as? [String:Any] else {return}
guard let apiStatusCode = res["api_status"] as? Any else {return}
let apiCode = apiStatusCode as? Int
if apiCode == 200 {
guard let allData = try? JSONSerialization.data(withJSONObject: response.value, options: [])else {return}
guard let result = try? JSONDecoder().decode(UpdateTwoFactorModel.UpdateTwoFactorSuccessModel.self, from: allData) else {return}
completionBlock(result,nil,nil)
}
else {
guard let allData = try? JSONSerialization.data(withJSONObject: response.value, options: [])else {return}
guard let result = try? JSONDecoder().decode(UpdateTwoFactorModel.UpdateTwoFactorErrorModel.self, from: allData) else {return}
completionBlock(nil,result,nil)
}
}
else {
print(response.error?.localizedDescription)
completionBlock(nil,nil,response.error)
}
}
}
}
| 49.683333 | 224 | 0.566756 |
8ad1c869eb5e2a6d021e380537472b906bd46f02 | 2,548 | /// Copyright (c) 2021 Razeware LLC
///
/// 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.
///
/// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
/// distribute, sublicense, create a derivative work, and/or sell copies of the
/// Software in any work that is designed, intended, or marketed for pedagogical or
/// instructional purposes related to programming, coding, application development,
/// or information technology. Permission for such use, copying, modification,
/// merger, publication, distribution, sublicensing, creation of derivative works,
/// or sale is expressly withheld.
///
/// This project and source code may use libraries or frameworks that are
/// released under various Open-Source licenses. Use of those libraries and
/// frameworks are governed by their own individual licenses.
///
/// 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 SwiftUI
struct TimerView: View {
@State private var timeRemaining = 3 // 30
@Binding var timerDone: Bool
let timer = Timer.publish(
every: 1,
on: .main,
in: .common)
.autoconnect()
var body: some View {
Text("\(timeRemaining)")
.font(.system(size: 90, design: .rounded))
.padding()
.onReceive(timer) { _ in
if self.timeRemaining > 0 {
self.timeRemaining -= 1
} else {
timerDone = true
}
}
}
}
struct TimerView_Previews: PreviewProvider {
static var previews: some View {
TimerView(timerDone: .constant(false))
.previewLayout(.sizeThatFits)
}
}
| 39.8125 | 83 | 0.715856 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.