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
|
---|---|---|---|---|---|
20039adf4f7c179952b5bcff11391ad542974dab | 1,168 | //
// Created by Kiavash Faisali on 5/13/18.
//
import Foundation
// MARK: - AssociatedValue Protocol
internal protocol AssociatedValue {
func getAssociatedValue<T>(key: UnsafeRawPointer, defaultValue: T?) -> T?
func getAssociatedValue<T>(key: UnsafeRawPointer, defaultValue: T) -> T
func setAssociatedValue<T>(key: UnsafeRawPointer, value: T?, policy: objc_AssociationPolicy)
}
// MARK: - AssociatedValue Protocol Default Implementation
internal extension AssociatedValue {
func getAssociatedValue<T>(key: UnsafeRawPointer, defaultValue: T?) -> T? {
guard let value = objc_getAssociatedObject(self, key) as? T else {
return defaultValue
}
return value
}
func getAssociatedValue<T>(key: UnsafeRawPointer, defaultValue: T) -> T {
guard let value = objc_getAssociatedObject(self, key) as? T else {
return defaultValue
}
return value
}
func setAssociatedValue<T>(key: UnsafeRawPointer, value: T?, policy: objc_AssociationPolicy = .OBJC_ASSOCIATION_RETAIN_NONATOMIC) {
objc_setAssociatedObject(self, key, value, policy)
}
}
| 32.444444 | 135 | 0.680651 |
2096d678a53997379d545c8e555fda050e24ea2d | 1,609 | //
// UpdateUserInput.swift
// test
//
// Created by iandtop on 2020/10/27.
//
import Foundation
public class UpdateUserInput {
public var email: String? = nil
public var unionid: String? = nil
public var openid: String? = nil
public var emailVerified: Bool? = nil
public var phone: String? = nil
public var phoneVerified: Bool? = nil
public var username: String? = nil
public var nickname: String? = nil
public var password: String? = nil
public var photo: String? = nil
public var company: String? = nil
public var browser: String? = nil
public var device: String? = nil
public var oauth: String? = nil
public var tokenExpiredAt: String? = nil
public var loginsCount: Int? = nil
public var lastLogin: String? = nil
public var lastIP: String? = nil
public var blocked: Bool? = nil
public var name: String? = nil
public var givenName: String? = nil
public var familyName: String? = nil
public var middleName: String? = nil
public var profile: String? = nil
public var preferredUsername: String? = nil
public var website: String? = nil
public var gender: String? = nil
public var birthdate: String? = nil
public var zoneinfo: String? = nil
public var locale: String? = nil
public var address: String? = nil
public var formatted: String? = nil
public var streetAddress: String? = nil
public var locality: String? = nil
public var region: String? = nil
public var city: String? = nil
public var province: String? = nil
public var country: String? = nil
}
| 32.18 | 47 | 0.666252 |
3acd18af6ca6d34b1c0cf19bb8a134a3d06b5425 | 6,923 | //
// CometdClient+Parsing.swift
// ZetaPushSwift
//
// Created by Morvan Mikaël on 23/03/2017.
// Copyright © 2017 ZetaPush. All rights reserved.
//
// Adapted from https://github.com/hamin/FayeSwift
import Foundation
import SwiftyJSON
extension CometdClient {
// MARK:
// MARK: Parsing
func parseCometdMessage(_ messages: [JSON]) {
messages.forEach { (message) in
if let channel = message[Bayeux.Channel.rawValue].string {
log.verbose("parseCometdMessage \(channel)")
log.verbose(message)
// Handle Meta Channels
if let metaChannel = BayeuxChannel(rawValue: channel) {
switch(metaChannel) {
case .Handshake:
self.cometdClientId = message[Bayeux.ClientId.rawValue].stringValue
if message[Bayeux.Successful.rawValue].int == 1 {
if message[Bayeux.Ext.rawValue] != JSON.null {
let ext : AnyObject = message[Bayeux.Ext.rawValue].object as AnyObject
self.delegate?.handshakeSucceeded(self, handshakeDict: ext as! NSDictionary)
}
self.cometdConnected = true;
self.connect()
self.subscribeQueuedSubscriptions()
} else {
self.delegate?.handshakeFailed(self)
self.cometdConnected = false;
self.transport?.closeConnection()
self.delegate?.disconnectedFromServer(self)
}
case .Connect:
let advice = message[Bayeux.Advice.rawValue];
let successful = message[Bayeux.Successful.rawValue];
let reconnect = advice[BayeuxAdvice.Reconnect.rawValue].stringValue
if successful.boolValue {
if (reconnect == BayeuxAdviceReconnect.Retry.rawValue) {
self.cometdConnected = true;
self.delegate?.connectedToServer(self)
self.connect()
} else {
self.cometdConnected = false;
}
} else {
self.cometdConnected = false;
self.transport?.closeConnection()
self.delegate?.disconnectedFromServer(self)
if (reconnect == BayeuxAdviceReconnect.Handshake.rawValue) {
self.delegate?.disconnectedAdviceReconnect(self)
}
}
case .Disconnect:
if message[Bayeux.Successful.rawValue].boolValue {
self.cometdConnected = false;
self.transport?.closeConnection()
self.delegate?.disconnectedFromServer(self)
} else {
self.cometdConnected = false;
self.transport?.closeConnection()
self.delegate?.disconnectedFromServer(self)
}
case .Subscribe:
if let success = message[Bayeux.Successful.rawValue].int, success == 1 {
if let subscription = message[Bayeux.Subscription.rawValue].string {
_ = removeChannelFromPendingSubscriptions(subscription)
self.openSubscriptions.append(CometdSubscriptionModel(subscriptionUrl: subscription, clientId: cometdClientId))
self.delegate?.didSubscribeToChannel(self, channel: subscription)
} else {
log.warning("Cometd: Missing subscription for Subscribe")
}
} else {
// Subscribe Failed
if let error = message[Bayeux.Error.rawValue].string,
let subscription = message[Bayeux.Subscription.rawValue].string {
_ = removeChannelFromPendingSubscriptions(subscription)
self.delegate?.subscriptionFailedWithError(
self,
error: subscriptionError.error(subscription: subscription, error: error)
)
}
}
case .Unsubscibe:
if let subscription = message[Bayeux.Subscription.rawValue].string {
_ = removeChannelFromOpenSubscriptions(subscription)
self.delegate?.didUnsubscribeFromChannel(self, channel: subscription)
} else {
log.warning("Cometd: Missing subscription for Unsubscribe")
}
}
} else {
// Handle Client Channel
if self.isSubscribedToChannel(channel) {
if message[Bayeux.Data.rawValue] != JSON.null {
let data: AnyObject = message[Bayeux.Data.rawValue].object as AnyObject
if let channelBlock = self.channelSubscriptionBlocks[channel] {
for channel in channelBlock {
channel.callback!(data as! NSDictionary)
}
} else {
log.warning("Cometd: Failed to get channel block for : \(channel)")
}
self.delegate?.messageReceived(
self,
messageDict: data as! NSDictionary,
channel: channel
)
} else {
log.warning("Cometd: For some reason data is nil for channel: \(channel)")
}
} else {
log.warning("Cometd: Weird channel that not been set to subscribed: \(channel)")
}
}
} else {
log.warning("Cometd: Missing channel for \(message)")
}
}
}
}
| 50.532847 | 143 | 0.443594 |
9bce0dbaa29e788ca091f15daae067322ca38aca | 666 | //
// AppDelegate.swift
// SpeakLine
//
// Created by Andy Ron on 2018/10/5.
// Copyright © 2018 Andy Ron. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
var mainWindowController: MainWindowController?
func applicationDidFinishLaunching(_ aNotification: Notification) {
let mainWindowController = MainWindowController()
mainWindowController.showWindow(self)
self.mainWindowController = mainWindowController
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
}
| 21.483871 | 71 | 0.714715 |
fe9e17aff57007e1ee11a95fa50eb4b5d82d4deb | 1,501 | // RichTextRenderer
import Contentful
extension BlockQuote: RenderableNodeProviding {
public var renderableNode: RenderableNode {
.blockQuote(self)
}
}
extension Heading: RenderableNodeProviding {
public var renderableNode: RenderableNode {
.heading(self)
}
}
extension HorizontalRule: RenderableNodeProviding {
public var renderableNode: RenderableNode {
.horizontalRule(self)
}
}
extension Hyperlink: RenderableNodeProviding {
public var renderableNode: RenderableNode {
.hyperlink(self)
}
}
extension ListItem: RenderableNodeProviding {
public var renderableNode: RenderableNode {
.listItem(self)
}
}
extension OrderedList: RenderableNodeProviding {
public var renderableNode: RenderableNode {
.orderedList(self)
}
}
extension Paragraph: RenderableNodeProviding {
public var renderableNode: RenderableNode {
.paragraph(self)
}
}
extension ResourceLinkBlock: RenderableNodeProviding {
public var renderableNode: RenderableNode {
.resourceLinkBlock(self)
}
}
extension ResourceLinkInline: RenderableNodeProviding {
public var renderableNode: RenderableNode {
.resourceLinkInline(self)
}
}
extension Text: RenderableNodeProviding {
public var renderableNode: RenderableNode {
.text(self)
}
}
extension UnorderedList: RenderableNodeProviding {
public var renderableNode: RenderableNode {
.unorderedList(self)
}
}
| 21.140845 | 55 | 0.716189 |
08c9a144089bc4adf321bcaa043ce2ee8ae0712e | 4,290 | //
// SQLite.swift
// https://github.com/stephencelis/SQLite.swift
// Copyright © 2014-2015 Stephen Celis.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#if SQLITE_SWIFT_STANDALONE
import sqlite3
#elseif SQLITE_SWIFT_SQLCIPHER
import SQLCipher
#elseif COCOAPODS
import CSQLite
#endif
public typealias Star = (Expression<Binding>?, Expression<Binding>?) -> Expression<Void>
public func *(_: Expression<Binding>?, _: Expression<Binding>?) -> Expression<Void> {
return Expression(literal: "*")
}
public protocol _OptionalType {
associatedtype WrappedType
}
extension Optional : _OptionalType {
public typealias WrappedType = Wrapped
}
// let SQLITE_STATIC = unsafeBitCast(0, sqlite3_destructor_type.self)
let SQLITE_TRANSIENT = unsafeBitCast(-1, to: sqlite3_destructor_type.self)
extension String {
func quote(_ mark: Character = "\"") -> String {
let escaped = characters.reduce("") { string, character in
string + (character == mark ? "\(mark)\(mark)" : "\(character)")
}
return "\(mark)\(escaped)\(mark)"
}
func join(_ expressions: [Expressible]) -> Expressible {
var (template, bindings) = ([String](), [Binding?]())
for expressible in expressions {
let expression = expressible.expression
template.append(expression.template)
bindings.append(contentsOf: expression.bindings)
}
return Expression<Void>(template.joined(separator: self), bindings)
}
func infix<T>(_ lhs: Expressible, _ rhs: Expressible, wrap: Bool = true) -> Expression<T> {
let expression = Expression<T>(" \(self) ".join([lhs, rhs]).expression)
guard wrap else {
return expression
}
return "".wrap(expression)
}
func prefix(_ expressions: Expressible) -> Expressible {
return "\(self) ".wrap(expressions) as Expression<Void>
}
func prefix(_ expressions: [Expressible]) -> Expressible {
return "\(self) ".wrap(expressions) as Expression<Void>
}
func wrap<T>(_ expression: Expressible) -> Expression<T> {
return Expression("\(self)(\(expression.expression.template))", expression.expression.bindings)
}
func wrap<T>(_ expressions: [Expressible]) -> Expression<T> {
return wrap(", ".join(expressions))
}
}
func infix<T>(_ lhs: Expressible, _ rhs: Expressible, wrap: Bool = true, function: String = #function) -> Expression<T> {
return function.infix(lhs, rhs, wrap: wrap)
}
func wrap<T>(_ expression: Expressible, function: String = #function) -> Expression<T> {
return function.wrap(expression)
}
func wrap<T>(_ expressions: [Expressible], function: String = #function) -> Expression<T> {
return function.wrap(", ".join(expressions))
}
func transcode(_ literal: Binding?) -> String {
guard let literal = literal else { return "NULL" }
switch literal {
case let blob as Blob:
return blob.description
case let string as String:
return string.quote("'")
case let binding:
return "\(binding)"
}
}
func value<A: Value>(_ v: Binding) -> A {
return A.fromDatatypeValue(v as! A.Datatype) as! A
}
func value<A: Value>(_ v: Binding?) -> A {
return value(v!)
}
| 32.748092 | 121 | 0.680653 |
f57478f62a3fc327b0838bec0bf829b35afcc10a | 44 | let testcase = readLine()
print(testcase!)
| 11 | 25 | 0.727273 |
22595c8667d99fe2d50975be546c0395e80eac36 | 1,150 | //
// SynchronizedResolver.swift
// Swinject
//
// Created by Yoichi Tagaya on 11/23/15.
// Copyright © 2015 Swinject Contributors. All rights reserved.
//
internal final class SynchronizedResolver {
internal let container: Container
internal init(container: Container) {
self.container = container
}
}
extension SynchronizedResolver: _Resolver {
// swiftlint:disable:next identifier_name
internal func _resolve<Service, Factory>(name: String?, option: ServiceKeyOption?, invoker: (Factory) -> Service) -> Service? {
return container.lock.sync {
return self.container._resolve(name: name, option: option, invoker: invoker)
}
}
}
extension SynchronizedResolver: Resolver {
internal func resolve<Service>(_ serviceType: Service.Type) -> Service? {
return container.lock.sync {
return self.container.resolve(serviceType)
}
}
internal func resolve<Service>(_ serviceType: Service.Type, name: String?) -> Service? {
return container.lock.sync {
return self.container.resolve(serviceType, name: name)
}
}
}
| 29.487179 | 131 | 0.668696 |
d99cab75b8aeec66cce2cd3620b3c4b06b645f5a | 6,964 | //
// InlineTimerView.swift
// Surround
//
// Created by Anh Khoa Hong on 7/14/20.
//
import SwiftUI
struct InlineByoYomiTimerView: View {
var thinkingTime: ThinkingTime
var mainFont: Font
var subFont: Font
var body: some View {
if thinkingTime.thinkingTimeLeft! > 0 {
(
Text(timeString(timeLeft: thinkingTime.thinkingTimeLeft!))
.font(mainFont)
+
Text(" (\(thinkingTime.periods!))")
.font(subFont)
).minimumScaleFactor(0.5)
} else {
if thinkingTime.periodsLeft! > 1 {
(
Text(timeString(timeLeft: thinkingTime.periodTimeLeft!))
.font(mainFont)
+
Text(" (\(thinkingTime.periodsLeft!))")
.font(subFont)
).minimumScaleFactor(0.5)
} else {
(
Text(timeString(timeLeft: thinkingTime.periodTimeLeft!))
.font(mainFont)
+
Text(" SD")
.font(subFont.bold())
.foregroundColor(Color.red)
).minimumScaleFactor(0.5)
}
}
}
}
struct InlineFischerTimerView: View {
var thinkingTime: ThinkingTime
var mainFont: Font
var subFont: Font
var body: some View {
Text(timeString(timeLeft: thinkingTime.thinkingTimeLeft!))
.font(mainFont)
.minimumScaleFactor(0.5)
}
}
struct InlineCanadianTimerView: View {
var thinkingTime: ThinkingTime
var mainFont: Font
var subFont: Font
var body: some View {
if thinkingTime.thinkingTimeLeft! > 0 {
Text(timeString(timeLeft: thinkingTime.thinkingTimeLeft!))
.font(mainFont)
.minimumScaleFactor(0.5)
} else {
Text("\(timeString(timeLeft: thinkingTime.blockTimeLeft!))/\(thinkingTime.movesLeft!)")
.font(mainFont)
.minimumScaleFactor(0.5)
}
}
}
struct InlineSimpleTimerView: View {
var thinkingTime: ThinkingTime
var mainFont: Font
var subFont: Font
var body: some View {
Text(timeString(timeLeft: thinkingTime.thinkingTimeLeft!))
.font(mainFont)
.minimumScaleFactor(0.5)
}
}
struct InlineTimerView: View {
var timeControl: TimeControl?
var clock: OGSClock?
var player: StoneColor
var mainFont: Font?
var subFont: Font?
var pauseControl: OGSPauseControl?
var showsPauseReason = true
var body: some View {
guard let clock = clock, let timeControl = timeControl else {
return AnyView(EmptyView())
}
let thinkingTime = player == .black ? clock.blackTime : clock.whiteTime
let mainFont = self.mainFont ?? Font.subheadline.monospacedDigit()
let subFont = self.subFont ?? Font.caption.monospacedDigit()
let playerId = player == .black ? clock.blackPlayerId : clock.whitePlayerId
let isPaused = pauseControl?.isPaused() ?? false
let pausedReason = pauseControl?.pauseReason(playerId: playerId) ?? ""
return AnyView(HStack(alignment: .firstTextBaseline) {
if !clock.started {
if let timeLeft = clock.timeUntilExpiration {
if clock.currentPlayerColor == player {
Image(systemName: "hourglass")
.foregroundColor(Color(UIColor.systemIndigo))
Text(timeString(timeLeft: timeLeft))
.font(mainFont.bold())
.foregroundColor(Color(UIColor.systemIndigo))
.minimumScaleFactor(0.5)
} else {
Text("Waiting...")
.font(mainFont.bold())
.foregroundColor(Color(UIColor.systemIndigo))
.minimumScaleFactor(0.5)
}
}
} else {
if clock.currentPlayerColor == player && !isPaused {
Image(systemName: "hourglass")
}
switch timeControl.system {
case .ByoYomi:
InlineByoYomiTimerView(thinkingTime: thinkingTime, mainFont: mainFont, subFont: subFont)
case .Fischer:
InlineFischerTimerView(thinkingTime: thinkingTime, mainFont: mainFont, subFont: subFont)
case .Canadian:
InlineCanadianTimerView(thinkingTime: thinkingTime, mainFont: mainFont, subFont: subFont)
case .Simple, .Absolute:
InlineSimpleTimerView(thinkingTime: thinkingTime, mainFont: mainFont, subFont: subFont)
default:
Text("").font(mainFont)
}
if isPaused {
if showsPauseReason {
Text(pausedReason).font(subFont.bold()).minimumScaleFactor(0.5)
} else {
Image(systemName: "pause.fill")
}
}
}
})
}
}
struct InlineTimerView_Previews: PreviewProvider {
static var previews: some View {
let timeControl1 = TimeControl(codingData: TimeControl.TimeControlCodingData(timeControl: "byoyomi", mainTime: 300, periods: 5, periodTime: 30))
let clock1 = OGSClock(
blackTime: ThinkingTime(thinkingTime: 200, thinkingTimeLeft: 185, periods: 5, periodTime: 30),
whiteTime: ThinkingTime(thinkingTime: 0, thinkingTimeLeft: 0, periods: 5, periodsLeft: 1, periodTime: 30, periodTimeLeft: 15),
currentPlayerColor: .black,
lastMoveTime: Date().timeIntervalSince1970 * 1000 - 10 * 3600 * 1000,
currentPlayerId: 1, blackPlayerId: 1, whitePlayerId: 2
)
let timeControl2 = TimeControl(codingData: TimeControl.TimeControlCodingData(timeControl: "fischer", initialTime: 600, timeIncrement: 30, maxTime: 600))
let clock2 = OGSClock(
blackTime: ThinkingTime(thinkingTime: 200, thinkingTimeLeft: 185),
whiteTime: ThinkingTime(thinkingTime: 300, thinkingTimeLeft: 300),
currentPlayerColor: .black,
lastMoveTime: Date().timeIntervalSince1970 * 1000 - 10 * 3600 * 1000,
currentPlayerId: 1, blackPlayerId: 1, whitePlayerId: 2
)
return Group {
InlineTimerView(timeControl: timeControl1, clock: clock1, player: .black)
InlineTimerView(timeControl: timeControl1, clock: clock1, player: .white)
InlineTimerView(timeControl: timeControl2, clock: clock2, player: .white)
}.previewLayout(.fixed(width: 180, height: 44))
}
}
| 37.847826 | 160 | 0.558443 |
091b153bfa370f94c7c0d81c41ae475dd4365cde | 717 | //
// GpxWaypointEntity+Initialisers.swift
// XMLParsing
//
// Created by Peter Bohac on 12/29/17.
// Copyright © 2017 Peter Bohac. All rights reserved.
//
import CoreData
extension GpxWaypointEntity {
convenience init(context: NSManagedObjectContext, waypoint: GpxWaypoint) {
self.init(context: context)
self.latitude = waypoint.latitude
self.longitude = waypoint.longitude
self.name = waypoint.name
self.waypointDescription = waypoint.pointDescription
}
convenience init(context: NSManagedObjectContext, latitude: Double, longitude: Double) {
self.init(context: context)
self.latitude = latitude
self.longitude = longitude
}
}
| 26.555556 | 92 | 0.694561 |
460a0e6e1ae3fc1353429d66ed7ed79c0fdd551b | 2,767 | //
// Cat2CatExampleSwiftTests.swift
// Cat2CatExampleSwiftTests
//
// Created by Isaac Greenspan on 10/29/14.
// Copyright (c) 2014 Vokal. All rights reserved.
//
import UIKit
import XCTest
class Cat2CatExampleSwiftTests: XCTestCase {
/// Tests the assumption that an .appiconset does not return an image when using imageNamed:
func testIconsDoNotReturnImages() {
XCTAssertNil(UIImage(named:"AppIcon"), "AppIcon is not nil!")
}
/// Tests the assumption that a .launchimage *does* return an image when using imageNamed:
func testLaunchImagesDoReturnImages() {
XCTAssertNotNil(UIImage(named:"LaunchImage"), "Launch image is nil!")
}
/// Tests that the image data retrieved from the two different methods is identical.
func testMethodImageAndImageNamedAreEqual() {
guard let imageNamed = UIImage(named:"US Capitol") else {
XCTFail("Named image did not unwrap!")
return
}
let methodRetreived = UIImage.ac_US_Capitol()
let imageNamedData = UIImagePNGRepresentation(imageNamed)
let methodReterivedData = UIImagePNGRepresentation(methodRetreived)
//Compare the data of the two images. Note that comparing the images directly doesn't work since
//that tests whether they're the same instance, not whether they have identical data.
XCTAssertEqual(imageNamedData, methodReterivedData, "Capitol images are not equal!")
}
/// Tests that our pipe-seperation of items from seperate catalogs is working by making sure at least one image from each catalog has made it in.
func testAtLeastOneImageFromEachCatalogWorks() {
XCTAssertNotNil(UIImage.ac_No_C(), "No C Image was nil!")
XCTAssertNotNil(UIImage.ac_Golden_Gate_Bridge(), "Golden Gate Bridge image was nil!")
}
/// Tests that all images from the Photos Asset Catalog are working.
func testAllImagesFromPhotosWork() {
XCTAssertNotNil(UIImage.ac_Golden_Gate_Bridge(), "Golden Gate Bridge image was nil!")
XCTAssertNotNil(UIImage.ac_US_Capitol(), "US Capitol image was nil!")
XCTAssertNotNil(UIImage.ac_Venice_Beach(), "Venice Beach image was nil!")
XCTAssertNotNil(UIImage.ac_Wrigley_Field(), "Wrigley Field image was nil!")
}
/// Tests that all images from the Icons Asset Catalog are working.
func testThatAllImagesFromIconsWork() {
XCTAssertNotNil(UIImage.ac_No_C(), "No C image was nil!")
XCTAssertNotNil(UIImage.ac_SidewaysC(), "Sideways C was nil!")
XCTAssertNotNil(UIImage.ac_PD_in_circle(), "PD in circle was nil!")
XCTAssertNotNil(UIImage.ac_PDe_Darka_Circle(), "PD in dark circle was nil")
}
}
| 43.234375 | 149 | 0.698229 |
39dc0f052a33ad8a53c5053bf10e93ccfd578e31 | 9,815 | //
// PreciseTime.swift
// PreciseTime
//
// Created by Stéphane Copin on 5/19/16.
// Copyright © 2016 Stéphane Copin. All rights reserved.
//
import Foundation
import Darwin
/**
Describe a time interval in nanoseconds.
`PreciseTime` provides helpers methods to convert to/from a NSTimeInterval,
which stores a time interval in seconds.
*/
public typealias PreciseTimeInterval = UInt64
/**
A struct representing a precise time.
It's basically a wrapper around the `mach_absolute_time()` function, with some goodies.
*/
public struct PreciseTime {
private let timeReference: PreciseTimeInterval
/// Returns the precise time interval that elapsed since the creation of the object.
public var preciseTimeIntervalSinceNow: PreciseTimeInterval {
return self.preciseTimeIntervalSincePreciseTime(PreciseTime())
}
/// Returns the time interval that elapsed since the creation of the object.
public var timeIntervalSinceNow: NSTimeInterval {
return PreciseTime.preciseTimeIntervalToTimeInterval(self.preciseTimeIntervalSinceNow)
}
/**
Initialize a new PreciseTime object with a time reference set to now.
- returns: An initialized PreciseTime object.
*/
public init() {
var timeBaseInfo = mach_timebase_info_data_t()
mach_timebase_info(&timeBaseInfo);
self.init(timeReference: mach_absolute_time() * UInt64(timeBaseInfo.numer) / UInt64(timeBaseInfo.denom))
}
/**
Initialize a new PreciseTime object with a time reference set to that of the argument.
- parameter preciseTime The precise time to copy the time reference from.
- returns: An initialized PreciseTime object.
*/
public init(preciseTime: PreciseTime) {
self.init(timeReference: preciseTime.timeReference)
}
public init(_ preciseTime: __PreciseTime) {
self.init(preciseTime: preciseTime.preciseTimeReference)
}
/**
Initialize a new PreciseTime object with a time reference set to that of the second argument,
added with the first argument.
- parameter preciseTimeInterval The interval to add to the time reference.
- parameter preciseTime The precise time to copy the time reference from.
- returns: An initialized PreciseTime object.
*/
public init(preciseTimeInterval: PreciseTimeInterval, sincePreciseTime preciseTime: PreciseTime) {
self.init(timeReference: preciseTime.timeReference + preciseTimeInterval)
}
private init(timeReference: PreciseTimeInterval) {
self.timeReference = timeReference
}
/**
Return the precise time interval that elapsed compared to another PreciseTime's time reference.
- parameter preciseTime The PreciseTime to compare to.
- returns: The resulting precise time interval
*/
public func preciseTimeIntervalSincePreciseTime(preciseTime: PreciseTime) -> PreciseTimeInterval {
if preciseTime.timeReference < self.timeReference {
return 0
}
return preciseTime.timeReference - self.timeReference
}
/**
Return the time interval that elapsed compared to another PreciseTime's time reference.
- parameter preciseTime The PreciseTime to compare to.
- returns: The resulting time interval
*/
public func timeIntervalSincePreciseTime(preciseTime: PreciseTime) -> NSTimeInterval {
return PreciseTime.preciseTimeIntervalToTimeInterval(self.preciseTimeIntervalSincePreciseTime(preciseTime))
}
/**
Create a new PreciseTime object by adding a precise time interval to the time reference to the receiver.
Equivalent to doing:
[PreciseTime @c preciseTimeWithPreciseTimeInterval:<#preciseTimeInterval#> @c preciseTime:self]
- parameter preciseTimeInterval The interval to add to the receiver's time reference.
- returns: A new PreciseTime object.
*/
public func preciseTimeByAddingPreciseTimeInterval(preciseTimeInterval: PreciseTimeInterval) -> PreciseTime {
return PreciseTime(preciseTimeInterval: preciseTimeInterval, sincePreciseTime: self)
}
/**
Create a new PreciseTime object by adding a time interval to the time reference to the receiver.
Equivalent to doing:
PreciseTimeInterval preciseTimeInterval = [PreciseTime timeIntervalToPreciseTimeInterval:<#timeInterval#>];
[PreciseTime preciseTimeWithPreciseTimeInterval:preciseTimeInterval preciseTime:self];
- parameter timeInterval The interval to add to the receiver's time reference.
- returns: A new PreciseTime object.
*/
public func preciseTimeByAddingTimeInterval(timeInterval: NSTimeInterval) -> PreciseTime {
return self.preciseTimeByAddingPreciseTimeInterval(PreciseTime.timeIntervalToPreciseTimeInterval(timeInterval))
}
/**
Converts a precise time interval to a time interval (nanoseconds to seconds conversion)
- parameter preciseTimeInterval The precise time interval to convert from in nanoseconds.
- returns: The resulting time interval in seconds
*/
public static func preciseTimeIntervalToTimeInterval(preciseTimeInterval: PreciseTimeInterval) -> NSTimeInterval {
return NSTimeInterval(preciseTimeInterval) / 1e9
}
/**
Converts a time interval to a precise time interval (seconds to nanoseconds conversion)
- parameter timeInterval The time interval to convert from in seconds.
- returns: The resulting precise time interval in nanoseconds
*/
public static func timeIntervalToPreciseTimeInterval(timeInterval: NSTimeInterval) -> PreciseTimeInterval {
return PreciseTimeInterval(timeInterval * 1e9)
}
/**
Compare the receiver against the first argument.
- parameter preciseTime The precise time to compare the receiver against.
- returns:
`NSOrderedDescending` if the receiver has a time reference later than the first argument. \
`NSOrderedEqual` if the receiver and the first argument have the same time reference. \
`NSOrderedAscending` if the receiver has a time reference earlier than the first argument.
*/
public func compare(preciseTime: PreciseTime) -> NSComparisonResult {
if self.timeReference == preciseTime.timeReference {
return .OrderedSame
}
return self.timeReference > preciseTime.timeReference ? .OrderedDescending : .OrderedAscending
}
}
extension PreciseTime: Hashable {
public var hashValue: Int {
return self.timeReference.hashValue
}
}
public func ==(preciseTime1: PreciseTime, preciseTime2: PreciseTime) -> Bool {
return preciseTime1.timeReference == preciseTime2.timeReference
}
/**
A class representing a precise time.
It is a wrapper against the swift struct PreciseTime, please refer to the documentation of that struct for more information.
It shouldn't be used in Swift.
*/
@objc(PreciseTime)
public final class __PreciseTime : NSObject {
private let preciseTimeReference: PreciseTime
public var preciseTimeIntervalSinceNow: PreciseTimeInterval {
return self.preciseTimeReference.preciseTimeIntervalSinceNow
}
public var timeIntervalSinceNow: NSTimeInterval {
return self.preciseTimeReference.timeIntervalSinceNow
}
public override init() {
self.preciseTimeReference = PreciseTime()
}
public init(preciseTime: __PreciseTime) {
self.preciseTimeReference = PreciseTime(preciseTime: preciseTime.preciseTimeReference)
}
public init(_ preciseTime: PreciseTime) {
self.preciseTimeReference = PreciseTime(preciseTime: preciseTime)
}
public init(preciseTimeInterval: PreciseTimeInterval, sincePreciseTime preciseTime: __PreciseTime) {
self.preciseTimeReference = PreciseTime(preciseTimeInterval: preciseTimeInterval, sincePreciseTime: preciseTime.preciseTimeReference)
}
private init(timeReference: PreciseTimeInterval) {
self.preciseTimeReference = PreciseTime(timeReference: timeReference)
}
public func preciseTimeIntervalSincePreciseTime(preciseTime: __PreciseTime) -> PreciseTimeInterval {
return self.preciseTimeReference.preciseTimeIntervalSincePreciseTime(preciseTime.preciseTimeReference)
}
public func timeIntervalSincePreciseTime(preciseTime: __PreciseTime) -> NSTimeInterval {
return self.preciseTimeReference.timeIntervalSincePreciseTime(preciseTime.preciseTimeReference)
}
public func preciseTimeByAddingPreciseTimeInterval(preciseTimeInterval: PreciseTimeInterval) -> __PreciseTime {
return __PreciseTime(self.preciseTimeReference.preciseTimeByAddingPreciseTimeInterval(preciseTimeInterval))
}
public func preciseTimeByAddingTimeInterval(timeInterval: NSTimeInterval) -> __PreciseTime {
return __PreciseTime(self.preciseTimeReference.preciseTimeByAddingTimeInterval(timeInterval))
}
public class func preciseTimeIntervalToTimeInterval(preciseTimeInterval: PreciseTimeInterval) -> NSTimeInterval {
return PreciseTime.preciseTimeIntervalToTimeInterval(preciseTimeInterval)
}
public class func timeIntervalToPreciseTimeInterval(timeInterval: NSTimeInterval) -> PreciseTimeInterval {
return PreciseTime.timeIntervalToPreciseTimeInterval(timeInterval)
}
/**
Test if the receiver is equal to the first argument.
- parameter preciseTime The precise time to compare the receiver against.
- returns: YES if both objects have the same time difference, NO otherwise.
*/
public func isEqualToPreciseTime(preciseTime: __PreciseTime) -> Bool {
return self.preciseTimeReference == preciseTime.preciseTimeReference
}
public func compare(preciseTime: __PreciseTime) -> NSComparisonResult {
return self.preciseTimeReference.compare(preciseTime.preciseTimeReference)
}
}
extension __PreciseTime: NSCopying {
public func copyWithZone(zone: NSZone) -> AnyObject {
return self
}
}
extension __PreciseTime: NSSecureCoding {
public convenience init?(coder decoder: NSCoder) {
guard let timeReference = decoder.decodeObjectOfClass(NSNumber.self, forKey: "timeReference") else {
return nil
}
self.init(timeReference: timeReference.unsignedLongLongValue)
}
public func encodeWithCoder(coder: NSCoder) {
coder.encodeObject(NSNumber(unsignedLongLong: self.preciseTimeReference.timeReference))
}
public static func supportsSecureCoding() -> Bool {
return true
}
}
| 34.804965 | 135 | 0.802038 |
f8cb5890cbb600de95b572c8a80fb619ce8aae8a | 16,761 | //
// TN2155.swift
// PDFPagePrinter
//
// Created by marc on 2017.07.01.
// Copyright © 2017 Example. All rights reserved.
//
import Cocoa
import Quartz
public class TN2155 {
/// Obtain available printer list
///
/// See also:
///
/// - returns: (err, printers, printerNames)
public static func getAvailablePrinterList() -> (err: OSStatus, printers: CFArray?, printerNames: [String]?)
{
var outPrinters: CFArray? = nil
var outPrinterNames: [String]? = nil
// Obtain the list of PMPrinters
var outPrintersUnmanaged: Unmanaged<CFArray>?
let err: OSStatus = PMServerCreatePrinterList( nil, &outPrintersUnmanaged )
outPrinters = outPrintersUnmanaged?.takeUnretainedValue()
if let printerArray = outPrinters {
var printerNames: [String] = []
for idx in 0 ..< CFArrayGetCount(printerArray) {
let printer = PMPrinter(CFArrayGetValueAtIndex(printerArray, idx))!
let nameUnmanaged: Unmanaged<CFString>? = PMPrinterGetName(printer)
guard let name = nameUnmanaged?.takeUnretainedValue() as String? else {
continue
}
printerNames.append(name)
}
outPrinterNames = printerNames
}
return (err, outPrinters, outPrinterNames)
}
/// Obtain print settings from dialog
public static func getPrintInfoViaPageSetupPanel()
-> (session: PMPrintSession, settings: PMPrintSettings, format: PMPageFormat)? {
// Use Page Setup to get a page format
let printInfo = NSPrintInfo()
let pageLayout = NSPageLayout()
if pageLayout.runModal(with: printInfo) == NSApplication.ModalResponse.OK.rawValue {
return (
PMPrintSession(printInfo.pmPrintSession()),
PMPrintSettings(printInfo.pmPrintSettings()),
PMPageFormat(printInfo.pmPageFormat())
)
}
return nil
}
public static func getPrintInfoViaPrintPanel()
-> (session: PMPrintSession, settings: PMPrintSettings, format: PMPageFormat)? {
// Use Page Setup to get a page format
let printInfo = NSPrintInfo()
let printPanel = NSPrintPanel()
printPanel.setDefaultButtonTitle("Save")
// set NSPrintPanel options as needed
printPanel.options = [
NSPrintPanel.Options.showsCopies, // Copies:__ [] B&W [] Two-Sided
//.showsPageRange, // Pages: (•) All, ( ) From:__ To:__
NSPrintPanel.Options.showsPaperSize, // Paper Size: US Letter, …
NSPrintPanel.Options.showsOrientation, //
NSPrintPanel.Options.showsScaling //
//.showsPrintSelection, // Pages: ( ) Selection
// showsPaperSize, showsOrientation, showsScaling affect showsPageSetupAccessory
//.showsPageSetupAccessory, // Paper Size, Orientation, Scale
//.showsPreview
]
if printPanel.runModal(with: printInfo) == NSApplication.ModalResponse.OK.rawValue {
return (
PMPrintSession(printInfo.pmPrintSession()),
PMPrintSettings(printInfo.pmPrintSettings()),
PMPageFormat(printInfo.pmPageFormat())
)
}
return nil
}
/// Obtain print settings from dialog
/// getPageSettingsAndFormat() version accesses PM for some initial setup
public static func getPrintInfoViaPrintPanel2() -> (
printSession: PMPrintSession,
printSettings: PMPrintSettings,
pageFormat: PMPageFormat
)? {
let printInfo = NSPrintInfo()
//let printSession = printInfo.pmPrintSession()
// PMSessionSetCurrentPMPrinter(session: PMPrintSession, printer: PMPrinter)
// Set any initial PMPageFormat values
let pageFormat = PMPageFormat(printInfo.pmPageFormat())
// kPMPortrait, kPMLandscape, kPMReversePortrait, kPMReverseLandscape
let orientation = PMOrientation(kPMLandscape)
PMSetOrientation(pageFormat, orientation, false)
PMSetScale(pageFormat, 72.0)
printInfo.updateFromPMPageFormat()
// Set any initial PMPrintSettings values
let printSettings = PMPrintSettings( printInfo.pmPrintSettings() )
PMSetCopies(printSettings, 3, false)
// PMSetFirstPage(printSettings: PMPrintSettings, first: UInt32, lock: Bool)
// PMSetLastPage(printSettings: PMPrintSettings, last: UInt32, lock: Bool)
// PMSetPageRange(printSettings: PMPrintSettings, minPage: UInt32, maxPage: UInt32)
// PMPrintSettingsSetJobName(printSettings: PMPrintSettings, name: CFString)
PMSetCollate(printSettings, true)
// kPMDuplexNone, kPMDuplexNoTumble, kPMDuplexTumble
// PMSetDuplex(printSettings: PMPrintSettings, duplexSetting: PMDuplexMode)
// PMPrinterSetOutputResolution(printer: PMPrinter, printSettings: PMPrintSettings, resolutionP: UnsafePointer<PMResolution>)
printInfo.updateFromPMPrintSettings()
let printPanel = NSPrintPanel()
printPanel.setDefaultButtonTitle("Save")
// set NSPrintPanel options as needed
printPanel.options = [
NSPrintPanel.Options.showsCopies, // Copies:__ [] B&W [] Two-Sided
//.showsPageRange, // Pages: (•) All, ( ) From:__ To:__
NSPrintPanel.Options.showsPaperSize, // Paper Size: US Letter, …
NSPrintPanel.Options.showsOrientation, //
NSPrintPanel.Options.showsScaling //
//.showsPrintSelection, // Pages: ( ) Selection
// showsPaperSize, showsOrientation, showsScaling affect showsPageSetupAccessory
//.showsPageSetupAccessory, // Paper Size, Orientation, Scale
//.showsPreview
]
if printPanel.runModal(with: printInfo) == NSApplication.ModalResponse.OK.rawValue {
return (
PMPrintSession(printInfo.pmPrintSession()),
PMPrintSettings(printInfo.pmPrintSettings()),
PMPageFormat(printInfo.pmPageFormat())
)
}
return nil
}
/* ***********************************************************
:TODO: explore whether using `PMCreateSession(_:)` to obtain a print session has any advantages over `let pmPrintSession = PMPrintSession(printInfo.pmPrintSession())`
:NYI: createPageFormat3() to use PMCreatePageFormat and PMCreatePrintSettings to replace NSPrintInfo PM objects.
``` swift
PMSessionCreatePrinterList(PMPrintSession, UnsafeMutablePointer<Unmanaged<CFArray>>, UnsafeMutablePointer<CFIndex>?, UnsafeMutablePointer<PMPrinter>?)
```
Use using the function PMCreateSession(_:) to create print session
see https://developer.apple.com/documentation/applicationservices/1463247-pmcreatesession
Some printing functions can be called only after you have created a printing session object. For example, setting defaults for or validating page format and print settings objects can only be done after you have created a printing session object
• can use a printing session to implement multithreaded printing
• can create multiple sessions within a single-threaded application
• If your application does not use sheets, then your application can open only one dialog at a time
• Each printing session can have its own dialog, and settings changed in one dialog are independent of settings in any other dialog
``` objc
// not yet translated per se
OSStatus CreatePrintSettings( PMPageFormat ioFormat, PMPrinter * outPrinter, PMPrintSettings * outSettings)
{
PMPrintSession printSession;
OSStatus err;
Boolean accepted = false;
*outPrinter = NULL;
*outSettings = NULL;
// In order to create the Print Settings & select a printer we'll
// ask the user to create their settings using the Print dialog.
err = PMCreateSession( &printSession );
if( !err )
{
// Validate the Page Format against the current Printer, which may update
// that format.
err = PMSessionValidatePageFormat( printSession, ioFormat, kPMDontWantBoolean );
// Create and default the print settings
if( !err )
err = PMCreatePrintSettings( outSettings );
if( !err )
err = PMSessionDefaultPrintSettings( printSession, *outSettings );
// Present the Print dialog.
if( !err )
err = PMSessionPrintDialog( printSession, *outSettings, ioFormat, &accepted );
if( !err && accepted )
{
// If the user accepted, then we'll retain the printer selected
// so that it survives the scope of this session.
// If there is an error getting the printer, then it will
// remain NULL
err = PMSessionGetCurrentPrinter( printSession, outPrinter );
if( !err )
PMRetain( *outPrinter );
}
else
{
// We got an error, or the user canceled the operation
// so we'll release our settings and NULL them out.
// The PMPrinter hasn't been set yet, so it will remain NULL.
PMRelease( *outSettings );
*outSettings = NULL;
}
PMRelease( printSession );
}
return err;
}
```
*********************************************************** */
/// Saving print settings to preferences
public static func savePrintPreferences(
data: (session: PMPrintSession, settings: PMPrintSettings, format: PMPageFormat),
prefix: String = ""
) -> OSStatus {
return savePrintPreferences(session: data.session, settings: data.settings, format: data.format, prefix: prefix)
}
public static func savePrintPreferences(
session: PMPrintSession,
settings: PMPrintSettings,
format: PMPageFormat,
prefix: String = ""
) -> OSStatus {
let kPrinterID: CFString = "\(prefix)kPrinterIDKey" as CFString
let kPrintSettings: CFString = "\(prefix)kPrintSettingsKey" as CFString
let kPageFormat: CFString = "\(prefix)kPageFormatKey" as CFString
var printerOptional: PMPrinter?
var err: OSStatus = noErr
var tempErr: OSStatus = noErr
// First, attempt to get the current printer from the print session
// If an error occurs, then simply return that error and do nothing else
err = PMSessionGetCurrentPrinter( session, &printerOptional )
guard let printer = printerOptional else { return err }
if err == noErr {
// If PMSessionGetCurrentPrinter returns successfully, then the printer is valid
// for as long as the session is valid, therefore we will assume that the printer name is valid.
let idUnmanaged: Unmanaged<CFString>? = PMPrinterGetID( printer )
guard let printerID = idUnmanaged?.takeUnretainedValue() as CFString? else { fatalError() }
// -- Preferences Set: Printer ID --
CFPreferencesSetAppValue( kPrinterID, printerID, kCFPreferencesCurrentApplication )
// -- Preferences Set: Print Settings --
var settingsDataUnmanagedOptional: Unmanaged<CFData>?
tempErr = PMPrintSettingsCreateDataRepresentation(settings, &settingsDataUnmanagedOptional, kPMDataFormatXMLMinimal)
guard let settingsDataUnmanaged = settingsDataUnmanagedOptional else { fatalError() }
if tempErr == noErr {
// If print settings are created, then save them to preferences
let settingsData: CFData = settingsDataUnmanaged.takeUnretainedValue() as CFData
CFPreferencesSetAppValue( kPrintSettings, settingsData, kCFPreferencesCurrentApplication )
}
else {
// If print settings are not created, then remove them from preferences
CFPreferencesSetAppValue( kPrintSettings, nil, kCFPreferencesCurrentApplication )
}
// -- Preferences Set: Page Format --
var formatDataUnmanagedOptional: Unmanaged<CFData>?
// kPMDataFormatXMLMinimal,
tempErr = PMPageFormatCreateDataRepresentation(format, &formatDataUnmanagedOptional, kPMDataFormatXMLDefault)
guard let formatDataUnmanaged = formatDataUnmanagedOptional else { fatalError() }
if tempErr == noErr {
// If page format data is created, then save data to preferences
let formatData: CFData = formatDataUnmanaged.takeUnretainedValue() as CFData
CFPreferencesSetAppValue( kPageFormat, formatData, kCFPreferencesCurrentApplication )
}
else {
// If page format is not created, no change is made
}
}
return err;
}
/// Restore print settings from preferences
public static func readPrintPreferences(prefix: String = "")
-> (id:CFString, settings: PMPrintSettings, format: PMPageFormat)? {
let kPrinterID: CFString = "\(prefix)kPrinterIDKey" as CFString
let kPrintSettings: CFString = "\(prefix)kPrintSettingsKey" as CFString
let kPageFormat: CFString = "\(prefix)kPageFormatKey" as CFString
var printerID: CFString = "" as CFString
var printSettingsOptional: PMPrintSettings?
var pageFormatOptional: PMPageFormat?
// -- Printer ID --
// load the printer ID via CFPreferences
guard let outPrinterID: CFPropertyList = CFPreferencesCopyAppValue(
kPrinterID, // key: CFString
kCFPreferencesCurrentApplication // applicationID: CFString
) else {
return nil
}
printerID = outPrinterID as! CFString
// -- Printer Settings --
guard let settingsPropertyList: CFPropertyList = CFPreferencesCopyAppValue(
kPrintSettings, // key: CFString
kCFPreferencesCurrentApplication // applicationID: CFString
) else {
return nil
}
_ = PMPrintSettingsCreateWithDataRepresentation(
settingsPropertyList as! CFData, // _ data: CFData
&printSettingsOptional // _ printSettings: UnsafeMutablePointer<PMPrintSettings>
)
guard let printSettings = printSettingsOptional else { fatalError() }
// -- Page Format --
guard let formatPropertyList: CFPropertyList = CFPreferencesCopyAppValue(
kPageFormat,
kCFPreferencesCurrentApplication
) else {
return nil
}
_ = PMPageFormatCreateWithDataRepresentation(
formatPropertyList as! CFData, // _ data: CFData
&pageFormatOptional // _ pageFormat: UnsafeMutablePointer<PMPageFormat>
)
guard let pageFormat = pageFormatOptional else { fatalError() }
return (printerID, printSettings, pageFormat)
}
// One approach to validate a printer.
// Alternate approach:
// attempt to create the printer.
// on success, use the printer print.
// on failure, ask user to update settings
public static func isValidPrinter(inPrinterID: CFString) -> Bool {
let printer: PMPrinter? = PMPrinterCreateFromPrinterID(inPrinterID)
var valid = false
if let _ = printer {
valid = true
}
// Be sure to release any non-NULL printer.
// If printer is `nil`, then PMRelease will return an error code
// which can be safely ignored.
PMRelease( PMObject(printer) )
return valid
}
}
| 44.458886 | 250 | 0.605453 |
ab1d03cdca2e50212c39b79ca8e7f3e12bc28dee | 5,808 | //
// AppDelegate.swift
// Weekly
//
// Created by Paul Wong on 4/12/20.
// Copyright © 2020 Paul Wong. All rights reserved.
//
import Cocoa
@available(OSX 10.14, *)
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
let statusItem = NSStatusBar.system.statusItem(withLength:NSStatusItem.variableLength)
let timeInterval: Double = 300
var priorWeekNo = 0
var priorMode: Bool = false
var timer: Timer!
var settings: Settings!
func applicationDidFinishLaunching(_ aNotification: Notification) {
// load settings
settings = Settings()
processCommandLine()
// Last things to do
update()
timer = Timer.scheduledTimer(
timeInterval: timeInterval,
target: self,
selector: #selector(fireTimer(_:)),
userInfo: nil,
repeats: true
)
RunLoop.current.add(timer, forMode: RunLoop.Mode.common)
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
@objc func fireTimer(_ sender: Any?) {
update()
}
@objc func about(_ sender: Any?) {
NSApp.activate(ignoringOtherApps: true)
NSApp.orderFrontStandardAboutPanel(self)
}
@objc func showLabel(_ sender: Any?) {
settings.settings.showLabel = !settings.settings.showLabel
settings.archive()
update()
}
@objc func openCalendar(_ sender: Any?) {
NSWorkspace.shared.launchApplication("iCal")
}
@objc func quit(_ sender: Any?) {
NSApplication.shared.terminate(nil)
}
func constructMenu(_ weekNo: Int) {
let menu = NSMenu()
menu.addItem(NSMenuItem(title: "Open week \(weekNo)", action: #selector(AppDelegate.openCalendar(_:)), keyEquivalent: ""))
menu.addItem(NSMenuItem.separator())
menu.addItem(NSMenuItem(title: "About...", action: #selector(AppDelegate.about(_:)), keyEquivalent: ""))
let showmenu = NSMenuItem(title: "Show Label", action: #selector(AppDelegate.showLabel(_:)), keyEquivalent: "s")
if settings.settings.showLabel == true {
showmenu.state = NSControl.StateValue.on
} else {
showmenu.state = NSControl.StateValue.off
}
menu.addItem(showmenu)
menu.addItem(NSMenuItem.separator())
menu.addItem(NSMenuItem(title: "Quit", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q"))
statusItem.menu = menu
}
func update() {
let calendar = Calendar.current
let weekNo = calendar.component(.weekOfYear, from: Date.init(timeIntervalSinceNow: 0))
if weekNo != priorWeekNo || settings.needsDisplay == true {
priorWeekNo = weekNo
var statusText = ""
if self.settings.settings.showLabel {
statusText = "Week "
}
statusItem.title = "\(statusText)"
let text = "\(weekNo)"
let iconImage = createMenuIcon(text: text, overrideWidth: 16)
iconImage.isTemplate = true
statusItem.image = iconImage
statusItem.button?.imagePosition = .imageRight
settings.needsDisplay = false
}
constructMenu(weekNo)
}
func createMenuIcon(text: String, overrideWidth: CGFloat?) -> NSImage {
let textFont = NSFont(name: "HelveticaNeue", size: 12)!
let textFontAttributes = [
NSAttributedString.Key.font: textFont,
NSAttributedString.Key.foregroundColor: NSColor.white,
] as [NSAttributedString.Key : Any]
let stringSize = text.size(withAttributes: textFontAttributes)
let width = overrideWidth ?? (stringSize.width + 4)
let size = NSSize(width: width, height: 16)
let backgroundImage = NSImage(size: size)
backgroundImage.lockFocus()
let rect = NSRect(origin: .zero, size: size)
let borderPath = NSBezierPath()
borderPath.appendRoundedRect(rect, xRadius: 2.0, yRadius: 2.0)
borderPath.lineWidth = 1
let fillColor = NSColor.black
fillColor.set()
borderPath.fill()
borderPath.stroke()
backgroundImage.unlockFocus()
let foregroundImage = NSImage(size: size)
foregroundImage.lockFocus()
text.draw(
in: CGRect(
x: (size.width - stringSize.width) / 2,
y: (size.height - stringSize.height + 3) / 2,
width: stringSize.width,
height: stringSize.height
),
withAttributes: textFontAttributes
)
foregroundImage.unlockFocus()
backgroundImage.lockFocus()
foregroundImage.draw(in: CGRect(origin: .zero, size: size), from: CGRect(origin: .zero, size: foregroundImage.size), operation: .destinationOut, fraction: 1.0)
backgroundImage.unlockFocus()
return backgroundImage
}
func processCommandLine() {
let arguments = ProcessInfo.processInfo.arguments
// reset takes takes priority
for i in 0..<arguments.count {
if (arguments[i] == "-R") {
settings.reset()
print("Reset configuration.")
}
}
// now handle the rest
for i in 0..<arguments.count {
switch arguments[i] {
case "-R":
print("Reset configuration, already handled.")
default:
print("Unhandled argument: \(arguments[i])")
}
}
}
}
| 32.629213 | 167 | 0.585227 |
29e59488dfe5b8b1c52c1400904b6f5d4a6390bf | 686 | //
// ResultDestination.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public struct ResultDestination: Codable {
public var outputFile: String?
public var inputFile: String?
public var destinationType: String?
public enum CodingKeys: String, CodingKey {
case outputFile = "OutputFile"
case inputFile = "InputFile"
case destinationType = "DestinationType"
}
public init(outputFile: String?, inputFile: String?, destinationType: String?) {
self.outputFile = outputFile
self.inputFile = inputFile
self.destinationType = destinationType
}
}
| 20.787879 | 84 | 0.689504 |
119136a66dd76e32a4abc4c20cd19786f6f44dc2 | 3,885 | //
// GlucoseTests.swift
// xDripG5
//
// Created by Nate Racklyeft on 8/6/16.
// Copyright © 2016 Nathan Racklyeft. All rights reserved.
//
import XCTest
import HealthKit
@testable import CGMBLEKit
class GlucoseTests: XCTestCase {
var timeMessage: TransmitterTimeRxMessage!
var calendar = Calendar(identifier: .gregorian)
var activationDate: Date!
override func setUp() {
super.setUp()
let data = Data(hexadecimalString: "2500470272007cff710001000000fa1d")!
timeMessage = TransmitterTimeRxMessage(data: data)!
calendar.timeZone = TimeZone(identifier: "UTC")!
activationDate = calendar.date(from: DateComponents(year: 2016, month: 10, day: 1))!
}
func testMessageData() {
let data = Data(hexadecimalString: "3100680a00008a715700cc0006ffc42a")!
let message = GlucoseRxMessage(data: data)!
let glucose = Glucose(transmitterID: "123456", glucoseMessage: message, timeMessage: timeMessage, activationDate: activationDate)
XCTAssertEqual(TransmitterStatus.ok, glucose.status)
XCTAssertEqual(calendar.date(from: DateComponents(year: 2016, month: 12, day: 6, hour: 7, minute: 51, second: 38))!, glucose.readDate)
XCTAssertEqual(calendar.date(from: DateComponents(year: 2016, month: 12, day: 26, hour: 11, minute: 16, second: 12))!, glucose.sessionStartDate)
XCTAssertFalse(glucose.isDisplayOnly)
XCTAssertEqual(204, glucose.glucose?.doubleValue(for: .milligramsPerDeciliter))
XCTAssertEqual(.known(.ok), glucose.state)
XCTAssertEqual(-1, glucose.trend)
}
func testNegativeTrend() {
let data = Data(hexadecimalString: "31006f0a0000be7957007a0006e4818d")!
let message = GlucoseRxMessage(data: data)!
let glucose = Glucose(transmitterID: "123456", glucoseMessage: message, timeMessage: timeMessage, activationDate: activationDate)
XCTAssertEqual(TransmitterStatus.ok, glucose.status)
XCTAssertEqual(calendar.date(from: DateComponents(year: 2016, month: 12, day: 6, hour: 8, minute: 26, second: 38))!, glucose.readDate)
XCTAssertFalse(glucose.isDisplayOnly)
XCTAssertEqual(122, glucose.glucose?.doubleValue(for: .milligramsPerDeciliter))
XCTAssertEqual(.known(.ok), glucose.state)
XCTAssertEqual(-28, glucose.trend)
}
func testDisplayOnly() {
let data = Data(hexadecimalString: "3100700a0000f17a5700584006e3cee9")!
let message = GlucoseRxMessage(data: data)!
let glucose = Glucose(transmitterID: "123456", glucoseMessage: message, timeMessage: timeMessage, activationDate: activationDate)
XCTAssertEqual(TransmitterStatus.ok, glucose.status)
XCTAssertEqual(calendar.date(from: DateComponents(year: 2016, month: 12, day: 6, hour: 8, minute: 31, second: 45))!, glucose.readDate)
XCTAssertTrue(glucose.isDisplayOnly)
XCTAssertEqual(88, glucose.glucose?.doubleValue(for: .milligramsPerDeciliter))
XCTAssertEqual(.known(.ok), glucose.state)
XCTAssertEqual(-29, message.glucose.trend)
}
func testOldTransmitter() {
let data = Data(hexadecimalString: "3100aa00000095a078008b00060a8b34")!
let message = GlucoseRxMessage(data: data)!
let glucose = Glucose(transmitterID: "123456", glucoseMessage: message, timeMessage: timeMessage, activationDate: activationDate)
XCTAssertEqual(TransmitterStatus.ok, glucose.status)
XCTAssertEqual(calendar.date(from: DateComponents(year: 2016, month: 12, day: 31, hour: 11, minute: 57, second: 09))!, glucose.readDate) // 90 days, status is still OK
XCTAssertFalse(glucose.isDisplayOnly)
XCTAssertEqual(139, glucose.glucose?.doubleValue(for: .milligramsPerDeciliter))
XCTAssertEqual(.known(.ok), glucose.state)
XCTAssertEqual(10, message.glucose.trend)
}
}
| 46.25 | 176 | 0.709653 |
895efabd47799c91f0b2133d829c2072bbf67c3d | 747 | import XCTest
import SipHashPod
class Tests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
}
| 25.758621 | 111 | 0.601071 |
0eac9fdfab72931e2fdb7d483ba33bda3636ec80 | 996 | // RUN: %target-resilience-test
// REQUIRES: executable_test
import StdlibUnittest
import struct_static_stored_to_computed
// Also import modules which are used by StdlibUnittest internally. This
// workaround is needed to link all required libraries in case we compile
// StdlibUnittest with -sil-serialize-all.
import SwiftPrivate
import SwiftPrivatePthreadExtras
#if _runtime(_ObjC)
import ObjectiveC
#endif
var StructStaticChangeStoredToComputedTest = TestSuite("StructStaticChangeStoredToComputed")
StructStaticChangeStoredToComputedTest.test("ChangeStoredToComputed") {
do {
@inline(never) func twice(inout x: Int) {
x *= 2
}
expectEqual(ChangeStoredToComputed.value, 0)
ChangeStoredToComputed.value = 32
expectEqual(ChangeStoredToComputed.value, 32)
ChangeStoredToComputed.value = -128
expectEqual(ChangeStoredToComputed.value, -128)
twice(&ChangeStoredToComputed.value)
expectEqual(ChangeStoredToComputed.value, -256)
}
}
runAllTests()
| 28.457143 | 92 | 0.787149 |
fecac8f90cbe81249534fbac79a5b3d69ed7f63d | 1,681 | import GRDB
/// A "row value" https://www.sqlite.org/rowvalue.html
///
/// WARNING: the Comparable conformance does not handle database collations.
/// FIXME: collation is available through https://www.sqlite.org/c3ref/table_column_metadata.html
struct RowValue {
let dbValues: [DatabaseValue]
}
extension RowValue: Comparable {
static func < (lhs: RowValue, rhs: RowValue) -> Bool {
return lhs.dbValues.lexicographicallyPrecedes(rhs.dbValues, by: <)
}
static func == (lhs: RowValue, rhs: RowValue) -> Bool {
return lhs.dbValues == rhs.dbValues
}
}
/// Compares DatabaseValue like SQLite
///
/// WARNING: this comparison does not handle database collations.
func < (lhs: DatabaseValue, rhs: DatabaseValue) -> Bool {
switch (lhs.storage, rhs.storage) {
case (.int64(let lhs), .int64(let rhs)):
return lhs < rhs
case (.double(let lhs), .double(let rhs)):
return lhs < rhs
case (.int64(let lhs), .double(let rhs)):
return Double(lhs) < rhs
case (.double(let lhs), .int64(let rhs)):
return lhs < Double(rhs)
case (.string(let lhs), .string(let rhs)):
return lhs.utf8.lexicographicallyPrecedes(rhs.utf8)
case (.blob(let lhs), .blob(let rhs)):
return lhs.lexicographicallyPrecedes(rhs, by: <)
case (.blob, _):
return false
case (_, .blob):
return true
case (.string, _):
return false
case (_, .string):
return true
case (.int64, _), (.double, _):
return false
case (_, .int64), (_, .double):
return true
case (.null, _):
return false
case (_, .null):
return true
}
}
| 30.017857 | 97 | 0.61749 |
91e81cef911d90357035d4f7e3bc59ca995dbb43 | 5,537 | //
// ViewController.swift
// Stopwatch
//
// Copyright © 2016 YiGu. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDelegate {
// MARK: - Variables
fileprivate let mainStopwatch: Stopwatch = Stopwatch()
fileprivate let lapStopwatch: Stopwatch = Stopwatch()
fileprivate var isPlay: Bool = false
fileprivate var laps: [String] = []
// MARK: - UI components
@IBOutlet weak var timerLabel: UILabel!
@IBOutlet weak var lapTimerLabel: UILabel!
@IBOutlet weak var playPauseButton: UIButton!
@IBOutlet weak var lapRestButton: UIButton!
@IBOutlet weak var lapsTableView: UITableView!
// MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
let initCircleButton: (UIButton) -> Void = { button in
button.layer.cornerRadius = 0.5 * button.bounds.size.width
button.backgroundColor = UIColor.white
}
initCircleButton(playPauseButton)
initCircleButton(lapRestButton)
lapRestButton.isEnabled = false
lapsTableView.delegate = self;
lapsTableView.dataSource = self;
}
// MARK: - UI Settings
override var shouldAutorotate : Bool {
return false
}
override var preferredStatusBarStyle : UIStatusBarStyle {
return UIStatusBarStyle.lightContent
}
override var supportedInterfaceOrientations : UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.portrait
}
// MARK: - Actions
@IBAction func playPauseTimer(_ sender: AnyObject) {
lapRestButton.isEnabled = true
changeButton(lapRestButton, title: "Lap", titleColor: UIColor.black)
if !isPlay {
unowned let weakSelf = self
mainStopwatch.timer = Timer.scheduledTimer(timeInterval: 0.035, target: weakSelf, selector: Selector.updateMainTimer, userInfo: nil, repeats: true)
lapStopwatch.timer = Timer.scheduledTimer(timeInterval: 0.035, target: weakSelf, selector: Selector.updateLapTimer, userInfo: nil, repeats: true)
RunLoop.current.add(mainStopwatch.timer, forMode: RunLoop.Mode.common)
RunLoop.current.add(lapStopwatch.timer, forMode: RunLoop.Mode.common)
isPlay = true
changeButton(playPauseButton, title: "Stop", titleColor: UIColor.red)
} else {
mainStopwatch.timer.invalidate()
lapStopwatch.timer.invalidate()
isPlay = false
changeButton(playPauseButton, title: "Start", titleColor: UIColor.green)
changeButton(lapRestButton, title: "Reset", titleColor: UIColor.black)
}
}
@IBAction func lapResetTimer(_ sender: AnyObject) {
if !isPlay {
resetMainTimer()
resetLapTimer()
changeButton(lapRestButton, title: "Lap", titleColor: UIColor.lightGray)
lapRestButton.isEnabled = false
} else {
if let timerLabelText = timerLabel.text {
laps.append(timerLabelText)
}
lapsTableView.reloadData()
resetLapTimer()
unowned let weakSelf = self
lapStopwatch.timer = Timer.scheduledTimer(timeInterval: 0.1, target: weakSelf, selector: Selector.updateLapTimer, userInfo: nil, repeats: true)
RunLoop.current.add(lapStopwatch.timer, forMode: RunLoop.Mode.common)
}
}
// MARK: - Private Helpers
fileprivate func changeButton(_ button: UIButton, title: String, titleColor: UIColor) {
button.setTitle(title, for: UIControl.State())
button.setTitleColor(titleColor, for: UIControl.State())
}
fileprivate func resetMainTimer() {
resetTimer(mainStopwatch, label: timerLabel)
laps.removeAll()
lapsTableView.reloadData()
}
fileprivate func resetLapTimer() {
resetTimer(lapStopwatch, label: lapTimerLabel)
}
fileprivate func resetTimer(_ stopwatch: Stopwatch, label: UILabel) {
stopwatch.timer.invalidate()
stopwatch.counter = 0.0
label.text = "00:00:00"
}
@objc func updateMainTimer() {
updateTimer(mainStopwatch, label: timerLabel)
}
@objc func updateLapTimer() {
updateTimer(lapStopwatch, label: lapTimerLabel)
}
func updateTimer(_ stopwatch: Stopwatch, label: UILabel) {
stopwatch.counter = stopwatch.counter + 0.035
var minutes: String = "\((Int)(stopwatch.counter / 60))"
if (Int)(stopwatch.counter / 60) < 10 {
minutes = "0\((Int)(stopwatch.counter / 60))"
}
var seconds: String = String(format: "%.2f", (stopwatch.counter.truncatingRemainder(dividingBy: 60)))
if stopwatch.counter.truncatingRemainder(dividingBy: 60) < 10 {
seconds = "0" + seconds
}
label.text = minutes + ":" + seconds
}
}
// MARK: - UITableViewDataSource
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return laps.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let identifier: String = "lapCell"
let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath)
if let labelNum = cell.viewWithTag(11) as? UILabel {
labelNum.text = "Lap \(laps.count - (indexPath as NSIndexPath).row)"
}
if let labelTimer = cell.viewWithTag(12) as? UILabel {
labelTimer.text = laps[laps.count - (indexPath as NSIndexPath).row - 1]
}
return cell
}
}
// MARK: - Extension
fileprivate extension Selector {
static let updateMainTimer = #selector(ViewController.updateMainTimer)
static let updateLapTimer = #selector(ViewController.updateLapTimer)
}
| 32.00578 | 153 | 0.699657 |
0a1773163705e7f85c7aebc4ccd5b3aa6186842a | 390 | //
// TokenEOF.swift
// TurtleCore
//
// Created by Andrew Fox on 9/3/19.
// Copyright © 2019 Andrew Fox. All rights reserved.
//
public class TokenEOF : Token {
public override var description: String {
return String(format: "<%@: sourceAnchor=%@>",
String(describing: type(of: self)),
String(describing: sourceAnchor))
}
}
| 24.375 | 57 | 0.584615 |
f5e9e65de2b48753e4d7754e2440d23e68373ba2 | 9,954 | //
// visitorView.swift
// SinaWeiBo
//
// Created by 何启亮 on 16/5/12.
// Copyright © 2016年 HQL. All rights reserved.
//
import UIKit
// ==============MARK: - 定义协议 @objc protocol 协议名: NSObjectProtocol
@objc protocol visitorViewDelegate: NSObjectProtocol{
// 定义方法 如果前缀没有修饰 optional 则所有方法都是 required 的
func visitorViewDidClickLogin()
func visitorViewDidClickRegister()
}
class visitorView: UIView {
// 加载页面 -- 加载控件 -- 控件使用懒加载的方式
// ==================MARK: - 属性
weak var delegate: visitorViewDelegate?
// ==================MARK: - 公开的方法 -- 转轮 -- 设置不同的view
/// 设置访客视图内容
func setupVisitorInfo(imageName: String, message: String){
self.iconView.image = UIImage(named: imageName)
self.messageLabel.text = message
self.coverView.hidden = true
self.homeView.hidden = true
}
func startRotationAnimation(){
let anim = CABasicAnimation(keyPath: "transform.rotation")
anim.toValue = M_PI * 2
anim.repeatCount = MAXFLOAT
anim.duration = 25
// 核心动画完成时不会自动移除
anim.removedOnCompletion = false
iconView.layer.addAnimation(anim, forKey: nil)
}
// ==================MARK: - 生命周期方法
override init(frame: CGRect) {
super.init(frame: frame)
// 在这个方法中添加子控件
self.prepareUI()
}
// 这个方法是view重写构造方法必须实现的
// 因为switf的语法中,如果重写了构造函数,则
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// ==================MARK: - prepare -- 设置子控件
private func prepareUI(){
// 设置背景颜色
// self.backgroundColor = UIColor(red: 233 / 255.0, green: 233 / 255.0, blue: 233 / 255.0, alpha: 1)
self.backgroundColor = UIColor(white: 237 / 255.0, alpha: 1)
// 添加控件
self.addSubview(iconView)
self.addSubview(coverView)
self.addSubview(homeView)
self.addSubview(messageLabel)
self.addSubview(registerButton)
self.addSubview(loginButton)
// 如果是用代码添加约束,则需要将translatesAutoresizingMaskIntoConstraints这个属性设置为false
iconView.translatesAutoresizingMaskIntoConstraints = false
coverView.translatesAutoresizingMaskIntoConstraints = false
homeView.translatesAutoresizingMaskIntoConstraints = false
messageLabel.translatesAutoresizingMaskIntoConstraints = false
registerButton.translatesAutoresizingMaskIntoConstraints = false
loginButton.translatesAutoresizingMaskIntoConstraints = false
// 开始添加约束
// 约束要添加到控件的父控件上面
// item: 要添加约束的view
// attribute: 要添加的View的属性
// toItem: 要参照的view
// attribute: 要参照View的属性
// 将约束添加到view上面去
// 轮子
self.addConstraint(NSLayoutConstraint(item: iconView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
self.addConstraint(NSLayoutConstraint(item: iconView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: -40))
// 遮盖
self.addConstraint(NSLayoutConstraint(item: coverView, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 0))
self.addConstraint(NSLayoutConstraint(item: coverView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0))
self.addConstraint(NSLayoutConstraint(item: coverView, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 0))
self.addConstraint(NSLayoutConstraint(item: coverView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: registerButton, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0))
// 小房子
// CenterX转轮CenterX
self.addConstraint(NSLayoutConstraint(item: homeView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: iconView, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
// CenterY转轮CenterY
self.addConstraint(NSLayoutConstraint(item: homeView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: iconView, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
// 消息label
/// 宽度
/// 当参照的view为nil时,属性为NSLayoutAttribute.NotAnAttribute
self.addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 240))
// CenterX 和父控件CenterX
self.addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
// Top和转轮底部
self.addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: iconView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 16))
// 注册按钮
/// 顶部和label底部
self.addConstraint(NSLayoutConstraint(item: registerButton, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: messageLabel, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 16))
/// 左边和label对齐
self.addConstraint(NSLayoutConstraint(item: registerButton, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: messageLabel, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 0))
/// 宽度
self.addConstraint(NSLayoutConstraint(item: registerButton, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 100))
// 高度
self.addConstraint(NSLayoutConstraint(item: registerButton, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 35))
// 登录按钮
/// 顶部和label底部
self.addConstraint(NSLayoutConstraint(item: loginButton, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: messageLabel, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 16))
/// 右边和label对齐
self.addConstraint(NSLayoutConstraint(item: loginButton, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: messageLabel, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 0))
/// 宽度
self.addConstraint(NSLayoutConstraint(item: loginButton, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 100))
// 高度
self.addConstraint(NSLayoutConstraint(item: loginButton, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 35))
}
// ==================MARK: - 点击事件
// 按钮点击事件方法是系统来调用, 当把按钮点击事件private后系统就找不到这个方法了
// @objc: 让系统可以找到我们的方法
@objc private func registerBtnClick(){
// view不能Modal出控制器来,需要将事件传递给控制器
self.delegate?.visitorViewDidClickRegister()
}
@objc private func loginBtnClick(){
self.delegate?.visitorViewDidClickLogin()
}
// ==================MARK: - 懒加载控件
// 转轮
lazy private var iconView: UIImageView = UIImageView(image: UIImage(named: "visitordiscover_feed_image_smallicon"))
// 遮罩 -- 渐变隐形的一般用一个遮罩的view来实现
lazy private var coverView: UIImageView = UIImageView(image: UIImage(named: "visitordiscover_feed_mask_smallicon"))
// 小房子
lazy private var homeView: UIImageView = UIImageView(image: UIImage(named: "visitordiscover_feed_image_house"))
// 文字 如果想在定义的时候定义多个属性,可以用这种方式={...}() 的方式来实现
lazy private var messageLabel:UILabel = {
let label:UILabel = UILabel()
// 设置属性
label.text = "关注一些人,看看有什么惊喜!"
label.textColor = UIColor.blackColor()
label.font = UIFont.systemFontOfSize(16)
label.textAlignment = NSTextAlignment.Center
label.numberOfLines = 0;
label.sizeToFit()
return label
}()
// 注册按钮
lazy private var registerButton:UIButton = {
let button = UIButton(type: UIButtonType.Custom)
// 设置属性
button.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Normal)
button.setTitleColor(UIColor.orangeColor(), forState: UIControlState.Normal)
button.setTitle("注册", forState: UIControlState.Normal)
button.addTarget(self, action: #selector(visitorView.registerBtnClick), forControlEvents: UIControlEvents.TouchUpInside)
return button
}()
// 登录按钮
lazy private var loginButton:UIButton = {
let button = UIButton(type: UIButtonType.Custom)
// 设置属性
button.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Normal)
button.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
button.setTitle("登录", forState: UIControlState.Normal)
button.addTarget(self, action: #selector(visitorView.loginBtnClick), forControlEvents: UIControlEvents.TouchUpInside)
return button
}()
}
| 49.522388 | 229 | 0.694796 |
e858d86639b1ab2fd117f82da01e8bc3b2e8b38f | 2,845 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Hummingbird server framework project
//
// Copyright (c) 2021-2021 the Hummingbird authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See hummingbird/CONTRIBUTORS.txt for the list of Hummingbird authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIO
import NIOHTTP1
/// Object that can generate a `Response`.
///
/// This is used by `Router` to convert handler return values into a `HBResponse`.
public protocol HBResponseGenerator {
/// Generate response based on the request this object came from
func response(from request: HBRequest) throws -> HBResponse
}
/// Extend Response to conform to ResponseGenerator
extension HBResponse: HBResponseGenerator {
/// Return self as the response
public func response(from request: HBRequest) -> HBResponse { self }
}
/// Extend String to conform to ResponseGenerator
extension String: HBResponseGenerator {
/// Generate response holding string
public func response(from request: HBRequest) -> HBResponse {
let buffer = request.allocator.buffer(string: self)
return HBResponse(status: .ok, headers: ["content-type": "text/plain; charset=utf-8"], body: .byteBuffer(buffer))
}
}
/// Extend ByteBuffer to conform to ResponseGenerator
extension ByteBuffer: HBResponseGenerator {
/// Generate response holding bytebuffer
public func response(from request: HBRequest) -> HBResponse {
HBResponse(status: .ok, headers: ["content-type": "application/octet-stream"], body: .byteBuffer(self))
}
}
/// Extend HTTPResponseStatus to conform to ResponseGenerator
extension HTTPResponseStatus: HBResponseGenerator {
/// Generate response with this response status code
public func response(from request: HBRequest) -> HBResponse {
HBResponse(status: self, headers: [:], body: .empty)
}
}
/// Extend Optional to conform to HBResponseGenerator
extension Optional: HBResponseGenerator where Wrapped: HBResponseGenerator {
public func response(from request: HBRequest) throws -> HBResponse {
switch self {
case .some(let wrapped):
return try wrapped.response(from: request)
case .none:
throw HBHTTPError(.notFound)
}
}
}
/// Extend EventLoopFuture of a ResponseEncodable to conform to ResponseFutureEncodable
extension EventLoopFuture where Value: HBResponseGenerator {
/// Generate `EventLoopFuture` that will be fulfilled with the response
public func responseFuture(from request: HBRequest) -> EventLoopFuture<HBResponse> {
return self.flatMapThrowing { try $0.response(from: request) }
}
}
| 37.434211 | 121 | 0.68471 |
16fab0491e00734d67cc78bd6730d56b754c94c1 | 2,228 | //
// HeaderView.swift
// PetWorld
//
// Created by my mac on 7/30/17.
// Copyright © 2017 GangsterSwagMuffins. All rights reserved.
//
import UIKit
@IBDesignable
class HeaderView: UIView {
@IBOutlet weak var titleText: UILabel!
@IBOutlet weak var leftButton: UIButton!
@IBOutlet var backgroundView: UIView!
@IBOutlet weak var rightButton: UIButton!
var onClickCallBack: ((Void)->Void)?
var onRightClickCallBack: ((Void)->Void)?
@IBInspectable
var color: UIColor?{
didSet{
if let color = color{
self.backgroundView.backgroundColor = color
}
}
}
@IBInspectable
var title: String?{
didSet{
titleText.text = title
}
}
@IBInspectable
var leftPicture: UIImage?{
didSet{
if let picture = leftPicture{
leftButton.setImage(picture, for: UIControlState.normal)
}
// leftButton.imageView.image = leftPicture
}
}
@IBInspectable
var rightPicture: UIImage?{
didSet{
if let picture = rightPicture{
rightButton.setImage(picture, for: UIControlState.normal)
}
}
}
override init(frame: CGRect){
super.init(frame: frame)
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
@IBAction func onTappedLeftButton(_ sender: Any) {
onClickCallBack?()
}
@IBAction func onTappedRightButton(_ sender: Any) {
onRightClickCallBack?()
}
func setupView(){
let nib = UINib(nibName: "HeaderView", bundle: nil)
nib.instantiate(withOwner: self, options: nil)
self.backgroundView.frame = bounds
self.backgroundColor = ColorPalette.primary
self.titleText.tintColor = UIColor.white
addSubview(self.backgroundView)
}
}
| 19.042735 | 73 | 0.523788 |
e6610f089ab35f58f36c6bef1c4a3656754e8405 | 38 | Int(romanNumerals: "MDCLXVI") // 1666
| 19 | 37 | 0.710526 |
f8c2632c951febff76763a2ab5f63a872adab4b6 | 6,643 | import _CJavaScriptKit
/// JSClosureProtocol wraps Swift closure objects for use in JavaScript. Conforming types
/// are responsible for managing the lifetime of the closure they wrap, but can delegate that
/// task to the user by requiring an explicit `release()` call.
public protocol JSClosureProtocol: JSValueCompatible {
/// Release this function resource.
/// After calling `release`, calling this function from JavaScript will fail.
func release()
}
/// `JSOneshotClosure` is a JavaScript function that can be called only once.
public class JSOneshotClosure: JSObject, JSClosureProtocol {
private var hostFuncRef: JavaScriptHostFuncRef = 0
public init(_ body: @escaping ([JSValue]) -> JSValue) {
// 1. Fill `id` as zero at first to access `self` to get `ObjectIdentifier`.
super.init(id: 0)
// 2. Create a new JavaScript function which calls the given Swift function.
hostFuncRef = JavaScriptHostFuncRef(bitPattern: Int32(ObjectIdentifier(self).hashValue))
id = _create_function(hostFuncRef)
// 3. Retain the given body in static storage by `funcRef`.
JSClosure.sharedClosures[hostFuncRef] = (self, {
defer { self.release() }
return body($0)
})
}
/// Release this function resource.
/// After calling `release`, calling this function from JavaScript will fail.
public func release() {
JSClosure.sharedClosures[hostFuncRef] = nil
}
}
/// `JSClosure` represents a JavaScript function the body of which is written in Swift.
/// This type can be passed as a callback handler to JavaScript functions.
///
/// e.g.
/// ```swift
/// let eventListenter = JSClosure { _ in
/// ...
/// return JSValue.undefined
/// }
///
/// button.addEventListener!("click", JSValue.function(eventListenter))
/// ...
/// button.removeEventListener!("click", JSValue.function(eventListenter))
/// ```
///
public class JSClosure: JSObject, JSClosureProtocol {
// Note: Retain the closure object itself also to avoid funcRef conflicts
fileprivate static var sharedClosures: [JavaScriptHostFuncRef: (object: JSObject, body: ([JSValue]) -> JSValue)] = [:]
private var hostFuncRef: JavaScriptHostFuncRef = 0
#if JAVASCRIPTKIT_WITHOUT_WEAKREFS
private var isReleased: Bool = false
#endif
@available(*, deprecated, message: "This initializer will be removed in the next minor version update. Please use `init(_ body: @escaping ([JSValue]) -> JSValue)` and add `return .undefined` to the end of your closure")
@_disfavoredOverload
public convenience init(_ body: @escaping ([JSValue]) -> ()) {
self.init({
body($0)
return .undefined
})
}
public init(_ body: @escaping ([JSValue]) -> JSValue) {
// 1. Fill `id` as zero at first to access `self` to get `ObjectIdentifier`.
super.init(id: 0)
// 2. Create a new JavaScript function which calls the given Swift function.
hostFuncRef = JavaScriptHostFuncRef(bitPattern: Int32(ObjectIdentifier(self).hashValue))
id = _create_function(hostFuncRef)
// 3. Retain the given body in static storage by `funcRef`.
Self.sharedClosures[hostFuncRef] = (self, body)
}
#if JAVASCRIPTKIT_WITHOUT_WEAKREFS
deinit {
guard isReleased else {
fatalError("release() must be called on JSClosure objects manually before they are deallocated")
}
}
#endif
}
// MARK: - `JSClosure` mechanism note
//
// 1. Create a thunk in the JavaScript world, which has a reference
// to a Swift closure.
// ┌─────────────────────┬──────────────────────────┐
// │ Swift side │ JavaScript side │
// │ │ │
// │ │ │
// │ │ ┌──────[Thunk]───────┐ │
// │ ┌ ─ ─ ─ ─ ─│─ ─│─ ─ ─ ─ ─ ┐ │ │
// │ ↓ │ │ │ │ │
// │ [Swift Closure] │ │ Host Function ID │ │
// │ │ │ │ │
// │ │ └────────────────────┘ │
// └─────────────────────┴──────────────────────────┘
//
// 2. When the thunk function is invoked, it calls the Swift closure via
// `_call_host_function` and receives the result through a callback.
// ┌─────────────────────┬──────────────────────────┐
// │ Swift side │ JavaScript side │
// │ │ │
// │ │ │
// │ Apply ┌──────[Thunk]───────┐ │
// │ ┌ ─ ─ ─ ─ ─│─ ─│─ ─ ─ ─ ─ ┐ │ │
// │ ↓ │ │ │ │ │
// │ [Swift Closure] │ │ Host Function ID │ │
// │ │ │ │ │ │
// │ │ │ └────────────────────┘ │
// │ │ │ ↑ │
// │ │ Apply │ │
// │ └─[Result]─┼───>[Callback func]─┘ │
// │ │ │
// └─────────────────────┴──────────────────────────┘
@_cdecl("_call_host_function_impl")
func _call_host_function_impl(
_ hostFuncRef: JavaScriptHostFuncRef,
_ argv: UnsafePointer<RawJSValue>, _ argc: Int32,
_ callbackFuncRef: JavaScriptObjectRef
) {
guard let (_, hostFunc) = JSClosure.sharedClosures[hostFuncRef] else {
fatalError("The function was already released")
}
let arguments = UnsafeBufferPointer(start: argv, count: Int(argc)).map {
$0.jsValue()
}
let result = hostFunc(arguments)
let callbackFuncRef = JSFunction(id: callbackFuncRef)
_ = callbackFuncRef(result)
}
/// [WeakRefs](https://github.com/tc39/proposal-weakrefs) are already Stage 4,
/// but was added recently enough that older browser versions don’t support it.
/// Build with `-Xswiftc -DJAVASCRIPTKIT_WITHOUT_WEAKREFS` to disable the relevant behavior.
#if JAVASCRIPTKIT_WITHOUT_WEAKREFS
// MARK: - Legacy Closure Types
extension JSClosure {
public func release() {
isReleased = true
Self.sharedClosures[hostFuncRef] = nil
}
}
@_cdecl("_free_host_function_impl")
func _free_host_function_impl(_ hostFuncRef: JavaScriptHostFuncRef) {}
#else
extension JSClosure {
@available(*, deprecated, message: "JSClosure.release() is no longer necessary")
public func release() {}
}
@_cdecl("_free_host_function_impl")
func _free_host_function_impl(_ hostFuncRef: JavaScriptHostFuncRef) {
JSClosure.sharedClosures[hostFuncRef] = nil
}
#endif
| 36.905556 | 223 | 0.568267 |
26ce80115a6793b4092252b541d1b1ec58fee64a | 3,026 | //
// Curried_ValueWithObjectMetadata.swift
// YapDatabaseExtensions
//
// Created by Daniel Thorpe on 14/10/2015.
//
//
import Foundation
import ValueCoding
// MARK: - Persistable
extension Persistable where
Self: ValueCoding,
Self.Coder: NSCoding,
Self.Coder.Value == Self {
/**
Returns a closure which, given a read transaction will return
the item at the given index.
- parameter index: a YapDB.Index
- returns: a (ReadTransaction) -> Self? closure.
*/
public static func readWithMetadataAtIndex<
ReadTransaction, Metadata>(_ index: YapDB.Index) -> (ReadTransaction) -> YapItem<Self, Metadata>? where
ReadTransaction: ReadTransactionType,
Metadata: NSCoding {
return { $0.readWithMetadataAtIndex(index) }
}
/**
Returns a closure which, given a read transaction will return
the items at the given indexes.
- parameter indexes: a SequenceType of YapDB.Index values
- returns: a (ReadTransaction) -> [Self] closure.
*/
public static func readWithMetadataAtIndexes<
Indexes, ReadTransaction, Metadata>(_ indexes: Indexes) -> (ReadTransaction) -> [YapItem<Self, Metadata>?] where
Indexes: Sequence,
Indexes.Iterator.Element == YapDB.Index,
ReadTransaction: ReadTransactionType,
Metadata: NSCoding {
return { $0.readWithMetadataAtIndexes(indexes) }
}
/**
Returns a closure which, given a read transaction will return
the item at the given key.
- parameter key: a String
- returns: a (ReadTransaction) -> Self? closure.
*/
public static func readWithMetadataByKey<
ReadTransaction, Metadata>(_ key: String) -> (ReadTransaction) -> YapItem<Self, Metadata>? where
ReadTransaction: ReadTransactionType,
Metadata: NSCoding {
return { $0.readWithMetadataByKey(key) }
}
/**
Returns a closure which, given a read transaction will return
the items at the given keys.
- parameter keys: a SequenceType of String values
- returns: a (ReadTransaction) -> [Self] closure.
*/
public static func readWithMetadataByKeys<
Keys, ReadTransaction, Metadata>(_ keys: Keys) -> (ReadTransaction) -> [YapItem<Self, Metadata>?] where
Keys: Sequence,
Keys.Iterator.Element == String,
ReadTransaction: ReadTransactionType,
Metadata: NSCoding {
return { $0.readWithMetadataAtIndexes(Self.indexesWithKeys(keys)) }
}
/**
Returns a closure which, given a write transaction will write
and return the item.
- warning: Be aware that this will capure `self`.
- returns: a (WriteTransaction) -> Self closure
*/
public func writeWithMetadata<
WriteTransaction, Metadata>(_ metadata: Metadata? = nil) -> (WriteTransaction) -> YapItem<Self, Metadata> where
WriteTransaction: WriteTransactionType,
Metadata: NSCoding {
return { $0.writeWithMetadata(YapItem(self, metadata)) }
}
}
| 32.537634 | 120 | 0.668539 |
9bb19d6e1aaed588a96078c11f6243d61a80b9ec | 1,403 | //
// Tests_iOS.swift
// Tests iOS
//
// Created by 杨立鹏 on 2021/12/30.
//
import XCTest
class Tests_iOS: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// UI tests must launch the application that they test.
let app = XCUIApplication()
app.launch()
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testLaunchPerformance() throws {
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 7.0, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTApplicationLaunchMetric()]) {
XCUIApplication().launch()
}
}
}
}
| 32.627907 | 182 | 0.650036 |
1843c8b64207149b4d94bb1768f4b3a1e0d5b1f8 | 5,714 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
/// Allocates `ByteBuffer`s to be used to read bytes from a `Channel` and records the number of the actual bytes that were used.
public protocol RecvByteBufferAllocator {
/// Allocates a new `ByteBuffer` that will be used to read bytes from a `Channel`.
func buffer(allocator: ByteBufferAllocator) -> ByteBuffer
/// Records the actual number of bytes that were read by the last socket call.
///
/// - parameters:
/// - actualReadBytes: The number of bytes that were used by the previous allocated `ByteBuffer`
/// - returns: `true` if the next call to `buffer` may return a bigger buffer then the last call to `buffer`.
mutating func record(actualReadBytes: Int) -> Bool
}
/// `RecvByteBufferAllocator` which will always return a `ByteBuffer` with the same fixed size no matter what was recorded.
public struct FixedSizeRecvByteBufferAllocator: RecvByteBufferAllocator {
public let capacity: Int
public init(capacity: Int) {
precondition(capacity > 0)
self.capacity = capacity
}
public mutating func record(actualReadBytes: Int) -> Bool {
// Returns false as we always allocate the same size of buffers.
return false
}
public func buffer(allocator: ByteBufferAllocator) -> ByteBuffer {
return allocator.buffer(capacity: capacity)
}
}
/// `RecvByteBufferAllocator` which will gracefully increment or decrement the buffer size on the feedback that was recorded.
public struct AdaptiveRecvByteBufferAllocator: RecvByteBufferAllocator {
private static let indexIncrement = 4
private static let indexDecrement = 1
private static let sizeTable: [Int] = {
var sizeTable: [Int] = []
var i: Int = 16
while i < 512 {
sizeTable.append(i)
i += 16
}
i = 512
while i < UInt32.max { // 1 << 32 max buffer size
sizeTable.append(i)
i <<= 1
}
return sizeTable
}()
private let minIndex: Int
private let maxIndex: Int
public let minimum: Int
public let maximum: Int
public let initial: Int
private var index: Int
private var nextReceiveBufferSize: Int
private var decreaseNow: Bool
public init() {
self.init(minimum: 64, initial: 2048, maximum: 65536)
}
public init(minimum: Int, initial: Int, maximum: Int) {
precondition(minimum >= 0, "minimum: \(minimum)")
precondition(initial > minimum, "initial: \(initial)")
precondition(maximum > initial, "maximum: \(maximum)")
let minIndex = AdaptiveRecvByteBufferAllocator.sizeTableIndex(minimum)
if AdaptiveRecvByteBufferAllocator.sizeTable[minIndex] < minimum {
self.minIndex = minIndex + 1
} else {
self.minIndex = minIndex
}
let maxIndex = AdaptiveRecvByteBufferAllocator.sizeTableIndex(maximum)
if AdaptiveRecvByteBufferAllocator.sizeTable[maxIndex] > maximum {
self.maxIndex = maxIndex - 1
} else {
self.maxIndex = maxIndex
}
self.initial = initial
self.minimum = minimum
self.maximum = maximum
self.index = AdaptiveRecvByteBufferAllocator.sizeTableIndex(initial)
self.nextReceiveBufferSize = AdaptiveRecvByteBufferAllocator.sizeTable[index]
self.decreaseNow = false
}
private static func sizeTableIndex(_ size: Int) -> Int {
var low: Int = 0
var high: Int = sizeTable.count - 1
repeat {
if high < low {
return low
}
if high == low {
return high
}
// It's important to put (...) around as >> is executed before + in Swift while in Java it's the other way around (doh!)
let mid = (low + high) >> 1
let a = sizeTable[mid]
let b = sizeTable[mid + 1]
if size > b {
low = mid + 1
} else if size < a {
high = mid - 1
} else if size == a {
return mid
} else {
return mid + 1
}
} while true
}
public func buffer(allocator: ByteBufferAllocator) -> ByteBuffer {
return allocator.buffer(capacity: nextReceiveBufferSize)
}
public mutating func record(actualReadBytes: Int) -> Bool {
if actualReadBytes <= AdaptiveRecvByteBufferAllocator.sizeTable[max(0, index - AdaptiveRecvByteBufferAllocator.indexDecrement - 1)] {
if decreaseNow {
index = max(index - AdaptiveRecvByteBufferAllocator.indexDecrement, minIndex)
nextReceiveBufferSize = AdaptiveRecvByteBufferAllocator.sizeTable[index]
decreaseNow = false
} else {
decreaseNow = true
}
} else if actualReadBytes >= nextReceiveBufferSize {
index = min(index + AdaptiveRecvByteBufferAllocator.indexIncrement, maxIndex)
nextReceiveBufferSize = AdaptiveRecvByteBufferAllocator.sizeTable[index]
decreaseNow = false
}
return actualReadBytes >= nextReceiveBufferSize
}
}
| 34.215569 | 141 | 0.610956 |
ddcfac6051017b68f5761f164b70298cb9861e65 | 550 | //
// Settings.swift
// MoyaApiStracher
//
// Created by Cloudus on 23/04/21.
//
import Foundation
struct Settings {
static var shared = Settings()
let apiURL: URL
private init() {
let path = Bundle.main.path(forResource: "Info", ofType: "plist")!
let plist = NSDictionary(contentsOfFile: path) as! [AnyHashable: Any]
let settings = plist["AppSettings"] as! [AnyHashable: Any]
apiURL = URL(string: (settings["ServerBaseURL"] as! String))!
// print("Settings loaded: \(self)")
}
}
| 23.913043 | 77 | 0.616364 |
712f0ecf2694a0ec1da6bf6b8913af0619b81090 | 1,869 | //
// ColorFromHex.swift
// Testing_Nav
//
// Created by zcrome on 7/17/17.
// Copyright © 2017 zcrome. All rights reserved.
//
import UIKit
extension UIColor {
convenience init(hex: String) {
var colorString = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
if colorString.hasPrefix("#"){
colorString.remove(at: colorString.startIndex)
}
if colorString.characters.count == 6{
var rgbValue:UInt32 = 0
Scanner(string: colorString).scanHexInt32(&rgbValue)
self.init(red: CGFloat((rgbValue & 0xFF0000) >> 16)/255, green: CGFloat((rgbValue & 0x00FF00) >> 8)/255, blue: CGFloat(rgbValue & 0x0000FF)/255, alpha: CGFloat(1))
}else if colorString.characters.count == 8{
var rgbValue:UInt32 = 0
Scanner(string: colorString).scanHexInt32(&rgbValue)
self.init(red: CGFloat((rgbValue & 0x00FF0000) >> 16)/255, green: CGFloat((rgbValue & 0x0000FF00) >> 8)/255, blue: CGFloat(rgbValue & 0x000000FF)/255, alpha: CGFloat((rgbValue & 0xFF000000) >> 24)/255)
}else{
self.init(colorLiteralRed: 0, green: 0, blue: 0, alpha: 1)
}
}
}
extension UIColor{
//NAME OF PLST: AppColors
//IT IS REQUIRED USE OF A PLIST FILE
convenience init(colorFromDict: String){
if let path = Bundle.main.path(forResource: "AppColors", ofType: "plist"),
let dict = NSDictionary(contentsOfFile: path) {
if let color = dict.value(forKey: colorFromDict) as? String{
self.init(hex: color)
}else{
self.init(colorLiteralRed: 0, green: 0, blue: 0, alpha: 1)
}
}else{
self.init(colorLiteralRed: 0, green: 0, blue: 0, alpha: 1)
}
}
}
| 30.145161 | 213 | 0.58534 |
62333dbfeef1c447a52b767442bbc4db4a0577b6 | 2,171 | //
// AppDelegate.swift
// MovieGoer
//
// Created by Zhia Chong on 10/15/16.
// Copyright © 2016 Zhia Chong. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.191489 | 285 | 0.754952 |
f5bcf5858f8234ca91e11b69ea0b247cced443ba | 587 | //
// ApiInterface.swift
// NossoLixo
//
// Created by Diogo Ribeiro de Oliveira on 25/04/18.
// Copyright © 2018 Diogo Ribeiro de Oliveira. All rights reserved.
//
import Foundation
enum Result<T> {
case success(T)
case error(Error)
}
typealias ReturnCategoriesRequests = (Result<[Category]>) -> Void
typealias ReturnPlacesRequests = (Result<[Place]>) -> Void
protocol NossoLixoServiceInterface {
func getCategories(completion: @escaping ReturnCategoriesRequests)
func getPlaces(completion: @escaping ReturnPlacesRequests)
}
struct GenericError: Error {
}
| 21.740741 | 70 | 0.734242 |
618498a835a95e1061f62fe80ace4b6a2e04fd88 | 489 | //
// AppDelegate.swift
// SwiftTube
//
// Created by Dagg on 3/23/20.
// Copyright © 2020 Dagg. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
}
| 18.111111 | 71 | 0.705521 |
ef1a72819f6cc6e94ba1119f99adb1c8e3464c24 | 629 | //
// SWMonthDescription.swift
// SmartWallet
//
// Created by Soheil on 01/09/2019.
// Copyright © 2019 Soheil Novinfard. All rights reserved.
//
import Foundation
struct SWMonth {
let year: Int
let shortYear: Int
let month: Int
let title: String
let shortTitle: String
let currentYear: Bool
var titleWithYear: String {
return "\(title) \(year)"
}
var shortTitleWithYear: String {
return "\(shortTitle) \(shortYear)"
}
var titleWithCurrentYear: String {
return currentYear ? title : titleWithYear
}
var shortTitleWithCurrentYear: String {
return currentYear ? shortTitle : shortTitleWithYear
}
}
| 17.971429 | 59 | 0.718601 |
012268a21c7568a622e6f51755cb2979515fe12f | 1,240 |
import UIKit
import HandyJSON
import SwiftBasicKit
/// 应答事件
class ZModelIMAnswer: ZModelIMEvent {
/// aappid
var aappid: String = ""
/// 频道ID
var channel_id: String = ""
/// 频道Token
var channel_token: String = ""
/// 被叫者
var callee: ZModelUserInfo?
/// 是否可见
var issee: Bool = true
required override init() {
super.init()
}
required init<T: ZModelIMEvent>(instance: T) {
super.init()
guard let model = instance as? Self else { return }
self.event_code = model.event_code
self.call_id = model.call_id
self.type = model.type
self.issee = model.issee
self.aappid = model.aappid
self.channel_id = model.channel_id
self.channel_token = model.channel_token
if let user = model.callee {
self.callee = ZModelUserInfo.init(instance: user)
}
}
override func mapping(mapper: HelpingMapper) {
super.mapping(mapper: mapper)
mapper <<< self.aappid <-- "data.aaid"
mapper <<< self.channel_id <-- "data.channel_id"
mapper <<< self.channel_token <-- "data.channel_token"
mapper <<< self.callee <-- "data.callee"
}
}
| 26.382979 | 62 | 0.587903 |
502ad204019b62e11655b628c252f07ca6a14908 | 2,016 | //
// ViewController.swift
// RecyclerKit
//
// Created by evan-cai on 04/26/2019.
// Copyright (c) 2019 evan-cai. All rights reserved.
//
import UIKit
import RecyclerKit
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
private let identifier = String(describing: RecyclerKitCell.self)
private var recyclerTable : RecyclerTable!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
setupTableView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func setupTableView() {
tableView.register(UINib(nibName: identifier, bundle: nil), forCellReuseIdentifier: identifier)
recyclerTable = RecyclerKit
.tableView(tableView)
.modelViewBind { (indexPath, viewModel, tableViewCell) in
switch viewModel.identifier {
case self.identifier:
break
default:
break
}
}
.modelViewClick({ (indexPath, viewModel) in
switch viewModel.identifier {
case self.identifier:
break
default:
break
}
})
.build()
let section: RecyclerTable.Section = RecyclerTable.Section()
let models: [RecyclerTable.ViewModel] = [
RecyclerTable.ViewModel(identifier: identifier, value: ""),
RecyclerTable.ViewModel(identifier: identifier, value: ""),
RecyclerTable.ViewModel(identifier: identifier, value: ""),
RecyclerTable.ViewModel(identifier: identifier, value: "")
]
section.name = "phrase"
section.models = models
self.recyclerTable.sections = [section]
}
}
| 28.394366 | 103 | 0.586806 |
0800347ca042da7007395ab2f399798401beb9bd | 552 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift %S/Inputs/vtable_symbol_linkage_base.swift -emit-module -emit-module-path=%t/BaseModule.swiftmodule -emit-library -module-name BaseModule -o %t/BaseModule.%target-dylib-extension
// RUN: %target-build-swift -I %t %s %t/BaseModule.%target-dylib-extension -o %t/a.out
// Check if the program can be linked without undefined symbol errors.
import BaseModule
public class Derived : Base {
}
public class DerivedNested : Namespace.Nested {}
public class DerivedExtNested : Namespace.ExtNested {}
| 39.428571 | 206 | 0.762681 |
9bf66c8d7d5ef39e999a82119528148cfccd2867 | 16,031 | //
// AVIMClient_TestCase.swift
// AVOS
//
// Created by zapcannon87 on 2018/4/11.
// Copyright © 2018 LeanCloud Inc. All rights reserved.
//
import XCTest
class AVIMClient_TestCase: LCIMTestBase {
// MARK: - Client Open
func test_client_open_with_avuser() {
var aUser: AVUser! = nil
self.runloopTestingAsync(async: { (semaphore: RunLoopSemaphore) in
let user: AVUser = AVUser()
user.username = "\(#function)\(#line)"
user.password = "12345678"
semaphore.increment()
semaphore.increment()
user.signUpInBackground({ (succeeded: Bool, error: Error?) in
semaphore.decrement()
XCTAssertTrue(Thread.isMainThread)
if let _ = error {
AVUser.logInWithUsername(inBackground: user.username!, password: user.password!, block: { (user: AVUser?, error: Error?) in
semaphore.decrement()
XCTAssertTrue(Thread.isMainThread)
XCTAssertNotNil(user)
XCTAssertNotNil(user?.objectId)
XCTAssertNotNil(user?.sessionToken)
if let _ = user?.objectId, let _ = user?.sessionToken {
aUser = user
}
})
} else {
semaphore.decrement()
XCTAssertNotNil(user.objectId)
XCTAssertNotNil(user.sessionToken)
if let _ = user.objectId, let _ = user.sessionToken {
aUser = user
}
}
})
}, failure: {
XCTFail("timeout")
})
guard aUser != nil else {
XCTFail()
return
}
self.runloopTestingAsync(async: { (semaphore: RunLoopSemaphore) in
let client: AVIMClient = AVIMClient(user: aUser)
semaphore.increment()
client.open(callback: { (succeeded: Bool, error: Error?) in
semaphore.decrement()
XCTAssertTrue(Thread.isMainThread)
XCTAssertTrue(succeeded)
XCTAssertNil(error)
})
}, failure: {
XCTFail("timeout")
})
}
// MARK: - Create Conversation
func test_create_temp_conv() {
let delegate_1: AVIMClientDelegate_TestCase = AVIMClientDelegate_TestCase()
guard let client_1: AVIMClient = self.newOpenedClient(clientId: "\(#function.substring(to: #function.index(of: "(")!))_\(#line)", delegate: delegate_1) else {
XCTFail()
return
}
let delegate_2: AVIMClientDelegate_TestCase = AVIMClientDelegate_TestCase()
guard let client_2: AVIMClient = self.newOpenedClient(clientId: "\(#function.substring(to: #function.index(of: "(")!))_\(#line)", delegate: delegate_2) else {
XCTFail()
return
}
self.runloopTestingAsync(async: { (semaphore: RunLoopSemaphore) in
semaphore.increment(5)
let clientIds: [String] = [client_1.clientId, client_2.clientId]
delegate_1.invitedByClosure = { (conv: AVIMConversation, byClientId: String?) in
semaphore.decrement()
XCTAssertTrue(Thread.isMainThread)
XCTAssertEqual(byClientId, client_1.clientId)
XCTAssertTrue((conv.conversationId ?? "").hasPrefix(kTemporaryConversationIdPrefix))
XCTAssertTrue(conv.isKind(of: AVIMTemporaryConversation.self))
}
delegate_1.membersAddedClosure = { (conv: AVIMConversation, memberIds: [String]?, byClientId: String?) in
semaphore.decrement()
XCTAssertTrue(Thread.isMainThread)
XCTAssertNotNil(memberIds)
XCTAssertEqual(memberIds?.count, clientIds.count)
XCTAssertNotNil((memberIds ?? []).contains(client_1.clientId))
XCTAssertNotNil((memberIds ?? []).contains(client_2.clientId))
XCTAssertEqual(byClientId, client_1.clientId)
XCTAssertTrue((conv.conversationId ?? "").hasPrefix(kTemporaryConversationIdPrefix))
XCTAssertTrue(conv.isKind(of: AVIMTemporaryConversation.self))
}
delegate_2.invitedByClosure = { (conv: AVIMConversation, byClientId: String?) in
semaphore.decrement()
XCTAssertTrue(Thread.isMainThread)
XCTAssertEqual(byClientId, client_1.clientId)
XCTAssertTrue((conv.conversationId ?? "").hasPrefix(kTemporaryConversationIdPrefix))
XCTAssertTrue(conv.isKind(of: AVIMTemporaryConversation.self))
}
delegate_2.membersAddedClosure = { (conv: AVIMConversation, memberIds: [String]?, byClientId: String?) in
semaphore.decrement()
XCTAssertTrue(Thread.isMainThread)
XCTAssertNotNil(memberIds)
XCTAssertEqual(memberIds?.count, clientIds.count)
XCTAssertNotNil((memberIds ?? []).contains(client_1.clientId))
XCTAssertNotNil((memberIds ?? []).contains(client_2.clientId))
XCTAssertEqual(byClientId, client_1.clientId)
XCTAssertTrue((conv.conversationId ?? "").hasPrefix(kTemporaryConversationIdPrefix))
XCTAssertTrue(conv.isKind(of: AVIMTemporaryConversation.self))
}
client_1.createTemporaryConversation(withClientIds: clientIds, timeToLive: 0, callback: { (conversation: AVIMTemporaryConversation?, error: Error?) in
semaphore.decrement()
XCTAssertTrue(Thread.isMainThread)
XCTAssertNotNil(conversation)
XCTAssertNotNil(conversation?.conversationId)
if let conv: AVIMTemporaryConversation = conversation,
let convId: String = conv.conversationId {
XCTAssertTrue(convId.hasPrefix(kTemporaryConversationIdPrefix))
XCTAssertTrue(conv.isKind(of: AVIMTemporaryConversation.self))
}
XCTAssertNil(error)
})
}, failure: {
XCTFail("timeout")
})
}
// MARK: - Session Token
func test_refresh_session_token() {
guard let client: AVIMClient = self.newOpenedClient(clientId: "\(#function)\(#line)") else {
XCTFail()
return
}
self.runloopTestingAsync(async: { (semaphore: RunLoopSemaphore) in
semaphore.increment()
semaphore.increment()
client.getSessionToken(withForcingRefresh: false, callback: { (token: String?, error: Error?) in
semaphore.decrement()
XCTAssertTrue(!Thread.isMainThread)
XCTAssertNotNil(token)
XCTAssertNil(error)
if let _token: String = token {
client.getSessionToken(withForcingRefresh: true, callback: { (token: String?, error: Error?) in
semaphore.decrement()
XCTAssertTrue(!Thread.isMainThread)
XCTAssertNotNil(token)
XCTAssertNil(error)
XCTAssertNotEqual(_token, token)
})
} else {
semaphore.decrement()
}
})
}, failure: {
XCTFail("timeout")
})
}
// MARK: - Session Conflict
func test_session_conflict() {
let clientId: String = "\(#function.substring(to: #function.index(of: "(")!))"
let tag: String = "tag"
let delegate_1: AVIMClientDelegate_TestCase = AVIMClientDelegate_TestCase()
let installation_1: AVInstallation = AVInstallation()
installation_1.deviceToken = UUID().uuidString
guard let _: AVIMClient = self.newOpenedClient(clientId: clientId, tag: tag, delegate: delegate_1, installation: installation_1) else {
XCTFail()
return
}
self.runloopTestingAsync(async: { (semaphore: RunLoopSemaphore) in
semaphore.increment(2)
delegate_1.didOfflineClosure = { (client: AVIMClient, error: Error?) in
semaphore.decrement()
XCTAssertTrue(Thread.isMainThread)
XCTAssertNotNil(error)
let _err: NSError? = error as NSError?
XCTAssertEqual(_err?.code, 4111)
XCTAssertEqual(_err?.domain, kLeanCloudErrorDomain)
}
let installation_2: AVInstallation = AVInstallation()
installation_2.deviceToken = UUID().uuidString
let client_2: AVIMClient = AVIMClient(clientId: clientId, tag: tag, installation: installation_2)
client_2.open(with: .forceOpen, callback: { (succeeded: Bool, error: Error?) in
semaphore.decrement()
XCTAssertTrue(Thread.isMainThread)
XCTAssertTrue(succeeded)
XCTAssertNil(error)
})
}, failure: {
XCTFail("timeout")
})
}
}
class AVIMClientDelegate_TestCase: NSObject, AVIMClientDelegate {
var didReceiveTypeMessageClosure: ((AVIMConversation, AVIMTypedMessage) -> Void)?
var didReceiveCommonMessageClosure: ((AVIMConversation, AVIMMessage) -> Void)?
var didOfflineClosure: ((AVIMClient, Error?) -> Void)?
var messageHasBeenUpdatedClosure: ((AVIMConversation, AVIMMessage) -> Void)?
var messageDeliveredClosure: ((AVIMConversation, AVIMMessage) -> Void)?
var didUpdateForKeyClosure: ((AVIMConversation, AVIMConversationUpdatedKey) -> Void)?
var updateByClosure: ((AVIMConversation, Date?, String?, [AnyHashable : Any]?) -> Void)?
var invitedByClosure: ((AVIMConversation, String?) -> Void)?
var kickedByClosure: ((AVIMConversation, String?) -> Void)?
var membersAddedClosure: ((AVIMConversation, [String]?, String?) -> Void)?
var membersRemovedClosure: ((AVIMConversation, [String]?, String?) -> Void)?
var memberInfoChangeClosure: ((AVIMConversation, String?, String?, String?) -> Void)?
var blockByClosure: ((AVIMConversation, String?) -> Void)?
var unblockByClosure: ((AVIMConversation, String?) -> Void)?
var membersBlockByClosure: ((AVIMConversation, String?, [String]?) -> Void)?
var membersUnblockByClosure: ((AVIMConversation, String?, [String]?) -> Void)?
var muteByClosure: ((AVIMConversation, String?) -> Void)?
var unmuteByClosure: ((AVIMConversation, String?) -> Void)?
var membersMuteByClosure: ((AVIMConversation, String?, [String]?) -> Void)?
var membersUnmuteByClosure: ((AVIMConversation, String?, [String]?) -> Void)?
func imClientPaused(_ imClient: AVIMClient) {}
func imClientResuming(_ imClient: AVIMClient) {}
func imClientResumed(_ imClient: AVIMClient) {}
func imClientClosed(_ imClient: AVIMClient, error: Error?) {}
func conversation(_ conversation: AVIMConversation, didReceive message: AVIMTypedMessage) {
self.didReceiveTypeMessageClosure?(conversation, message)
}
func conversation(_ conversation: AVIMConversation, didReceiveCommonMessage message: AVIMMessage) {
self.didReceiveCommonMessageClosure?(conversation, message)
}
func client(_ client: AVIMClient, didOfflineWithError error: Error?) {
self.didOfflineClosure?(client, error)
}
func conversation(_ conversation: AVIMConversation, messageHasBeenUpdated message: AVIMMessage) {
self.messageHasBeenUpdatedClosure?(conversation, message)
}
func conversation(_ conversation: AVIMConversation, messageDelivered message: AVIMMessage) {
self.messageDeliveredClosure?(conversation, message)
}
func conversation(_ conversation: AVIMConversation, didUpdateForKey key: AVIMConversationUpdatedKey) {
self.didUpdateForKeyClosure?(conversation, key)
}
func conversation(_ conversation: AVIMConversation, didUpdateAt date: Date?, byClientId clientId: String?, updatedData data: [AnyHashable : Any]?) {
self.updateByClosure?(conversation, date, clientId, data)
}
func conversation(_ conversation: AVIMConversation, invitedByClientId clientId: String?) {
self.invitedByClosure?(conversation, clientId)
}
func conversation(_ conversation: AVIMConversation, kickedByClientId clientId: String?) {
self.kickedByClosure?(conversation, clientId)
}
func conversation(_ conversation: AVIMConversation, membersAdded clientIds: [String]?, byClientId clientId: String?) {
self.membersAddedClosure?(conversation, clientIds, clientId)
}
func conversation(_ conversation: AVIMConversation, membersRemoved clientIds: [String]?, byClientId clientId: String?) {
self.membersRemovedClosure?(conversation, clientIds, clientId)
}
func conversation(_ conversation: AVIMConversation, didMemberInfoUpdateBy byClientId: String?, memberId: String?, role: String?) {
self.memberInfoChangeClosure?(conversation, byClientId, memberId, role)
}
func conversation(_ conversation: AVIMConversation, didBlockBy byClientId: String?) {
self.blockByClosure?(conversation, byClientId)
}
func conversation(_ conversation: AVIMConversation, didUnblockBy byClientId: String?) {
self.unblockByClosure?(conversation, byClientId)
}
func conversation(_ conversation: AVIMConversation, didMembersBlockBy byClientId: String?, memberIds: [String]?) {
self.membersBlockByClosure?(conversation, byClientId, memberIds)
}
func conversation(_ conversation: AVIMConversation, didMembersUnblockBy byClientId: String?, memberIds: [String]?) {
self.membersUnblockByClosure?(conversation, byClientId, memberIds)
}
func conversation(_ conversation: AVIMConversation, didMuteBy byClientId: String?) {
self.muteByClosure?(conversation, byClientId)
}
func conversation(_ conversation: AVIMConversation, didMembersMuteBy byClientId: String?, memberIds: [String]?) {
self.membersMuteByClosure?(conversation, byClientId, memberIds)
}
func conversation(_ conversation: AVIMConversation, didUnmuteBy byClientId: String?) {
self.unmuteByClosure?(conversation, byClientId)
}
func conversation(_ conversation: AVIMConversation, didMembersUnmuteBy byClientId: String?, memberIds: [String]?) {
self.membersUnmuteByClosure?(conversation, byClientId, memberIds)
}
}
| 40.482323 | 166 | 0.578629 |
502e9686cba1027c372c5c6708ba70c6964c930d | 321 | import Foundation
extension Mach {
var cstrings: [String] {
guard let cstringSection = cstringSection
else { return [] }
let cstringData = data.subdata(in: cstringSection.range.intRange)
return cstringData.split(separator: 0).compactMap { String(bytes: $0, encoding: .utf8) }
}
}
| 29.181818 | 96 | 0.660436 |
03f750aab9295780280331d67948aff8f47bd803 | 574 | // swift-tools-version:5.3
import PackageDescription
let package = Package(
name: "Adapty",
platforms: [
.iOS(.v9),
.macOS(.v10_12)
],
products: [
.library(
name: "Adapty",
targets: ["Adapty"]
),
],
dependencies: [
.package(url: "https://github.com/krzyzanowskim/CryptoSwift.git", .exact("1.3.2")),
],
targets: [
.target(
name: "Adapty",
dependencies: [
"CryptoSwift"
],
path: "Adapty"
),
]
)
| 19.793103 | 91 | 0.452962 |
20fc8c7d4b49dde9dc5a0c8c470ea85beba05316 | 288 | //
// MJResultViewController.swift
// MJCore
//
// Created by Martin Janák on 18/11/2018.
//
import UIKit
open class MJResultViewController<View: MJView, ViewModel: MJViewModel, Result>
: MJViewController<View, ViewModel> {
public var close: ((Result) -> Void)?
}
| 16.941176 | 79 | 0.673611 |
39648cdc43b277b33d657614d6aafac08822e4ca | 8,269 | //
// SearchVM.swift
// gitimoji
//
// Created by Timo Zacherl on 19.09.20.
//
import Foundation
import SwiftUI
import ServiceManagement
class SearchVM: ObservableObject {
@Published var searchResults = [Gitmoji]()
@Published var autoLaunchEnabled: Bool = false {
didSet {
toggleAutoLaunch(bool: autoLaunchEnabled)
}
}
@Published var isLoading: Bool = false
@Published var fetchState: FetchState = .stateless
@Published var searchText: String = "" {
didSet {
updateSearchText(width: searchText)
}
}
var allGitmojis = [Gitmoji]()
let managedObjectContext = PersistenceController.shared.container.viewContext
let fetchRequest: NSFetchRequest<Gitmoji> = Gitmoji.fetchRequest()
var helperBundleName = "com.timozacherl.GitimojiAutoLaunchHelper"
init() {
let foundHelper = NSWorkspace.shared.runningApplications.contains {
$0.bundleIdentifier == helperBundleName
}
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
do {
self.allGitmojis = try managedObjectContext.fetch(fetchRequest)
self.searchResults = self.allGitmojis
if self.allGitmojis.count == 0 {
refetchGitmojis()
}
} catch let error as NSError {
print("Could not fetch gitmojis. \(error), \(error.userInfo)")
}
autoLaunchEnabled = foundHelper
}
public func toggleAutoLaunch(bool: Bool) {
SMLoginItemSetEnabled(helperBundleName as CFString, bool)
}
public func updateSearchText(width text: String) {
self.isLoading = true
if text.count > 0 {
getSearchResults(forText: text)
} else {
self.searchResults = allGitmojis
}
self.isLoading = false
}
public func getSearchResults(forText text: String) {
self.searchResults = allGitmojis.filter { emoji in
let searchMatcher = SmartSearchMatcher(searchString: searchText.lowercased())
if let code = emoji.code, let emojiDescription = emoji.emojiDescription {
return searchMatcher.matches(emojiDescription.lowercased()) || searchMatcher.matches(code.lowercased())
}
return false
}
}
private func removeGitmojis() {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Gitmoji")
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
do {
try managedObjectContext.execute(deleteRequest)
} catch let error as NSError {
print(error)
}
}
public func refetchGitmojis() {
self.fetchState = .loading
self.removeGitmojis()
fetchEmojis { gitmojis in
gitmojis.forEach { gitmoji in
let newEntity = Gitmoji(context: self.managedObjectContext)
newEntity.name = gitmoji.name
newEntity.emojiDescription = gitmoji.description
newEntity.emojiEntity = gitmoji.entity
newEntity.code = gitmoji.code
newEntity.emoji = gitmoji.emoji
newEntity.semver = gitmoji.semver?.rawValue
}
do {
try self.managedObjectContext.save()
} catch let error as NSError {
print(error)
}
do {
let fetchRequest = NSFetchRequest<Gitmoji>(entityName: "Gitmoji")
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
self.allGitmojis = try self.managedObjectContext.fetch(fetchRequest)
DispatchQueue.main.async {
self.searchText = ""
}
} catch let error as NSError {
print(error)
DispatchQueue.main.async {
self.fetchState = .error
}
}
DispatchQueue.main.async {
self.fetchState = .success
}
}
}
}
enum FetchState {
case loading, success, error, stateless
}
//
// MARK: SmartSearchMatcher
//
// Created by Geoff Hackworth on 23/01/2021. Licensed under the MIT license, as follows:
//
// 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.
//
/// Search string matcher using token prefixes.
struct SmartSearchMatcher {
private(set) var searchTokens: [String.SubSequence]
/// Creates a new instance for testing matches against `searchString`.
public init(searchString: String) {
// Split `searchString` into tokens by whitespace and sort them by decreasing length
searchTokens = searchString.split(whereSeparator: { $0.isWhitespace }).sorted { $0.count > $1.count }
}
/// Check if `candidateString` matches `searchString`.
func matches(_ candidateString: String) -> Bool {
// If there are no search tokens, everything matches
guard !searchTokens.isEmpty else { return true }
// Split `candidateString` into tokens by whitespace
var candidateStringTokens = candidateString.split(whereSeparator: { $0.isWhitespace })
// Iterate over each search token
for searchToken in searchTokens {
// We haven't matched this search token yet
var matchedSearchToken = false
// Iterate over each candidate string token
for (candidateStringTokenIndex, candidateStringToken) in candidateStringTokens.enumerated() {
// Does `candidateStringToken` start with `searchToken`?
if let range = candidateStringToken.range(of: searchToken,
options: [.caseInsensitive, .diacriticInsensitive]),
range.lowerBound == candidateStringToken.startIndex {
matchedSearchToken = true
// Remove the candidateStringToken so we don't match it again against a different searchToken.
// Since we sorted the searchTokens by decreasing length, this ensures that searchTokens that
// are equal or prefixes of each other don't repeatedly match the same `candidateStringToken`.
// I.e. the longest matches are "consumed" so they don't match again. Thus "c c" does not match
// a string unless there are at least two words beginning with "c", and "b ba" will match
// "Bill Bailey" but not "Barry Took"
candidateStringTokens.remove(at: candidateStringTokenIndex)
// Check the next search string token
break
}
}
// If we failed to match `searchToken` against the candidate string tokens, there is no match
guard matchedSearchToken else { return false }
}
// If we match every `searchToken` against the candidate string tokens, `candidateString` is a match
return true
}
}
| 38.640187 | 119 | 0.620389 |
eb940d94b3be9f9c3c1501e2dd05603f3ac83093 | 505 | //
// ViewController.swift
// SpotView
//
// Created by Test User on 7/11/17.
// Copyright © 2017 Slim School. 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.
}
}
//
| 18.703704 | 80 | 0.661386 |
9b0514e43b26dfd91ee0c32e81c0aa3216ab2d87 | 3,320 | //
// Copyright 2018-2019 Amazon.com,
// Inc. or its affiliates. All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
import UIKit
import AWSMobileClient
protocol ItemCellDelegate {
func didTapDelete(item: Item)
}
class ItemCell: UICollectionViewCell {
var delegate: ItemCellDelegate?
var item: Item? {
didSet {
guard let key = item?.key else { return }
guard let accessLevel = item?.accessLevel else { return }
keyLabel.text = key
switch accessLevel {
case .guest:
userLabel.text = "N/A"
case .protected:
userLabel.text = item?.targetIdentityId
if let targetIdentity = item?.targetIdentityId, let identityId = AWSMobileClient.default().identityId {
if targetIdentity != identityId {
deleteButton.isHidden = true
}
}
case .private:
userLabel.text = AWSMobileClient.default().identityId
}
amplifyImageView.loadImage(key: key, accessLevel: accessLevel, identityId: item?.targetIdentityId)
}
}
let userLabel: UILabel = {
let label = UILabel()
label.font = UIFont.boldSystemFont(ofSize: 14)
return label
}()
let keyLabel: UILabel = {
let label = UILabel()
label.font = UIFont.boldSystemFont(ofSize: 13)
return label
}()
lazy var deleteButton: UIButton = {
let button = UIButton(type: .system)
button.setImage(#imageLiteral(resourceName: "delete").withRenderingMode(.alwaysOriginal), for: .normal)
button.addTarget(self, action: #selector(handleDelete), for: .touchUpInside)
return button
}()
let amplifyImageView: AmplifyImageView = {
let iv = AmplifyImageView()
iv.contentMode = .scaleAspectFill
iv.clipsToBounds = true
return iv
}()
@objc func handleDelete() {
print("Deleting item")
guard let item = item else { return }
delegate?.didTapDelete(item: item)
}
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(userLabel)
addSubview(keyLabel)
addSubview(deleteButton)
addSubview(amplifyImageView)
userLabel.anchor(top: topAnchor, left: leftAnchor, bottom: nil, right: nil, paddingTop: 0, paddingLeft: 8, paddingBottom: 0, paddingRight: 0, width: 0, height: 20)
keyLabel.anchor(top: userLabel.bottomAnchor, left: leftAnchor, bottom: nil, right: nil, paddingTop: 0, paddingLeft: 8, paddingBottom: 0, paddingRight: 0, width: 0, height: 30)
deleteButton.anchor(top: topAnchor, left: nil, bottom: nil, right: rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 8, width: 0, height: 30)
amplifyImageView.anchor(top: keyLabel.bottomAnchor, left: leftAnchor, bottom: nil, right: rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 0, height: 0)
amplifyImageView.heightAnchor.constraint(equalTo: widthAnchor, multiplier: 1).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 33.535354 | 197 | 0.625301 |
72c2545ad3623c0faaf2cac5f841fa1d947ff67d | 1,845 | import XCTest
/*
This version of the tests has been proved to have some problems with Xcode 6 Beta 5 (Up to 6.0.0)
If the tests won't compile and gives you the error Type '[String : Int]' does not conform to protocol 'Equatable',
please update your Xcode to the stable version 6.0.1 or higher.
*/
class WordCountTest: XCTestCase {
func testCountOneWord() {
let words = WordCount(words: "word")
let expected = ["word": 1]
let result = words.count()
XCTAssertEqual(expected, result)
}
func testCountOneOfEeach() {
let words = WordCount(words: "one of each")
let expected = ["one" : 1, "of" : 1, "each" : 1 ]
let result = words.count();
XCTAssertEqual(expected, result)
}
func testCountMultipleOccurrences() {
let words = WordCount(words: "one fish two fish red fish blue fish")
let expected = ["one" : 1, "fish" : 4, "two" : 1, "red" : 1, "blue" : 1 ]
let result = words.count()
XCTAssertEqual(expected, result)
}
func testIgnorePunctation() {
let words = WordCount(words: "car : carpet as java : javascript!!&$%^&")
let expected = ["car" : 1, "carpet" : 1, "as" : 1, "java" : 1, "javascript" : 1 ]
let result = words.count()
XCTAssertEqual(expected, result)
}
func testIncludeNumbers() {
let words = WordCount(words: "testing, 1, 2 testing")
let expected = [ "testing" : 2, "1" : 1, "2" : 1 ]
let result = words.count()
XCTAssertEqual(expected, result)
}
func testNormalizeCase() {
let words = WordCount(words:"go Go GO")
let expected = [ "go" : 3]
let result = words.count()
XCTAssertEqual(expected, result)
}
}
| 29.758065 | 114 | 0.566396 |
5bbc452a46b60d5d56043bd6b2e6074ea5ec6c3b | 3,386 | @testable import TRX
import Quick
import Nimble
import Nimble_Snapshots
import UIKit
class EasingSpec: QuickSpec {
override func spec() {
describe("linear") {
it("has valid graph") {
expect(EasingTestView(easing: Ease.linear)).to(haveValidSnapshot())
}
}
describe("quad") {
it("has valid in graph") {
expect(EasingTestView(easing: Ease.Quad.easeIn)).to(haveValidSnapshot())
}
it("has valid out graph") {
expect(EasingTestView(easing: Ease.Quad.easeOut)).to(haveValidSnapshot())
}
it("has valid inOut graph") {
expect(EasingTestView(easing: Ease.Quad.easeInOut)).to(haveValidSnapshot())
}
}
describe("cubic") {
it("has valid in graph") {
expect(EasingTestView(easing: Ease.Cubic.easeIn)).to(haveValidSnapshot())
}
it("has valid out graph") {
expect(EasingTestView(easing: Ease.Cubic.easeOut)).to(haveValidSnapshot())
}
it("has valid inOut graph") {
expect(EasingTestView(easing: Ease.Cubic.easeInOut)).to(haveValidSnapshot())
}
}
describe("quart") {
it("has valid in graph") {
expect(EasingTestView(easing: Ease.Quart.easeIn)).to(haveValidSnapshot())
}
it("has valid out graph") {
expect(EasingTestView(easing: Ease.Quart.easeOut)).to(haveValidSnapshot())
}
it("has valid inOut graph") {
expect(EasingTestView(easing: Ease.Quart.easeInOut)).to(haveValidSnapshot())
}
}
describe("sin") {
it("has valid in graph") {
expect(EasingTestView(easing: Ease.Sin.easeIn)).to(haveValidSnapshot())
}
it("has valid out graph") {
expect(EasingTestView(easing: Ease.Sin.easeOut)).to(haveValidSnapshot())
}
it("has valid inOut graph") {
expect(EasingTestView(easing: Ease.Sin.easeInOut)).to(haveValidSnapshot())
}
}
describe("expo") {
it("has valid in graph") {
expect(EasingTestView(easing: Ease.Expo.easeIn)).to(haveValidSnapshot())
}
it("has valid out graph") {
expect(EasingTestView(easing: Ease.Expo.easeOut)).to(haveValidSnapshot())
}
it("has valid inOut graph") {
expect(EasingTestView(easing: Ease.Expo.easeInOut)).to(haveValidSnapshot())
}
}
describe("circ") {
it("has valid in graph") {
expect(EasingTestView(easing: Ease.Circ.easeIn)).to(haveValidSnapshot())
}
it("has valid out graph") {
expect(EasingTestView(easing: Ease.Circ.easeOut)).to(haveValidSnapshot())
}
it("has valid inOut graph") {
expect(EasingTestView(easing: Ease.Circ.easeInOut)).to(haveValidSnapshot())
}
}
describe("elastic") {
it("has valid in graph") {
expect(EasingTestView(easing: Ease.Elastic.easeIn)).to(haveValidSnapshot())
}
it("has valid out graph") {
expect(EasingTestView(easing: Ease.Elastic.easeOut)).to(haveValidSnapshot())
}
it("has valid inOut graph") {
expect(EasingTestView(easing: Ease.Elastic.easeInOut)).to(haveValidSnapshot())
}
}
}
}
| 25.268657 | 86 | 0.575605 |
dd9def665dac29a746a3a239342729535bd1de75 | 3,155 | // Copyright (c) 2019 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.
//
// 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 GRDB
extension Download: TableRecord, FetchableRecord, MutablePersistableRecord {
enum Columns {
static let id = Column("id")
static let requestedAt = Column("requestedAt")
static let lastValidatedAt = Column("lastValidatedAt")
static let fileName = Column("fileName")
static let remoteUrl = Column("remoteUrl")
static let progress = Column("progress")
static let state = Column("state")
static let contentId = Column("contentId")
static let ordinal = Column("ordinal")
}
}
extension Download {
static let content = belongsTo(Content.self)
static let group = hasOne(Group.self, through: content, using: Content.group)
static let parentContent = hasOne(Content.self, through: group, using: Group.content)
static let parentDownload = hasOne(Download.self, through: parentContent, using: Content.download)
var content: QueryInterfaceRequest<Content> {
request(for: Download.content)
}
var parentContent: QueryInterfaceRequest<Content> {
request(for: Download.parentContent)
}
var parentDownload: QueryInterfaceRequest<Download> {
request(for: Download.parentDownload)
}
}
extension DerivableRequest where RowDecoder == Download {
func filter(state: Download.State) -> Self {
filter(Download.Columns.state == state.rawValue)
}
func orderByRequestedAtAndOrdinal() -> Self {
let requestedAt = Download.Columns.requestedAt
let ordinal = Download.Columns.ordinal
return order(requestedAt.asc, ordinal.asc)
}
}
| 42.066667 | 100 | 0.751506 |
1a51cd6f207d69ec6ccfefd5457271e870aca912 | 1,275 | //
// MIT License
//
// Copyright (c) 2018-2019 Radix DLT ( https://radixdlt.com )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import BigInt
public extension BigUInt {
init?(hex: String) {
self.init(hex, radix: 16)
}
}
| 39.84375 | 81 | 0.739608 |
1676deb9eabe6175f2699117c7c4abcb8e8b9352 | 718 | //
// AppDelegate.swift
// NewArch
//
// Created by Stefano Mondino on 22/10/2019.
// Copyright © 2019 Synesthesia. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let container = DefaultAppDependencyContainer()
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let window = UIWindow(frame: UIScreen.main.bounds)
self.window = window
container
.routeFactory
.restartRoute()
.execute(from: UIViewController())
return true
}
}
| 23.933333 | 115 | 0.66156 |
89c94cfe9797625a94dabac6f1c5abfd35bbd9e1 | 1,555 | //
// PageRightBarItem.swift
// woyuPageController
//
// Created by 魏卧鱼 on 2020/9/21.
// Copyright © 2020 魏卧鱼. All rights reserved.
//
import UIKit
// MARK: - 页眉控制器右侧按钮类
class PageRightBarItem: UIView {
// MARK: - 公有属性
var width: CGFloat = 0 //barItem的宽度
// MARK: - 私有属性
private lazy var barItemBody: UIImageView = { // item主体
// frame设置
let imageView = UIImageView(frame: .zero)
imageView.translatesAutoresizingMaskIntoConstraints = false
// 属性设置
imageView.image = UIImage(systemName: "list.triangle")
imageView.contentMode = .scaleAspectFit
imageView.tintColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
imageView.sizeToFit()
return imageView
}()
// MARK: - 构造器
// 指定构造器
init() {
super.init(frame: .zero)
translatesAutoresizingMaskIntoConstraints = false
buildSubViews()
}
// 必须构造器
@available(*, unavailable)
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - 子View构建相关方法
extension PageRightBarItem {
// UI搭建
private func buildSubViews() {
createBarItemBody()
}
// 创建item主体
private func createBarItemBody() {
addSubview(barItemBody)
// autolayout约束设置
NSLayoutConstraint.activate([
barItemBody.centerYAnchor.constraint(equalTo: centerYAnchor),
barItemBody.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -5),
])
}
}
| 22.536232 | 89 | 0.62508 |
0e38d0fb8f8af80f984b2cabbd2fc037cddf9427 | 1,232 | //
// Created by Tapash Majumder on 1/20/20.
// Copyright © 2020 Iterable. All rights reserved.
//
import Foundation
import IterableSDK
/// To change sort order of messages, set the `comparator` property of view delegate.
extension MainViewController {
@IBAction private func onSortByTitleAscendingTapped() {
// <ignore -- data loading>
DataManager.shared.loadMessages(from: "sort-by-title-ascending-messages", withExtension: "json")
// </ignore -- data loading>
let viewController = IterableInboxNavigationViewController()
viewController.viewDelegate = SortByTitleAscendingInboxViewDelegate()
present(viewController, animated: true)
}
}
public class SortByTitleAscendingInboxViewDelegate: IterableInboxViewControllerViewDelegate {
public required init() {}
public let comparator: (IterableInAppMessage, IterableInAppMessage) -> Bool = { message1, message2 in
guard let title1 = message1.inboxMetadata?.title else {
return true
}
guard let title2 = message2.inboxMetadata?.title else {
return false
}
return title1.caseInsensitiveCompare(title2) == .orderedAscending
}
}
| 33.297297 | 105 | 0.69237 |
11f3286183b516133a98b3e0c4fb653dd6b02de0 | 8,052 | //
// ControllerAnswersTVC.swift
// Answers
//
// Created by Enrique de la Torre (dev) on 04/04/2015.
// Copyright (c) 2015 Enrique de la Torre. 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 UIKit
class ControllerAnswersTVC: UITableViewController
{
// MARK: - Properties
private var question: IAWModelQuestion?
private var datastore: IAWPersistenceDatastoreProtocol
private var indexManager: IAWPersistenceDatastoreIndexManagerProtocol?
private var notificationCenter: IAWPersistenceDatastoreNotificationCenter?
private var allAnswers: [IAWModelAnswer]
// MARK: - Init object
override init(style: UITableViewStyle)
{
self.datastore = IAWPersistenceDatastoreDummy()
self.allAnswers = []
super.init(style: style)
}
required init(coder aDecoder: NSCoder)
{
self.datastore = IAWPersistenceDatastoreDummy.datastore()
self.allAnswers = []
super.init(coder: aDecoder)
}
// MARK: - Memory management
deinit
{
self.removeDatastoreObservers()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - View lifecycle
override func viewDidLoad()
{
super.viewDidLoad()
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
if let addAnswerTVC = segue.destinationViewController as? IAWControllerAddAnswerTVC
{
addAnswerTVC.useQuestion(question, inDatastore: datastore)
}
}
// MARK: - UITableViewDataSource methods
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return allAnswers.count
}
override func tableView (tableView: UITableView,
cellForRowAtIndexPath indexPath: NSIndexPath)
-> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier(kControllerAnswersTVCCellID,
forIndexPath: indexPath)
as! UITableViewCell
cell.configureWithAnswer(allAnswers[indexPath.row])
return cell
}
override func tableView(tableView: UITableView,
canEditRowAtIndexPath indexPath: NSIndexPath)
-> Bool
{
return true
}
override func tableView(tableView: UITableView,
commitEditingStyle editingStyle: UITableViewCellEditingStyle,
forRowAtIndexPath indexPath: NSIndexPath)
{
let oneAnswer = allAnswers[indexPath.row]
var error: NSError?
if !IAWModelAnswer.deleteAnswer(oneAnswer, inDatastore: datastore, error: &error)
{
// #warning Show log
}
}
// MARK: - Internal methods
func useQuestion(question: IAWModelQuestion?,
inDatastore datastore: IAWPersistenceDatastoreProtocol?,
indexedWith indexManager: IAWPersistenceDatastoreIndexManagerProtocol?,
listenNotificationsWith notificationCenter: IAWPersistenceDatastoreNotificationCenter?)
{
// Remove observers on previous datastore
self.removeDatastoreObservers()
// Update properties with new values
self.question = question
self.datastore = (datastore != nil ? datastore! : IAWPersistenceDatastoreDummy())
self.indexManager = indexManager
self.notificationCenter = notificationCenter
allAnswers = ControllerAnswersTVC.allAnswersForQuestion(self.question,
inIndexManager: self.indexManager)
// Refresh UI
title = (self.question != nil ?
self.question!.questionText :
NSLocalizedString("Answers", comment: "Answers"))
if isViewLoaded()
{
tableView.reloadData()
}
// Add observers to new datastore
self.addDatastoreObservers()
}
// MARK: - Private methods
private func addDatastoreObservers()
{
if let notificationCenter = notificationCenter
{
notificationCenter.addDidCreateDocumentNotificationObserver(self,
selector: "manageDidCreateDocumentNotification:",
sender: datastore)
notificationCenter.addDidDeleteDocumentNotificationObserver(self,
selector: "manageDidCreateDocumentNotification:",
sender: datastore)
notificationCenter.addDidReplaceDocumentNotificationObserver(self,
selector: "manageDidReplaceDocumentNotification:",
sender: datastore)
}
}
private func removeDatastoreObservers()
{
if let notificationCenter = notificationCenter
{
notificationCenter.removeDidCreateDocumentNotificationObserver(self, sender: datastore)
notificationCenter.removeDidDeleteDocumentNotificationObserver(self, sender: datastore)
notificationCenter.removeDidReplaceDocumentNotificationObserver(self, sender: datastore)
}
}
// Next method has to be dynamic (visible to objc runtime), otherwise the app will crash when
// NotificationCenter calls it because it is private
dynamic private func manageDidCreateDocumentNotification(notification: NSNotification)
{
// #warning Show log
allAnswers = ControllerAnswersTVC.allAnswersForQuestion(question, inIndexManager: indexManager)
if isViewLoaded()
{
tableView.reloadData()
}
}
dynamic private func manageDidReplaceDocumentNotification(notification: NSNotification)
{
// #warning Show log
let userInfo = notification.userInfo as! Dictionary<String, IAWPersistenceDatastoreDocumentProtocol!>
let replacedDoc = userInfo[kIAWPersistenceDatastoreNotificationCenterDidReplaceDocumentNotificationUserInfoKeyReplaced]
if let questionDocument = question?.document
{
if questionDocument === replacedDoc
{
// Update properties
let nextDoc = userInfo[kIAWPersistenceDatastoreNotificationCenterDidReplaceDocumentNotificationUserInfoKeyNext];
question = IAWModelQuestion(document: nextDoc)
allAnswers = ControllerAnswersTVC.allAnswersForQuestion(question, inIndexManager: indexManager)
// Refresh UI
title = question!.questionText
if isViewLoaded()
{
tableView.reloadData()
}
}
}
}
// MARK: - Private type methods
private class func allAnswersForQuestion(question: IAWModelQuestion?,
inIndexManager indexManager: IAWPersistenceDatastoreIndexManagerProtocol?)
-> [IAWModelAnswer]
{
var result = [] as [IAWModelAnswer]
if let question = question
{
if let indexManager = indexManager
{
result = IAWModelAnswer.allAnswersWithText(question.questionText,
inIndexManager: indexManager)
as! [IAWModelAnswer]
}
}
return result
}
}
| 31.952381 | 128 | 0.639965 |
d6bb00ebd571d89fbf6576269238038fb13bed22 | 2,461 | //
// ReviewProviderViewController.swift
// ServicesApp
//
// Created by Jawaher Mohammad on 08/06/1443 AH.
//
import UIKit
import Firebase
class ReviewProviderViewController: UIViewController {
// MARK: - Outlat
@IBOutlet weak var reviewView: UIView!{
didSet{
reviewView.layer.cornerRadius = 10
reviewView.layer.shadowRadius = 30
reviewView.layer.shadowOpacity = 0.5
}
}
@IBOutlet weak var saveButton: UIButton!{
didSet{
saveButton.setTitle("send".localizes, for: .normal)
saveButton.layer.cornerRadius = 10
}
}
@IBOutlet var starButtonCollection: [UIButton]!
// MARK: - Definitions
var rating = 0 {
didSet{
for starButton in starButtonCollection{
let imageName = (starButton.tag < rating ? "star.fill" : "star")
starButton.setImage(UIImage(systemName: imageName), for: .normal)
starButton.tintColor = (starButton.tag < rating ? .systemYellow : .darkText)
}
print("rating..>>",rating)
}
}
var selectUser : User?
var id = ""
// MARK: - View did load
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.black.withAlphaComponent(0.8)
// Do any additional setup after loading the view.
}
// MARK: - action star
@IBAction func starButtonPressed(_ sender: UIButton) {
rating = sender.tag + 1
}
// MARK: - save action
@IBAction func saveRating(_ sender: Any) {
if let selectUser = selectUser {
let sum = rating + selectUser.numberStar
let avg = sum/selectUser.numberRating
print("rating..>>",avg)
let db = Firestore.firestore()
db.collection("users").document(selectUser.id).updateData(["numberRating":selectUser.numberRating+1])
db.collection("users").document(selectUser.id).updateData(["numberStar":sum])
db.collection("users").document(selectUser.id).updateData(["rating":Double(avg)])
let ref = Firestore.firestore().collection("requests")
ref.document(id).delete { error in
if let error = error {
print("Error in db delete",error)
}
}
}
self.dismiss(animated: true, completion: nil)
}
}
| 33.256757 | 113 | 0.581877 |
0a5105862ebe95eedb062db6b3409ebbd065793b | 3,970 | //
// TextComponent.swift
// OnCall Health iOS
//
// Created by Domenic Bianchi on 2020-05-29.
// Copyright © 2020 OnCall Health. All rights reserved.
//
import SnapKit
import UIKit
// MARK: - TextComponent
class TextComponent: UIView {
// MARK: TextType
enum TextType {
case normal(bolded: Bool)
case subtitle(bolded: Bool)
}
// MARK: Lifecycle
init() {
super.init(frame: .zero)
addSubview(label)
label.lineBreakMode = .byWordWrapping
translatesAutoresizingMaskIntoConstraints = false
label.snp.makeConstraints {
$0.edges.equalToSuperview()
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Internal
func configure(
text: String?,
textColor: UIColor? = nil,
alignment: NSTextAlignment = .left,
numberOfLines: Int = 0,
type: TextType = .normal(bolded: false),
fontSize: CGFloat = 14)
{
label.text = text
accessibilityLabel = text
label.numberOfLines = numberOfLines
if numberOfLines == 0 {
label.lineBreakMode = .byWordWrapping
} else {
label.lineBreakMode = .byTruncatingTail
}
setLabelAttributes(fontSize: fontSize, alignment: alignment, type: type, textColor: textColor)
}
func configure(
attributedText: NSAttributedString?,
textColor: UIColor? = nil,
alignment: NSTextAlignment = .left,
type: TextType = .normal(bolded: false),
fontSize: CGFloat = 14)
{
label.attributedText = attributedText
accessibilityLabel = attributedText?.string
setLabelAttributes(fontSize: fontSize, alignment: alignment, type: type, textColor: textColor)
}
// MARK: Private
private func setLabelAttributes(fontSize: CGFloat, alignment: NSTextAlignment, type: TextType, textColor: UIColor?) {
switch type {
case .normal(let bolded):
label.font = bolded ? .boldSystemFont(ofSize: fontSize) : .systemFont(ofSize: fontSize)
label.textColor = textColor ?? .labelText
case .subtitle(let bolded):
label.font = bolded ? .boldSystemFont(ofSize: fontSize) : .systemFont(ofSize: fontSize)
label.textColor = textColor ?? .subtitle
}
label.textAlignment = alignment
}
private let label = UILabel()
}
// MARK: TextComponentCell
class TextComponentCell: UITableViewCell {
// MARK: Lifecycle
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(textComponent)
textComponent.snp.makeConstraints {
$0.leading.equalToSuperview().offset(16)
$0.trailing.equalToSuperview().offset(-16)
$0.top.equalToSuperview().offset(5)
$0.bottom.equalToSuperview().offset(-5)
}
selectionStyle = .none
backgroundColor = .background
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Internal
static let reuseIdentifier = "TextComponentCell"
func configure(
text: String?,
textColor: UIColor? = nil,
alignment: NSTextAlignment = .left,
numberOfLines: Int = 0,
type: TextComponent.TextType = .normal(bolded: false),
fontSize: CGFloat = 14)
{
textComponent.configure(
text: text,
textColor: textColor,
alignment: alignment,
numberOfLines: numberOfLines,
type: type,
fontSize: fontSize)
}
// MARK: Private
private let textComponent = TextComponent()
}
| 26.644295 | 121 | 0.599244 |
33e6afbd19b956291f4bf8af4f0e19c7efdab9f2 | 2,285 | //
// HashHelper.swift
// TigerTool
//
// Created by 胡金友 on 2020/7/19.
// Copyright © 2020 JyHu. All rights reserved.
//
import Cocoa
private func space(with level: Int) -> String {
return Array(repeating: "\t", count: level).joined(separator: "")
}
private func hashStringOf(object: Any) -> String {
if let str = object as? String {
return "\"\(str.replacing(string: "\"", target: "\\\""))\""
}
return (object is NSNumber) ? "\(object)" : "\"\(object)\""
}
/// 将一些swift对象转换成字符串
/// - Parameters:
/// - object: 要转换的对象
/// - level: 当前的层级,默认为0
/// - Returns: 转换后的字符串
func hashToString(of object: Any, level: Int = 0) -> String {
if let object = object as? Array<AnyObject> {
return object.toStringWith(level: level)
}
if let object = object as? Dictionary<String, AnyObject> {
return object.toStringWith(level: level)
}
return hashStringOf(object: object)
}
private extension Dictionary where Key: Comparable {
func toStringWith(level: Int) -> String {
return "{\n".appending(sorted(by: { $0.key < $1.key }).map { (key, value) -> String in
let tabs = "\(space(with: level + 1))\"\(key)\": "
if let value = value as? Array<AnyObject> {
return "\(tabs)\(value.toStringWith(level: level + 1))"
}
if let value = value as? Dictionary<String, AnyObject> {
return "\(tabs)\(value.toStringWith(level: level + 1))"
}
return "\(tabs)\(hashStringOf(object: value as AnyObject))"
}.joined(separator: ",\n")).appending("\n\(space(with: level))}")
}
}
private extension Array {
func toStringWith(level: Int) -> String {
return "[\n".appending(map({ object -> String in
let tabs = "\(space(with: level + 1))"
if let object = object as? Array<AnyObject> {
return "\(tabs)\(object.toStringWith(level: level + 1))"
}
if let object = object as? Dictionary<String, AnyObject> {
return "\(tabs)\(object.toStringWith(level: level + 1))"
}
return "\(tabs)\(hashStringOf(object: object as AnyObject))"
}).joined(separator: ",\n")).appending("\n\(space(with: level))]")
}
}
| 30.878378 | 94 | 0.571554 |
ace9c28f14d1d80a80f31d55bef4b714d351fac6 | 791 | //
// FMCalculatorViewController.swift
// CalcCal
//
// Created by Paolo Prodossimo Lopes on 31/01/22.
//
import Foundation
import UIKit
final class FMCalculatorViewController: FMBaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func configureStyle() {
super.configureStyle()
navigationItem.title = "CALCULADORA"
}
func getTabIcon() -> UITabBarItem {
if let icon = UIImage(systemName: "circle.grid.3x3") {
let item = UITabBarItem(
title: nil,
image: icon,
tag: 3
)
return item
}
return UITabBarItem(title: nil, image: UIImage(systemName: "xmark.octagon"), tag: 0)
}
}
| 21.378378 | 92 | 0.570164 |
1470d2235c66eca67e3147062acbeed31f754b15 | 4,093 | //
// AnyFlowRepresentable.swift
// Workflow
//
// Created by Tyler Thompson on 8/25/19.
// Copyright © 2021 WWT and Tyler Thompson. All rights reserved.
//
// swiftlint:disable private_over_fileprivate file_types_order
import Foundation
/// A type erased `FlowRepresentable`.
open class AnyFlowRepresentable {
typealias WorkflowInput = Any
typealias WorkflowOutput = Any
/// Erased instance that `AnyFlowRepresentable` wrapped.
public var underlyingInstance: Any {
_storage.underlyingInstance
}
var isPassthrough = false
var argsHolder: AnyWorkflow.PassedArgs
var workflow: AnyWorkflow? {
get {
_storage.workflow
} set {
_storage.workflow = newValue
}
}
var proceedInWorkflowStorage: ((AnyWorkflow.PassedArgs) -> Void)? {
get {
_storage.proceedInWorkflowStorage
} set {
_storage.proceedInWorkflowStorage = newValue
}
}
var backUpInWorkflowStorage: (() throws -> Void)? {
get {
_storage.backUpInWorkflowStorage
} set {
_storage.backUpInWorkflowStorage = newValue
}
}
fileprivate var _storage: AnyFlowRepresentableStorageBase
/**
Creates an erased `FlowRepresentable` by using its initializer
- Parameter type: The `FlowRepresentable` type to create an instance of
- Parameter args: The `AnyWorkflow.PassedArgs` to create the instance with. This ends up being cast into the `FlowRepresentable.WorkflowInput`.
*/
public init<FR: FlowRepresentable>(_ type: FR.Type, args: AnyWorkflow.PassedArgs) {
argsHolder = args
switch args {
case _ where FR.WorkflowInput.self == Never.self:
var instance = FR._factory(FR.self)
_storage = AnyFlowRepresentableStorage(&instance)
case _ where FR.WorkflowInput.self == AnyWorkflow.PassedArgs.self:
// swiftlint:disable:next force_cast
var instance = FR._factory(FR.self, with: args as! FR.WorkflowInput)
_storage = AnyFlowRepresentableStorage(&instance)
case .args(let extracted):
guard let cast = extracted as? FR.WorkflowInput else { fatalError("TYPE MISMATCH: \(String(describing: args)) is not type: \(FR.WorkflowInput.self)") }
var instance = FR._factory(FR.self, with: cast)
_storage = AnyFlowRepresentableStorage(&instance)
default: fatalError("No arguments were passed to representable: \(FR.self), but it expected: \(FR.WorkflowInput.self)")
}
_storage._workflowPointer = self
isPassthrough = FR.self is _PassthroughIdentifiable.Type
}
func shouldLoad() -> Bool { _storage.shouldLoad() }
}
fileprivate class AnyFlowRepresentableStorageBase {
var _workflowPointer: AnyFlowRepresentable?
var workflow: AnyWorkflow?
var proceedInWorkflowStorage: ((AnyWorkflow.PassedArgs) -> Void)?
var backUpInWorkflowStorage: (() throws -> Void)?
var underlyingInstance: Any {
fatalError("AnyFlowRepresentableStorageBase called directly, only available internally so something has gone VERY wrong.")
}
// https://github.com/wwt/SwiftCurrent/blob/main/.github/STYLEGUIDE.md#type-erasure
// swiftlint:disable:next unavailable_function
func shouldLoad() -> Bool {
fatalError("AnyFlowRepresentableStorageBase called directly, only available internally so something has gone VERY wrong.")
}
}
fileprivate class AnyFlowRepresentableStorage<FR: FlowRepresentable>: AnyFlowRepresentableStorageBase {
var holder: FR
override func shouldLoad() -> Bool {
holder.shouldLoad()
}
override var underlyingInstance: Any {
holder._workflowUnderlyingInstance
}
override var _workflowPointer: AnyFlowRepresentable? {
get {
holder._workflowPointer
} set {
holder._workflowPointer = newValue
}
}
init(_ instance: inout FR) {
holder = instance
}
}
| 34.686441 | 167 | 0.666992 |
9034eb72d5edfecd17b05cb110e9c4f8a7ffe668 | 2,156 | //
// AppDelegate.swift
// CTEventCalendar
//
// Created by Charles Tian on 01/05/2016.
// Copyright (c) 2016 Charles Tian. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
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:.
}
}
| 45.87234 | 285 | 0.754638 |
e4ac45d199b4a1c3b003dce65c1f4f828997f75f | 343 | //
// UIColor-Extension.swift
// DouYuZB
//
// Created by 皇坤鹏 on 17/4/12.
// Copyright © 2017年 皇坤鹏. All rights reserved.
//
import UIKit
extension UIColor {
// MARK:- 自定义构造方法
convenience init(r: CGFloat, g: CGFloat, b:CGFloat) {
self.init(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: 1.0)
}
}
| 17.15 | 80 | 0.58309 |
8ffdd37428080e8e5fd2e994a0d0ca62be950ea3 | 1,337 |
import Gorgon
/**
The ___FILEBASENAMEASIDENTIFIER___ will <# description #>
*/
internal final class ___FILEBASENAMEASIDENTIFIER___ {
/// Represents the APN category. This is must match what the server sends in the `category` property.
/// This must be unique for each remote notification (e.g. 1 remote notification daemon per category)
let category = "XXX"
}
// MARK: - RemoteNotificationDaemonType
extension ___FILEBASENAMEASIDENTIFIER___: RemoteNotificationDaemonType {
/**
Handler for the remote notification. The app can be in the background or foreground when this
notification is handled. You can check the application state of the UIApplication sharedInstance
to determine the background/foreground mode
- parameter notification: the `aps` userInfo object
- parameter completion: the completion handler to be called once the processing is completed
*/
func handleNotification(_ notification: [String : AnyObject], completion: @escaping (UIBackgroundFetchResult) -> ()) {
}
}
/**
COPY PASTE INTO ASSEMBLY
container.register(___FILEBASENAMEASIDENTIFIER___.self) { _ in
return ___FILEBASENAMEASIDENTIFIER___()
}
COPY PASTE INTO ASSEMBLY LOAD
DaemonManager.sharedInstance.register(resolver.resolve(___FILEBASENAMEASIDENTIFIER___.self)!)
*/
| 31.833333 | 122 | 0.751683 |
480195460f97908569b8a32aeb78051b16765f14 | 1,078 | //
// Grid.swift
// Migration
//
// Created by raniys on 6/17/20.
// Copyright © 2020 raniys. All rights reserved.
//
import SwiftUI
struct Grid<Item, ItemView>: View where Item: Identifiable, ItemView: View {
private var items: [Item]
private var viewForItem: (Item) -> ItemView
init(_ items: [Item], viewForItem: @escaping (Item) -> ItemView) {
self.items = items
self.viewForItem = viewForItem
}
var body: some View {
GeometryReader { geometry in
self.body(for: GridLayout(itemCount: self.items.count, in: geometry.size))
}
}
private func body(for layout: GridLayout) -> some View {
ForEach(items) { item in
self.body(for: item, in: layout)
}
}
private func body(for item: Item, in layout: GridLayout) -> some View {
let index = items.firstIndex(matching: item)!
return viewForItem(item)
.frame(width: layout.itemSize.width, height: layout.itemSize.height)
.position(layout.location(ofItemAt: index))
}
}
| 27.641026 | 86 | 0.615028 |
ddabb50466e89dcefcf6360266f26a74967820e4 | 4,371 | import CoreMotion
public class MagnetometerData {
public var timestamp: Double
public var caliberatedMagneticData: CMCalibratedMagneticField?
public var magneticData: CMMagneticField?
init(_ caliberatedMagnetoData: CMCalibratedMagneticField) {
self.caliberatedMagneticData = caliberatedMagnetoData
timestamp = Date().timeIntervalSince1970 * 1000
}
init(_ magneticData: CMMagneticField) {
self.magneticData = magneticData
timestamp = Date().timeIntervalSince1970 * 1000
}
}
public class MagnetometerSensor: ISensorController {
public var config = Config()
var motionManager: CMMotionManager
var LAST_DATA: CMMagneticField?
private let opQueue: OperationQueue = {
let o = OperationQueue()
o.name = "core-motion-updates"
return o
}()
//var LAST_SAVE:Double = Date().timeIntervalSince1970
public class Config: SensorConfig {
/**
* For real-time observation of the sensor data collection.
*/
public weak var sensorObserver: MagnetometerObserver?
/**
* Magnetometer frequency in hertz per second: e.g.
*
* 0 - fastest
* 1 - sample per second
* 5 - sample per second
* 20 - sample per second
*/
public var frequency: Int = 5
/**
* Period to save data in minutes. (optional)
*/
public var period: Double = 1
/**
* Magnetometer threshold (float). Do not record consecutive points if
* change in value is less than the set value.
*/
public var threshold: Double = 0.0
public override init() {
super.init()
}
public override func set(config: Dictionary<String, Any>) {
super.set(config: config)
if let frequency = config["frequency"] as? Int {
self.frequency = frequency
}
if let period = config["period"] as? Double {
self.period = period
}
if let threshold = config["threshold"] as? Double {
self.threshold = threshold
}
}
public func apply(closure:(_ config: MagnetometerSensor.Config) -> Void) -> Self {
closure(self)
return self
}
}
public convenience init() {
self.init(MagnetometerSensor.Config())
}
public init(_ config:MagnetometerSensor.Config) {
self.config = config
motionManager = CMMotionManager()
if config.debug{ print("Magnetometer sensor is created. ") }
}
public func start() {
if self.motionManager.isMagnetometerAvailable && !self.motionManager.isMagnetometerActive {
self.motionManager.magnetometerUpdateInterval = 1.0 / Double(config.frequency)
self.motionManager.startMagnetometerUpdates(to: opQueue) { (magnetometerData, error) in
guard let data = magnetometerData else {
return
}
// let x = magData.magneticField.x
// let y = magData.magneticField.y
// let z = magData.magneticField.z
// if let lastData = self.LAST_DATA {
// if self.CONFIG.threshold > 0 &&
// abs(x - lastData.x) < self.CONFIG.threshold &&
// abs(y - lastData.y) < self.CONFIG.threshold &&
// abs(z - lastData.z) < self.CONFIG.threshold {
// return
// }
// }
// self.LAST_DATA = magData.magneticField
self.config.sensorObserver?.onDataChanged(data: MagnetometerData(data.magneticField))
}
}
}
public func stop() {
if motionManager.isMagnetometerAvailable && motionManager.isMagnetometerActive {
motionManager.stopMagnetometerUpdates()
}
}
}
| 34.968 | 101 | 0.525967 |
ab1b3abda4bac9e681c8cb0153a597a68a438ad4 | 1,149 | //
// TestXXTEAUITests.swift
// TestXXTEAUITests
//
// Created by 郑嘉杰 on 2019/8/5.
// Copyright © 2019 郑嘉杰. All rights reserved.
//
import XCTest
class TestXXTEAUITests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 32.828571 | 182 | 0.688425 |
67151fd90bfe3eb4aa562ad92c2c6428f353a0ff | 2,129 | //
// ImageData.swift
// SNKit
//
// Created by ZJaDe on 2018/6/7.
// Copyright © 2018年 syk. All rights reserved.
//
import Foundation
#if canImport(RxOptional)
import RxOptional
extension ImageData: Occupiable {}
#endif
public enum ImageData: Codable {
case image(UIImage?)
case url(ImageURLProtocol?)
public var urlData: String? {
switch self {
case .url(let imageData):
return imageData?.url?.absoluteString
case .image:
return nil
}
}
public var image: UIImage? {
switch self {
case .url:
return nil
case .image(let image):
return image
}
}
public var isEmpty: Bool {
self.image == nil && self.urlData == nil
}
// MARK: - Codable
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.urlData)
}
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let value = try? container.decode(URL.self) {
self = .url(value)
} else if let value = try? container.decode(String.self) {
if value.hasPrefix("ic_") {
self = .image(UIImage(named: value, in: Bundle.main, compatibleWith: nil))
} else {
self = .url(value)
}
self = .url(value)
} else {
self = .url(nil)
}
}
}
extension ImageData: ExpressibleByStringLiteral {
public init(stringLiteral value: String) {
self = .url(value)
}
}
extension ImageData {
public static var userDefault: UIImage = {
UIImage(named: "ic_default_userImg") ?? ImageData.default
}()
public static var userFailure: UIImage = {
UIImage(named: "ic_default_userImg") ?? ImageData.failure
}()
public static var failure: UIImage = {
UIImage(named: "ic_default_image_failure") ?? ImageData.default
}()
public static var `default`: UIImage = {
UIImage(named: "ic_default_image")!
}()
}
| 27.649351 | 90 | 0.58713 |
3a05c2c2d0300a72af061901bea34d184641644a | 552 | //
// Copyright © 2020 Fixique. All rights reserved.
//
import Foundation
/// Base protocol for coordinator
protocol Coordinator: class {
/// Notifies coordinator that it can start itself
func start()
/// Notifies coordinator that it should start itself with deeplink option
///
/// - parameter deepLinkOption: deeplink option such as Dynamic Link, push-notification, etc.
func start(with deepLinkOption: DeepLinkOption?)
/// Notifies coordinator that it should remove all child coordinators
func removeAllChilds()
}
| 30.666667 | 97 | 0.726449 |
3344cea9292b69b2d9c06748e3d1e53d02f5b4a8 | 3,067 | // 394. Decode String Medium
/**
Given an encoded string, return its decoded string.
The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.
You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.
Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4].
Examples:
s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".
*/
/**
Confirm: 1. always right format? number [] and character
2. two or more digits allows?
Solution 1: Stack -- store prev str and number.
*/
class Item {
var num: Int = 0
var str: String = ""
init(num: Int, str: String) {
self.num = num
self.str = str
}
}
class Solution {
func decodeString(_ s: String) -> String {
let chs = Array(s)
var stack = [Item]()
var currNum = 0
var currStr = ""
var res = ""
for i in 0..<chs.count {
if let num = Int(String(chs[i])) {
currNum = currNum*10 + num
} else if chs[i] == "[" {
let curItem = Item.init(num: currNum, str: currStr)
stack.append(curItem)
currNum = 0
currStr = ""
} else if chs[i] == "]" {
let lastItem = stack.removeLast()
var temp = ""
for _ in 0..<lastItem.num {
temp += currStr
}
lastItem.str += temp
currStr = lastItem.str
} else {
currStr += String(chs[i])
}
}
if currStr != "" {
res += currStr
}
return res
}
}
// Another solution with stack
class Item{
var count:Int = 0
var str:String = ""
}
class Solution {
func decodeString(_ s: String) -> String {
let n = s.count
var stack:[Item] = []
let arr = Array(s)
let head = Item()
var curr = head
var num = 0
for i in 0..<n{
let c = arr[i]
if let intVal = Int(String(c)){
num = 10*num + intVal
} else {
if c == "["{
let nItem = Item()
nItem.count = num
stack.append(curr)
curr = nItem
num = 0
}else if c == "]"{
var str = ""
for i in 0..<curr.count{
str += curr.str
}
curr = stack.popLast()!
curr.str += str
}else{
curr.str += String(c)
}
}
}
return head.str
}
} | 28.137615 | 183 | 0.470818 |
28876ca2f4efff2358cb422e6e384fc64f0231ce | 510 | import Foundation
public struct AbiTable : Decodable {
public let name: String
public let index_type: String
public let key_names: Array<String>
public let key_types: Array<String>
public let type: String
public init(name: String, index_type: String, key_names: Array<String>, key_types: Array<String>, type: String) {
self.name = name
self.index_type = index_type
self.key_names = key_names
self.key_types = key_types
self.type = type
}
}
| 28.333333 | 117 | 0.67451 |
ac985b8c1e828d0c229100d42e19da34b7613f03 | 3,072 | //----------------------------------------------------------------------------------------------------------------------
//
// Copyright ©2022 Peter Baumgartner. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//----------------------------------------------------------------------------------------------------------------------
import BXMediaBrowser
import BXSwiftUtils
import Foundation
//----------------------------------------------------------------------------------------------------------------------
class ImageLibrary : GenericLibrary
{
/// Shared singleton instance
static let shared = ImageLibrary(identifier:"ImageLibrary")
/// Creates the basic structure of the ImageLibrary
override init(identifier:String)
{
super.init(identifier:identifier)
let photosSource = PhotosSource(allowedMediaTypes:[.image])
librariesSection?.addSource(photosSource)
if let data = BXKeychain.data(forKey:"api_unsplash_com_accessKey")
{
let key = String(decoding:data, as:UTF8.self)
Unsplash.shared.accessKey = key
let unsplashSource = UnsplashSource()
internetSection?.addSource(unsplashSource)
}
if let data = BXKeychain.data(forKey:"api_pexels_com_accessKey")
{
let key = String(decoding:data, as:UTF8.self)
Pexels.shared.accessKey = key
let pexelsSource = PexelsPhotoSource()
internetSection?.addSource(pexelsSource)
}
let folderSource = ImageFolderSource()
self.folderSource = folderSource
foldersSection?.addSource(folderSource)
self.load(with:self.state)
}
/// Creates a ImageFolderContainer for the specified folder URL
override func createContainer(for url:URL) -> FolderContainer
{
let filter = self.folderSource?.filter as? FolderFilter ?? FolderFilter()
return ImageFolderContainer(url:url, filter:filter)
{
[weak self] in self?.removeTopLevelFolder($0)
}
}
}
//----------------------------------------------------------------------------------------------------------------------
| 34.133333 | 120 | 0.628581 |
9c4c7e833abfb07c5bc4cb5aca041b1c906dd7e7 | 465 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
class B{class A<b where g:d{struct B{let a=B{{{{}}}}let w}struct B
| 46.5 | 79 | 0.739785 |
7688f083d56e3c2e92274af823842a13c5487f1e | 1,427 | //
// AppDelegate.swift
// SpacePhoto
//
// Created by Armando Carrillo on 02/08/20.
// Copyright © 2020 Armando Carrillo. All rights reserved.
//
import UIKit
@UIApplicationMain
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.
}
}
| 37.552632 | 179 | 0.749124 |
38a89074136240d50aabd3978dbb9f87600acd55 | 1,563 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
An `NSWindowController` subclass to simplify the game's interaction with window resizing on OS X.
*/
import Cocoa
import SpriteKit
class GameWindowController: NSWindowController, NSWindowDelegate {
// MARK: Properties
var view: SKView {
let gameViewController = window!.contentViewController as! GameViewController
return gameViewController.view as! SKView
}
override func awakeFromNib() {
super.awakeFromNib()
window?.delegate = self
}
// MARK: NSWindowDelegate
func windowWillStartLiveResize(notification: NSNotification) {
// Pause the scene while the window resizes if the game is active.
if let levelScene = view.scene as? LevelScene where levelScene.stateMachine.currentState is LevelSceneActiveState {
levelScene.paused = true
}
}
func windowDidEndLiveResize(notification: NSNotification) {
// Un-pause the scene when the window stops resizing if the game is active.
if let levelScene = view.scene as? LevelScene where levelScene.stateMachine.currentState is LevelSceneActiveState {
levelScene.paused = false
}
}
// OS X games that use a single window for the entire game should quit when that window is closed.
func applicationShouldTerminateAfterLastWindowClosed(sender: NSApplication) -> Bool {
return true
}
}
| 33.255319 | 123 | 0.692258 |
eff5e2fc99a5fade85523606be8a82e5a89a9b07 | 7,448 | // Copyright © 2015 Venture Media Labs. All rights reserved.
//
// This file is part of PlotKit. The full PlotKit copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.
import Foundation
internal class AxisView: NSView {
var insets = EdgeInsets(top: 40, left: 60, bottom: 40, right: 60)
var axis: Axis {
didSet {
needsDisplay = true
}
}
var xInterval = 0.0...1.0 {
didSet {
needsDisplay = true
}
}
var yInterval = 0.0...1.0 {
didSet {
needsDisplay = true
}
}
init(axis: Axis) {
self.axis = axis
super.init(frame: NSRect(x: 0, y: 0, width: 512, height: 512))
}
// MARK: - NSView overrides
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect) {
axis.color.setFill()
switch axis.orientation {
case .vertical:
drawVertical(rect)
case .horizontal:
drawHorizontal(rect)
}
}
override var intrinsicContentSize: NSSize {
switch axis.orientation {
case .horizontal:
var height = CGFloat(0)
for tick in axis.ticks.ticksInInterval(xInterval) {
let string = tick.label as NSString
let size = string.size(withAttributes: axis.labelAttributes)
if size.height > height {
height = size.height
}
}
return NSSize(width: NSViewNoIntrinsicMetric, height: height)
case .vertical:
var width = CGFloat(0)
for tick in axis.ticks.ticksInInterval(yInterval) {
let string = tick.label as NSString
let size = string.size(withAttributes: axis.labelAttributes)
if size.width > width {
width = size.width
}
}
return NSSize(width: width, height: NSViewNoIntrinsicMetric)
}
}
// MARK: - Helper functions
func drawVertical(_ rect: CGRect) {
var cappedInsets = insets
if insets.left + insets.right >= bounds.width {
cappedInsets.left = 0
cappedInsets.right = 0
}
if insets.top + insets.bottom >= bounds.height {
cappedInsets.top = 0
cappedInsets.bottom = 0
}
let boundsXInterval = Double(bounds.minX + cappedInsets.left)...Double(bounds.maxX - cappedInsets.right)
let boundsYInterval = Double(bounds.minY + cappedInsets.bottom)...Double(bounds.maxY - cappedInsets.top)
guard let context = NSGraphicsContext.current()?.cgContext else {
return
}
let width = CGFloat(axis.lineWidth)
let height = bounds.height - insets.top - insets.bottom
// Draw axis line
let x: CGFloat
switch axis.position {
case .start:
x = CGFloat(boundsXInterval.lowerBound) + width/2
case .end:
x = CGFloat(boundsXInterval.upperBound) - width/2
case .value(let position):
x = CGFloat(mapValue(position, fromInterval: xInterval, toInterval: boundsXInterval))
}
let axisRect = CGRect(x: x - width/2, y: CGFloat(boundsYInterval.lowerBound), width: width, height: height)
context.fill(axisRect)
// Draw tick marks
var lastTextFrame = NSRect()
for tick in axis.ticks.ticksInInterval(yInterval) {
if !yInterval.contains(tick.value) {
continue
}
let y = CGFloat(mapValue(tick.value, fromInterval: yInterval, toInterval: boundsYInterval))
let rect = NSRect(
x: x - tick.lineLength/2,
y: y - tick.lineWidth/2,
width: tick.lineLength,
height: tick.lineWidth)
context.fill(rect)
let string = tick.label as NSString
let size = string.size(withAttributes: axis.labelAttributes)
let point: NSPoint
switch axis.position {
case .start, .value:
point = NSPoint(
x: x - size.width - tick.lineLength,
y: y - size.height/2)
case .end:
point = NSPoint(
x: x + tick.lineLength,
y: y - size.height/2)
}
let frame = NSRect(origin: point, size: size)
if !lastTextFrame.intersects(frame) {
string.draw(at: point, withAttributes: axis.labelAttributes)
lastTextFrame = frame
}
}
}
func drawHorizontal(_ rect: CGRect) {
var cappedInsets = insets
if insets.left + insets.right >= bounds.width {
cappedInsets.left = 0
cappedInsets.right = 0
}
if insets.top + insets.bottom >= bounds.height {
cappedInsets.top = 0
cappedInsets.bottom = 0
}
let boundsXInterval = Double(bounds.minX + cappedInsets.left)...Double(bounds.maxX - cappedInsets.right)
let boundsYInterval = Double(bounds.minY + cappedInsets.bottom)...Double(bounds.maxY - cappedInsets.top)
guard let context = NSGraphicsContext.current()?.cgContext else {
return
}
let width = bounds.width - insets.left - insets.right
let height = CGFloat(axis.lineWidth)
// Draw axis line
let y: CGFloat
switch axis.position {
case .start:
y = CGFloat(boundsYInterval.lowerBound) + height/2
case .end:
y = CGFloat(boundsYInterval.upperBound) - height/2
case .value(let position):
y = CGFloat(mapValue(position, fromInterval: yInterval, toInterval: boundsYInterval))
}
let axisRect = CGRect(x: CGFloat(boundsXInterval.lowerBound), y: y - height/2, width: width, height: height)
context.fill(axisRect)
// Draw tick marks
var lastTextFrame = NSRect()
for tick in axis.ticks.ticksInInterval(xInterval) {
if !xInterval.contains(tick.value) {
continue
}
let x = CGFloat(mapValue(tick.value, fromInterval: xInterval, toInterval: boundsXInterval))
let rect = CGRect(
x: x - tick.lineWidth/2,
y: y - tick.lineLength/2,
width: tick.lineWidth,
height: tick.lineLength)
context.fill(rect)
let string = tick.label as NSString
let size = string.size(withAttributes: axis.labelAttributes)
var point: NSPoint
switch axis.position {
case .start, .value:
point = NSPoint(
x: x - size.width/2,
y: y - size.height)
case .end:
point = NSPoint(
x: x - size.width/2,
y: y + tick.lineLength)
}
let frame = NSRect(origin: point, size: size)
if !lastTextFrame.intersects(frame) {
string.draw(at: point, withAttributes: axis.labelAttributes)
lastTextFrame = frame
}
}
}
}
| 33.25 | 116 | 0.55196 |
ed56e510465fc37bdf86279d7e0469318ad17e79 | 19,822 | //
// AssetManager.swift
// CalculatorPhotoVault
//
// Created by ljk on 17/2/21.
// Copyright © 2017年 Tracy. All rights reserved.
//
import UIKit
import Photos
import Common
import FileKit
public typealias ExportImageBlock = (Data?, String?, UIImageOrientation, [AnyHashable : Any]?, PHAsset, URL) -> Swift.Void
public typealias ExportVideoBlock = (_ asset: PHAsset,_ fileURL: URL) -> Swift.Void
public typealias ExportProgressBlock = (Double) -> Swift.Void
public class AssetManager: NSObject {
fileprivate var exportAssets: [PHAsset]?
fileprivate var exportFilesPath: [String]!
fileprivate var requestID: PHImageRequestID?
fileprivate var exportSession: AVAssetExportSession?
fileprivate var finishedCount = 0
fileprivate var unExportCount = 0
fileprivate var totalCount = 0
// fileprivate var exportImageBlock: ExportImageBlock?
// fileprivate var exportVideoBlock: ExportVideoBlock?
public var fileSizeCallBack: ((Int64)->Void)?
fileprivate var callBack: ((String, PHAsset)->Void)?
fileprivate var progressBlock: ExportProgressBlock?
fileprivate var completionHandler: ((_ result: Bool, _ filesPath: [String]) -> Swift.Void)?
fileprivate var isCancel = false
fileprivate var directory: File! //导入沙盒的路径
fileprivate var timer: Timer?
static private let descriptor = NSSortDescriptor(key: "creationDate", ascending: false)
public static var thumbnailSize: CGSize = {
let size = CGSize(width: 70 * UIScreen.main.scale, height: 70 * UIScreen.main.scale)
return size
}()
static var thumbnailDegradedSize: CGSize = {
let size = CGSize(width: 10, height: 10)
return size
}()
// init() {
//
// }
}
// MARK: - ExportAsset
public extension AssetManager {
public func exportAssets(_ assets: [PHAsset], at path: String ,progressBlock: @escaping ExportProgressBlock, callBack: @escaping (String, PHAsset)->Void ,completionHandler: @escaping (_ result: Bool, _ filesPath: [String]) -> Swift.Void) {
self.directory = File(path: path)
self.exportFilesPath = [String]()
self.exportAssets = assets
self.progressBlock = progressBlock
self.callBack = callBack
self.completionHandler = completionHandler
self.totalCount = assets.count
self.isCancel = false
self.progressBlock?(0)
processAssets()
let timer = Timer(timeInterval: 0.5, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
RunLoop.current.add(timer, forMode: .commonModes)
self.timer = timer
}
private func processAssets() {
guard isCancel == false else { return }
if let assets = exportAssets, let item = assets.first {
exportAssets?.removeFirst()
self.exportSession = nil
switch item.mediaType {
case .image:
let id = requestImageData(with: item)
requestID = id
case .video:
getAVAssetAndExport(asset: item, completion: { (asset) in
if let asset = asset {
let id = self.exportVideo(asset, phasset: item)
self.requestID = id
} else {
self.unExportCount += 1
self.processAssets()
}
})
default:
unExportCount += 1
self.processAssets()
}
} else {
endTask(true)
}
}
private func requestImageData(with asset: PHAsset) -> PHImageRequestID {
let requestOptions = PHImageRequestOptions()
requestOptions.isSynchronous = false
requestOptions.deliveryMode = .highQualityFormat
requestOptions.isNetworkAccessAllowed = true
requestOptions.progressHandler = { [weak self] (progress, _, _, _) in
guard let `self` = self else { return }
self.processProgress(progress)
}
let id = PHImageManager.default().requestImageData(for: asset, options: requestOptions, resultHandler: { (imageData, uti, imageOrientation, info) in
if let data = imageData, self.fileSizeCallBack != nil {
self.fileSizeCallBack?(Int64(data.count))
}
let name = self.assetName(asset, info: info)
DispatchQueue.global(qos: .default).async(execute: {
if let file = AssetManager.saveImage(with: imageData, fileName: name, to: self.directory) {
self.exportFilesPath?.append(file.path)
self.callBack?(file.path, asset)
}
self.finishedCount += 1
self.processProgress()
self.processAssets()
})
})
return id
}
static func saveImage(with data: Data?, fileName: String?, to directory: File) -> File? {
guard let data = data, let fileName = fileName else { return nil }
let name = File.notDuplicatedName(for: fileName, underDirectory: directory)
if let file = try? File.createFile(name: name, data: data, underDirectory: directory) {
let image = UIImage(data: data)
if let thumbnail = image?.aspectScaled(toFill: self.thumbnailSize) {
file.saveThumbnail(thumbnail)
}
if let thumbnailDegraded = image?.aspectScaled(toFill: self.thumbnailDegradedSize) {
file.saveThumbnailDegraded(thumbnailDegraded)
}
return file
} else {
return nil
}
}
private func getAVAssetAndExport(asset: PHAsset, completion: @escaping (AVAsset?)->Void ) {
let requestOptions = PHVideoRequestOptions()
requestOptions.deliveryMode = .highQualityFormat
requestOptions.isNetworkAccessAllowed = true
PHImageManager.default().requestAVAsset(forVideo: asset, options: requestOptions) { [weak self] (asset, _, _) in
guard let `self` = self else { return }
if self.fileSizeCallBack != nil {
if let urlAsset = asset as? AVURLAsset, let resources = try? urlAsset.url.resourceValues(forKeys: [.fileSizeKey]), let fileSize = resources.fileSize {
self.fileSizeCallBack?(Int64(fileSize))
}
}
completion(asset)
}
}
private func exportVideo(_ asset: AVAsset, phasset: PHAsset) -> PHImageRequestID {
let requestOptions = PHVideoRequestOptions()
requestOptions.deliveryMode = .highQualityFormat
requestOptions.isNetworkAccessAllowed = true
requestOptions.progressHandler = { [weak self] (progress, error, stop, info) in
guard let `self` = self else { return }
self.processProgress(progress)
}
let id = PHImageManager.default().requestExportSession(forVideo: phasset, options: requestOptions, exportPreset: AVAssetExportPresetPassthrough) { [weak self] (exportSession, info) in
guard let `self` = self else { return }
if let session = exportSession {
let path = URL(fileURLWithPath: self.directory.path)
let fileName = self.assetName(phasset, info: info)
let notDuplicatedName = File.notDuplicatedName(for: fileName, underDirectory: self.directory)
let filePath = path.appendingPathComponent(notDuplicatedName)
session.outputFileType = session.supportedFileTypes.first ?? self.outputFileType(filePath.pathExtension)
session.outputURL = filePath
let videoComposition = self.fixedComposition(with: asset)
if videoComposition.renderSize.width != 0 {
session.videoComposition = videoComposition
}
self.exportSession = session
session.exportAsynchronously { [weak self] in
guard let `self` = self else { return }
self.saveThumbnail(phasset, to: filePath.path)
self.exportFilesPath.append(filePath.path)
self.callBack?(filePath.path, phasset)
self.finishedCount += 1
self.processProgress()
self.processAssets()
}
} else {
self.unExportCount += 1
self.processAssets()
}
}
return id
}
private func fixedComposition(with videoAsset: AVAsset) -> AVMutableVideoComposition {
let degress = degreeFromVideoAsset(videoAsset)
//旋转
let videoComposition = AVMutableVideoComposition()
if degress != 0, let videoTrack = videoAsset.tracks(withMediaType: AVMediaType.video).first {
var translateToCenter: CGAffineTransform
var mixedTransform: CGAffineTransform
videoComposition.frameDuration = videoTrack.minFrameDuration
let rotateInstruction = AVMutableVideoCompositionInstruction()
rotateInstruction.timeRange = CMTimeRange(start: kCMTimeZero, duration: videoAsset.duration)
let rotateLayerInstruction = AVMutableVideoCompositionLayerInstruction(assetTrack: videoTrack)
if degress == 90 {
// 顺时针旋转90°
translateToCenter = CGAffineTransform(translationX: videoTrack.naturalSize.height, y: 0.0)
mixedTransform = translateToCenter.rotated(by: .pi / 2.0)
videoComposition.renderSize = CGSize(width: videoTrack.naturalSize.height, height: videoTrack.naturalSize.width)
rotateLayerInstruction.setTransform(mixedTransform, at: kCMTimeZero)
} else if degress == 180 {
// 顺时针旋转180°
translateToCenter = CGAffineTransform(translationX: videoTrack.naturalSize.width, y: videoTrack.naturalSize.height)
mixedTransform = translateToCenter.rotated(by: .pi)
videoComposition.renderSize = CGSize(width: videoTrack.naturalSize.width, height: videoTrack.naturalSize.height)
rotateLayerInstruction.setTransform(mixedTransform, at: kCMTimeZero)
} else if degress == 270 {
// 顺时针旋转270°
translateToCenter = CGAffineTransform(translationX: 0.0, y: videoTrack.naturalSize.width)
mixedTransform = translateToCenter.rotated(by: .pi * 3.0 / 2.0)
videoComposition.renderSize = CGSize(width: videoTrack.naturalSize.height, height: videoTrack.naturalSize.width)
rotateLayerInstruction.setTransform(mixedTransform, at: kCMTimeZero)
}
rotateInstruction.layerInstructions = [rotateLayerInstruction]
videoComposition.instructions = [rotateInstruction]
}
return videoComposition
}
private func degreeFromVideoAsset(_ asset: AVAsset) -> Int {
var degress = 0
let tracks = asset.tracks(withMediaType: AVMediaType.video)
if let videoTrack = tracks.first {
let t = videoTrack.preferredTransform
if t.a == 0, t.b == 1, t.c == -1.0, t.d == 0 {
// Portrait
degress = 90
}else if (t.a == 0 && t.b == -1.0 && t.c == 1.0 && t.d == 0) {
// PortraitUpsideDown
degress = 270
}else if (t.a == 1.0 && t.b == 0 && t.c == 0 && t.d == 1.0) {
// LandscapeRight
degress = 0
}else if (t.a == -1.0 && t.b == 0 && t.c == 0 && t.d == -1.0) {
// LandscapeLeft
degress = 180
}
}
return degress
}
private func saveThumbnail(_ asset: PHAsset, to path: String) {
let requestOptions = PHImageRequestOptions()
requestOptions.isSynchronous = true
requestOptions.deliveryMode = .highQualityFormat
requestOptions.isNetworkAccessAllowed = true
guard let file = File(path: path) else { return }
file.saveDuraction(Int(asset.duration))
PHImageManager.default().requestImage(for: asset, targetSize: AssetManager.thumbnailSize, contentMode: .aspectFill, options: requestOptions) { (image, _) in
file.saveThumbnail(image)
let thumbnailDegrade = image?.aspectScaled(toFill: AssetManager.thumbnailDegradedSize)
file.saveThumbnailDegraded(thumbnailDegrade)
}
}
private func outputFileType(_ extention: String) -> AVFileType {
var type = AVFileType.mov
if isEqualInsensitive(extention, second: "mov"){
type = AVFileType.mov
} else if isEqualInsensitive(extention, second: "mp4") {
type = AVFileType.mp4
} else if isEqualInsensitive(extention, second: "m4v") {
type = AVFileType.m4v
} else if isEqualInsensitive(extention, second: "m4a") {
type = AVFileType.m4a
} else if isEqualInsensitive(extention, second: "3gp") {
type = AVFileType.mobile3GPP
} else if isEqualInsensitive(extention, second: "wav") {
type = AVFileType.wav
}
return type
}
private func isEqualInsensitive(_ first: String, second: String) -> Bool {
let result = first.caseInsensitiveCompare(second) == .orderedSame
return result
}
fileprivate func assetName(_ asset: PHAsset, info: [AnyHashable : Any]?) -> String {
if #available(iOS 9.0, *) {
let resources = PHAssetResource.assetResources(for: asset)
if let fileName = resources.first?.originalFilename {
return fileName
}
} else {
// Fallback on earlier versions
if let fileURL = info?["PHImageFileURLKey"] as? URL {
return FileManager.default.displayName(atPath: fileURL.path)
}
}
if let fileName = asset.value(forKey: "filename") as? String {
return fileName
}
if asset.mediaType == .video {
return "IMG_01.mov"
} else {
return "IMG_01.jpg"
}
}
@objc private func timerAction() {
guard let progress = exportSession?.progress, progress > 0 else { return }
self.processProgress(Double(progress))
}
private func processProgress(_ networkProgress: Double = 0) {
let current = Double(self.finishedCount + self.unExportCount) + networkProgress
let total = Double(self.totalCount)
let progress = current/total
DispatchQueue.main.async {
self.progressBlock?(min(progress, 1))
}
}
private func endTask(_ finished: Bool) {
DispatchQueue.main.async(execute: {
self.completionHandler?(finished, self.exportFilesPath)
self.clean()
})
}
public func cancel() {
self.isCancel = true
exportAssets?.removeAll()
if let id = requestID {
PHImageManager.default().cancelImageRequest(id)
}
if let session = exportSession {
session.cancelExport()
}
endTask(false)
}
private func clean() {
self.exportAssets = nil
self.progressBlock = nil
self.callBack = nil
self.fileSizeCallBack = nil
// self.exportImageBlock = nil
// self.exportVideoBlock = nil
self.completionHandler = nil
self.requestID = nil
self.exportSession = nil
self.finishedCount = 0
self.unExportCount = 0
self.timer?.invalidate()
self.timer = nil
}
}
// MARK: - Import、Delete
extension AssetManager {
static public func saveImage(url imageURL: URL, resultHandler: @escaping (_ success: Bool, _ error: Error?, _ localIdentifier: String?)
->
Swift.Void) {
var identifier: String?
PHPhotoLibrary.shared().performChanges({
let url = imageURL
if #available(iOS 9.0, *) {
let creationRequest = PHAssetCreationRequest.forAsset()
creationRequest.addResource(with: .photo, fileURL: url, options: nil)
identifier = creationRequest.placeholderForCreatedAsset?.localIdentifier
} else {
// Fallback on earlier versions
let request = PHAssetChangeRequest.creationRequestForAssetFromImage(atFileURL: url)
identifier = request?.placeholderForCreatedAsset?.localIdentifier
}
}) { (success, error) in
DispatchQueue.main.async {
resultHandler(success, error, identifier)
}
}
}
static public func saveImage(image: UIImage, resultHandler: @escaping (_ success: Bool, _ error: Error?, _ localIdentifier: String?)
->
Swift.Void) {
var identifier: String?
PHPhotoLibrary.shared().performChanges({
let request = PHAssetChangeRequest.creationRequestForAsset(from: image)
identifier = request.placeholderForCreatedAsset?.localIdentifier
}) { (success, error) in
DispatchQueue.main.async {
resultHandler(success, error, identifier)
}
}
}
static public func saveVideo(_ videoURL:URL, resultHandler: @escaping (_ success: Bool, _ error: Error?, _ localIdentifier: String?) -> Swift.Void) {
var identifier: String?
PHPhotoLibrary.shared().performChanges({
let request = PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: videoURL)
identifier = request?.placeholderForCreatedAsset?.localIdentifier
}) { (success, error) in
DispatchQueue.main.async {
resultHandler(success, error, identifier)
}
}
}
@available(iOS 9.1, *)
static public func saveLivePhoto(imageURL: URL, videoURL: URL, resultHandler: @escaping (_ success: Bool, _ error: Error?, _ localIdentifier: String?) -> Swift.Void) {
var identifier: String?
PHPhotoLibrary.shared().performChanges({
let request = PHAssetCreationRequest.forAsset()
request.addResource(with: .photo, fileURL: imageURL, options: nil)
request.addResource(with: .pairedVideo, fileURL: videoURL, options: nil)
identifier = request.placeholderForCreatedAsset?.localIdentifier
}) { (success, error) in
DispatchQueue.main.async {
resultHandler(success, error, identifier)
}
}
}
static public func deleteAsset(_ assets: [PHAsset], completionHandler: ((Bool, Error?) -> Swift.Void)? = nil) {
PHPhotoLibrary.shared().performChanges({
PHAssetChangeRequest.deleteAssets(assets as NSFastEnumeration)
}) { (success, error) in
DispatchQueue.main.async {
completionHandler?(success, error)
}
}
}
}
| 39.56487 | 243 | 0.587832 |
dbbf0ee13f8ec905d4ac8211ce0a1eccbc04e989 | 1,947 | //
// BadgeBackground.swift
// LandmarksSwiftUI
//
// Created by Steve Wall on 6/5/21.
//
import SwiftUI
struct BadgeBackground: View {
var body: some View {
GeometryReader { geometry in
Path { path in
var width: CGFloat = min(geometry.size.width, geometry.size.height)
let height = width
let xScale: CGFloat = 0.832
let xOffset = (width * (1.0 - xScale)) / 2.0
width *= xScale
// Add a starting point to the path assuming a container with size 100x100px.
path.move(
to: CGPoint(
x: width * 0.95 + xOffset,
y: height * (0.20 + HexagonParameters.adjustment)
)
)
// Draw the lines for each point of the shape data to create a rough hexagonal shape.
HexagonParameters.segments.forEach { segment in
// Add the lines
path.addLine(
to: CGPoint(
x: width * segment.line.x + xOffset,
y: height * segment.line.y
)
)
// Add the curves
path.addQuadCurve(
to: CGPoint(
x: width * segment.curve.x + xOffset,
y: height * segment.curve.y
),
control: CGPoint(
x: width * segment.control.x + xOffset,
y: height * segment.control.y
)
)
}
}
.fill(
LinearGradient(
gradient: Gradient(colors: [Self.gradientStart, Self.gradientEnd]),
startPoint: UnitPoint(x: 0.5, y: 0),
endPoint: UnitPoint(x: 0.5, y: 0.6)
)
)
}
}
static let gradientStart = Color(red: 239.0/255, green: 120.0/255, blue: 221.0/255)
static let gradientEnd = Color(red: 239.0/255, green: 172.0/255, blue: 120.0/255)
}
struct BadgeBackground_Previews: PreviewProvider {
static var previews: some View {
BadgeBackground()
}
}
| 28.217391 | 93 | 0.540318 |
56d6e627f0f0ef329a2e1c873091703a1a9a713e | 58,316 | //
// Awesome.swift
// AwesomeEnum
//
// Originally created by Ondrej Rafaj on 13/10/2017.
// Copyright © 2017 manGoweb UK. All rights reserved.
//
// This file has been auto-generated on 19/08/2021 12:17.
import Foundation
public struct Awesome {
public enum Solid: String, Amazing {
case ad = "\u{f641}"
case addressBook = "\u{f2b9}"
case addressCard = "\u{f2bb}"
case adjust = "\u{f042}"
case airFreshener = "\u{f5d0}"
case alignCenter = "\u{f037}"
case alignJustify = "\u{f039}"
case alignLeft = "\u{f036}"
case alignRight = "\u{f038}"
case allergies = "\u{f461}"
case ambulance = "\u{f0f9}"
case americanSignLanguageInterpreting = "\u{f2a3}"
case anchor = "\u{f13d}"
case angleDoubleDown = "\u{f103}"
case angleDoubleLeft = "\u{f100}"
case angleDoubleRight = "\u{f101}"
case angleDoubleUp = "\u{f102}"
case angleDown = "\u{f107}"
case angleLeft = "\u{f104}"
case angleRight = "\u{f105}"
case angleUp = "\u{f106}"
case angry = "\u{f556}"
case ankh = "\u{f644}"
case appleAlt = "\u{f5d1}"
case archive = "\u{f187}"
case archway = "\u{f557}"
case arrowAltCircleDown = "\u{f358}"
case arrowAltCircleLeft = "\u{f359}"
case arrowAltCircleRight = "\u{f35a}"
case arrowAltCircleUp = "\u{f35b}"
case arrowCircleDown = "\u{f0ab}"
case arrowCircleLeft = "\u{f0a8}"
case arrowCircleRight = "\u{f0a9}"
case arrowCircleUp = "\u{f0aa}"
case arrowDown = "\u{f063}"
case arrowLeft = "\u{f060}"
case arrowRight = "\u{f061}"
case arrowUp = "\u{f062}"
case arrowsAlt = "\u{f0b2}"
case arrowsAltH = "\u{f337}"
case arrowsAltV = "\u{f338}"
case assistiveListeningSystems = "\u{f2a2}"
case asterisk = "\u{f069}"
case at = "\u{f1fa}"
case atlas = "\u{f558}"
case atom = "\u{f5d2}"
case audioDescription = "\u{f29e}"
case award = "\u{f559}"
case baby = "\u{f77c}"
case babyCarriage = "\u{f77d}"
case backspace = "\u{f55a}"
case backward = "\u{f04a}"
case bacon = "\u{f7e5}"
case bacteria = "\u{e059}"
case bacterium = "\u{e05a}"
case bahai = "\u{f666}"
case balanceScale = "\u{f24e}"
case balanceScaleLeft = "\u{f515}"
case balanceScaleRight = "\u{f516}"
case ban = "\u{f05e}"
case bandAid = "\u{f462}"
case barcode = "\u{f02a}"
case bars = "\u{f0c9}"
case baseballBall = "\u{f433}"
case basketballBall = "\u{f434}"
case bath = "\u{f2cd}"
case batteryEmpty = "\u{f244}"
case batteryFull = "\u{f240}"
case batteryHalf = "\u{f242}"
case batteryQuarter = "\u{f243}"
case batteryThreeQuarters = "\u{f241}"
case bed = "\u{f236}"
case beer = "\u{f0fc}"
case bell = "\u{f0f3}"
case bellSlash = "\u{f1f6}"
case bezierCurve = "\u{f55b}"
case bible = "\u{f647}"
case bicycle = "\u{f206}"
case biking = "\u{f84a}"
case binoculars = "\u{f1e5}"
case biohazard = "\u{f780}"
case birthdayCake = "\u{f1fd}"
case blender = "\u{f517}"
case blenderPhone = "\u{f6b6}"
case blind = "\u{f29d}"
case blog = "\u{f781}"
case bold = "\u{f032}"
case bolt = "\u{f0e7}"
case bomb = "\u{f1e2}"
case bone = "\u{f5d7}"
case bong = "\u{f55c}"
case book = "\u{f02d}"
case bookDead = "\u{f6b7}"
case bookMedical = "\u{f7e6}"
case bookOpen = "\u{f518}"
case bookReader = "\u{f5da}"
case bookmark = "\u{f02e}"
case borderAll = "\u{f84c}"
case borderNone = "\u{f850}"
case borderStyle = "\u{f853}"
case bowlingBall = "\u{f436}"
case box = "\u{f466}"
case boxOpen = "\u{f49e}"
case boxTissue = "\u{e05b}"
case boxes = "\u{f468}"
case braille = "\u{f2a1}"
case brain = "\u{f5dc}"
case breadSlice = "\u{f7ec}"
case briefcase = "\u{f0b1}"
case briefcaseMedical = "\u{f469}"
case broadcastTower = "\u{f519}"
case broom = "\u{f51a}"
case brush = "\u{f55d}"
case bug = "\u{f188}"
case building = "\u{f1ad}"
case bullhorn = "\u{f0a1}"
case bullseye = "\u{f140}"
case burn = "\u{f46a}"
case bus = "\u{f207}"
case busAlt = "\u{f55e}"
case businessTime = "\u{f64a}"
case calculator = "\u{f1ec}"
case calendar = "\u{f133}"
case calendarAlt = "\u{f073}"
case calendarCheck = "\u{f274}"
case calendarDay = "\u{f783}"
case calendarMinus = "\u{f272}"
case calendarPlus = "\u{f271}"
case calendarTimes = "\u{f273}"
case calendarWeek = "\u{f784}"
case camera = "\u{f030}"
case cameraRetro = "\u{f083}"
case campground = "\u{f6bb}"
case candyCane = "\u{f786}"
case cannabis = "\u{f55f}"
case capsules = "\u{f46b}"
case car = "\u{f1b9}"
case carAlt = "\u{f5de}"
case carBattery = "\u{f5df}"
case carCrash = "\u{f5e1}"
case carSide = "\u{f5e4}"
case caravan = "\u{f8ff}"
case caretDown = "\u{f0d7}"
case caretLeft = "\u{f0d9}"
case caretRight = "\u{f0da}"
case caretSquareDown = "\u{f150}"
case caretSquareLeft = "\u{f191}"
case caretSquareRight = "\u{f152}"
case caretSquareUp = "\u{f151}"
case caretUp = "\u{f0d8}"
case carrot = "\u{f787}"
case cartArrowDown = "\u{f218}"
case cartPlus = "\u{f217}"
case cashRegister = "\u{f788}"
case cat = "\u{f6be}"
case certificate = "\u{f0a3}"
case chair = "\u{f6c0}"
case chalkboard = "\u{f51b}"
case chalkboardTeacher = "\u{f51c}"
case chargingStation = "\u{f5e7}"
case chartArea = "\u{f1fe}"
case chartBar = "\u{f080}"
case chartLine = "\u{f201}"
case chartPie = "\u{f200}"
case check = "\u{f00c}"
case checkCircle = "\u{f058}"
case checkDouble = "\u{f560}"
case checkSquare = "\u{f14a}"
case cheese = "\u{f7ef}"
case chess = "\u{f439}"
case chessBishop = "\u{f43a}"
case chessBoard = "\u{f43c}"
case chessKing = "\u{f43f}"
case chessKnight = "\u{f441}"
case chessPawn = "\u{f443}"
case chessQueen = "\u{f445}"
case chessRook = "\u{f447}"
case chevronCircleDown = "\u{f13a}"
case chevronCircleLeft = "\u{f137}"
case chevronCircleRight = "\u{f138}"
case chevronCircleUp = "\u{f139}"
case chevronDown = "\u{f078}"
case chevronLeft = "\u{f053}"
case chevronRight = "\u{f054}"
case chevronUp = "\u{f077}"
case child = "\u{f1ae}"
case church = "\u{f51d}"
case circle = "\u{f111}"
case circleNotch = "\u{f1ce}"
case city = "\u{f64f}"
case clinicMedical = "\u{f7f2}"
case clipboard = "\u{f328}"
case clipboardCheck = "\u{f46c}"
case clipboardList = "\u{f46d}"
case clock = "\u{f017}"
case clone = "\u{f24d}"
case closedCaptioning = "\u{f20a}"
case cloud = "\u{f0c2}"
case cloudDownloadAlt = "\u{f381}"
case cloudMeatball = "\u{f73b}"
case cloudMoon = "\u{f6c3}"
case cloudMoonRain = "\u{f73c}"
case cloudRain = "\u{f73d}"
case cloudShowersHeavy = "\u{f740}"
case cloudSun = "\u{f6c4}"
case cloudSunRain = "\u{f743}"
case cloudUploadAlt = "\u{f382}"
case cocktail = "\u{f561}"
case code = "\u{f121}"
case codeBranch = "\u{f126}"
case coffee = "\u{f0f4}"
case cog = "\u{f013}"
case cogs = "\u{f085}"
case coins = "\u{f51e}"
case columns = "\u{f0db}"
case comment = "\u{f075}"
case commentAlt = "\u{f27a}"
case commentDollar = "\u{f651}"
case commentDots = "\u{f4ad}"
case commentMedical = "\u{f7f5}"
case commentSlash = "\u{f4b3}"
case comments = "\u{f086}"
case commentsDollar = "\u{f653}"
case compactDisc = "\u{f51f}"
case compass = "\u{f14e}"
case compress = "\u{f066}"
case compressAlt = "\u{f422}"
case compressArrowsAlt = "\u{f78c}"
case conciergeBell = "\u{f562}"
case cookie = "\u{f563}"
case cookieBite = "\u{f564}"
case copy = "\u{f0c5}"
case copyright = "\u{f1f9}"
case couch = "\u{f4b8}"
case creditCard = "\u{f09d}"
case crop = "\u{f125}"
case cropAlt = "\u{f565}"
case cross = "\u{f654}"
case crosshairs = "\u{f05b}"
case crow = "\u{f520}"
case crown = "\u{f521}"
case crutch = "\u{f7f7}"
case cube = "\u{f1b2}"
case cubes = "\u{f1b3}"
case cut = "\u{f0c4}"
case database = "\u{f1c0}"
case deaf = "\u{f2a4}"
case democrat = "\u{f747}"
case desktop = "\u{f108}"
case dharmachakra = "\u{f655}"
case diagnoses = "\u{f470}"
case dice = "\u{f522}"
case diceD20 = "\u{f6cf}"
case diceD6 = "\u{f6d1}"
case diceFive = "\u{f523}"
case diceFour = "\u{f524}"
case diceOne = "\u{f525}"
case diceSix = "\u{f526}"
case diceThree = "\u{f527}"
case diceTwo = "\u{f528}"
case digitalTachograph = "\u{f566}"
case directions = "\u{f5eb}"
case disease = "\u{f7fa}"
case divide = "\u{f529}"
case dizzy = "\u{f567}"
case dna = "\u{f471}"
case dog = "\u{f6d3}"
case dollarSign = "\u{f155}"
case dolly = "\u{f472}"
case dollyFlatbed = "\u{f474}"
case donate = "\u{f4b9}"
case doorClosed = "\u{f52a}"
case doorOpen = "\u{f52b}"
case dotCircle = "\u{f192}"
case dove = "\u{f4ba}"
case download = "\u{f019}"
case draftingCompass = "\u{f568}"
case dragon = "\u{f6d5}"
case drawPolygon = "\u{f5ee}"
case drum = "\u{f569}"
case drumSteelpan = "\u{f56a}"
case drumstickBite = "\u{f6d7}"
case dumbbell = "\u{f44b}"
case dumpster = "\u{f793}"
case dumpsterFire = "\u{f794}"
case dungeon = "\u{f6d9}"
case edit = "\u{f044}"
case egg = "\u{f7fb}"
case eject = "\u{f052}"
case ellipsisH = "\u{f141}"
case ellipsisV = "\u{f142}"
case envelope = "\u{f0e0}"
case envelopeOpen = "\u{f2b6}"
case envelopeOpenText = "\u{f658}"
case envelopeSquare = "\u{f199}"
case equals = "\u{f52c}"
case eraser = "\u{f12d}"
case ethernet = "\u{f796}"
case euroSign = "\u{f153}"
case exchangeAlt = "\u{f362}"
case exclamation = "\u{f12a}"
case exclamationCircle = "\u{f06a}"
case exclamationTriangle = "\u{f071}"
case expand = "\u{f065}"
case expandAlt = "\u{f424}"
case expandArrowsAlt = "\u{f31e}"
case externalLinkAlt = "\u{f35d}"
case externalLinkSquareAlt = "\u{f360}"
case eye = "\u{f06e}"
case eyeDropper = "\u{f1fb}"
case eyeSlash = "\u{f070}"
case fan = "\u{f863}"
case fastBackward = "\u{f049}"
case fastForward = "\u{f050}"
case faucet = "\u{e005}"
case fax = "\u{f1ac}"
case feather = "\u{f52d}"
case featherAlt = "\u{f56b}"
case female = "\u{f182}"
case fighterJet = "\u{f0fb}"
case file = "\u{f15b}"
case fileAlt = "\u{f15c}"
case fileArchive = "\u{f1c6}"
case fileAudio = "\u{f1c7}"
case fileCode = "\u{f1c9}"
case fileContract = "\u{f56c}"
case fileCsv = "\u{f6dd}"
case fileDownload = "\u{f56d}"
case fileExcel = "\u{f1c3}"
case fileExport = "\u{f56e}"
case fileImage = "\u{f1c5}"
case fileImport = "\u{f56f}"
case fileInvoice = "\u{f570}"
case fileInvoiceDollar = "\u{f571}"
case fileMedical = "\u{f477}"
case fileMedicalAlt = "\u{f478}"
case filePdf = "\u{f1c1}"
case filePowerpoint = "\u{f1c4}"
case filePrescription = "\u{f572}"
case fileSignature = "\u{f573}"
case fileUpload = "\u{f574}"
case fileVideo = "\u{f1c8}"
case fileWord = "\u{f1c2}"
case fill = "\u{f575}"
case fillDrip = "\u{f576}"
case film = "\u{f008}"
case filter = "\u{f0b0}"
case fingerprint = "\u{f577}"
case fire = "\u{f06d}"
case fireAlt = "\u{f7e4}"
case fireExtinguisher = "\u{f134}"
case firstAid = "\u{f479}"
case fish = "\u{f578}"
case fistRaised = "\u{f6de}"
case flag = "\u{f024}"
case flagCheckered = "\u{f11e}"
case flagUsa = "\u{f74d}"
case flask = "\u{f0c3}"
case flushed = "\u{f579}"
case folder = "\u{f07b}"
case folderMinus = "\u{f65d}"
case folderOpen = "\u{f07c}"
case folderPlus = "\u{f65e}"
case font = "\u{f031}"
case footballBall = "\u{f44e}"
case forward = "\u{f04e}"
case frog = "\u{f52e}"
case frown = "\u{f119}"
case frownOpen = "\u{f57a}"
case funnelDollar = "\u{f662}"
case futbol = "\u{f1e3}"
case gamepad = "\u{f11b}"
case gasPump = "\u{f52f}"
case gavel = "\u{f0e3}"
case gem = "\u{f3a5}"
case genderless = "\u{f22d}"
case ghost = "\u{f6e2}"
case gift = "\u{f06b}"
case gifts = "\u{f79c}"
case glassCheers = "\u{f79f}"
case glassMartini = "\u{f000}"
case glassMartiniAlt = "\u{f57b}"
case glassWhiskey = "\u{f7a0}"
case glasses = "\u{f530}"
case globe = "\u{f0ac}"
case globeAfrica = "\u{f57c}"
case globeAmericas = "\u{f57d}"
case globeAsia = "\u{f57e}"
case globeEurope = "\u{f7a2}"
case golfBall = "\u{f450}"
case gopuram = "\u{f664}"
case graduationCap = "\u{f19d}"
case greaterThan = "\u{f531}"
case greaterThanEqual = "\u{f532}"
case grimace = "\u{f57f}"
case grin = "\u{f580}"
case grinAlt = "\u{f581}"
case grinBeam = "\u{f582}"
case grinBeamSweat = "\u{f583}"
case grinHearts = "\u{f584}"
case grinSquint = "\u{f585}"
case grinSquintTears = "\u{f586}"
case grinStars = "\u{f587}"
case grinTears = "\u{f588}"
case grinTongue = "\u{f589}"
case grinTongueSquint = "\u{f58a}"
case grinTongueWink = "\u{f58b}"
case grinWink = "\u{f58c}"
case gripHorizontal = "\u{f58d}"
case gripLines = "\u{f7a4}"
case gripLinesVertical = "\u{f7a5}"
case gripVertical = "\u{f58e}"
case guitar = "\u{f7a6}"
case hSquare = "\u{f0fd}"
case hamburger = "\u{f805}"
case hammer = "\u{f6e3}"
case hamsa = "\u{f665}"
case handHolding = "\u{f4bd}"
case handHoldingHeart = "\u{f4be}"
case handHoldingMedical = "\u{e05c}"
case handHoldingUsd = "\u{f4c0}"
case handHoldingWater = "\u{f4c1}"
case handLizard = "\u{f258}"
case handMiddleFinger = "\u{f806}"
case handPaper = "\u{f256}"
case handPeace = "\u{f25b}"
case handPointDown = "\u{f0a7}"
case handPointLeft = "\u{f0a5}"
case handPointRight = "\u{f0a4}"
case handPointUp = "\u{f0a6}"
case handPointer = "\u{f25a}"
case handRock = "\u{f255}"
case handScissors = "\u{f257}"
case handSparkles = "\u{e05d}"
case handSpock = "\u{f259}"
case hands = "\u{f4c2}"
case handsHelping = "\u{f4c4}"
case handsWash = "\u{e05e}"
case handshake = "\u{f2b5}"
case handshakeAltSlash = "\u{e05f}"
case handshakeSlash = "\u{e060}"
case hanukiah = "\u{f6e6}"
case hardHat = "\u{f807}"
case hashtag = "\u{f292}"
case hatCowboy = "\u{f8c0}"
case hatCowboySide = "\u{f8c1}"
case hatWizard = "\u{f6e8}"
case hdd = "\u{f0a0}"
case headSideCough = "\u{e061}"
case headSideCoughSlash = "\u{e062}"
case headSideMask = "\u{e063}"
case headSideVirus = "\u{e064}"
case heading = "\u{f1dc}"
case headphones = "\u{f025}"
case headphonesAlt = "\u{f58f}"
case headset = "\u{f590}"
case heart = "\u{f004}"
case heartBroken = "\u{f7a9}"
case heartbeat = "\u{f21e}"
case helicopter = "\u{f533}"
case highlighter = "\u{f591}"
case hiking = "\u{f6ec}"
case hippo = "\u{f6ed}"
case history = "\u{f1da}"
case hockeyPuck = "\u{f453}"
case hollyBerry = "\u{f7aa}"
case home = "\u{f015}"
case horse = "\u{f6f0}"
case horseHead = "\u{f7ab}"
case hospital = "\u{f0f8}"
case hospitalAlt = "\u{f47d}"
case hospitalSymbol = "\u{f47e}"
case hospitalUser = "\u{f80d}"
case hotTub = "\u{f593}"
case hotdog = "\u{f80f}"
case hotel = "\u{f594}"
case hourglass = "\u{f254}"
case hourglassEnd = "\u{f253}"
case hourglassHalf = "\u{f252}"
case hourglassStart = "\u{f251}"
case houseDamage = "\u{f6f1}"
case houseUser = "\u{e065}"
case hryvnia = "\u{f6f2}"
case iCursor = "\u{f246}"
case iceCream = "\u{f810}"
case icicles = "\u{f7ad}"
case icons = "\u{f86d}"
case idBadge = "\u{f2c1}"
case idCard = "\u{f2c2}"
case idCardAlt = "\u{f47f}"
case igloo = "\u{f7ae}"
case image = "\u{f03e}"
case images = "\u{f302}"
case inbox = "\u{f01c}"
case indent = "\u{f03c}"
case industry = "\u{f275}"
case infinity = "\u{f534}"
case info = "\u{f129}"
case infoCircle = "\u{f05a}"
case italic = "\u{f033}"
case jedi = "\u{f669}"
case joint = "\u{f595}"
case journalWhills = "\u{f66a}"
case kaaba = "\u{f66b}"
case key = "\u{f084}"
case keyboard = "\u{f11c}"
case khanda = "\u{f66d}"
case kiss = "\u{f596}"
case kissBeam = "\u{f597}"
case kissWinkHeart = "\u{f598}"
case kiwiBird = "\u{f535}"
case landmark = "\u{f66f}"
case language = "\u{f1ab}"
case laptop = "\u{f109}"
case laptopCode = "\u{f5fc}"
case laptopHouse = "\u{e066}"
case laptopMedical = "\u{f812}"
case laugh = "\u{f599}"
case laughBeam = "\u{f59a}"
case laughSquint = "\u{f59b}"
case laughWink = "\u{f59c}"
case layerGroup = "\u{f5fd}"
case leaf = "\u{f06c}"
case lemon = "\u{f094}"
case lessThan = "\u{f536}"
case lessThanEqual = "\u{f537}"
case levelDownAlt = "\u{f3be}"
case levelUpAlt = "\u{f3bf}"
case lifeRing = "\u{f1cd}"
case lightbulb = "\u{f0eb}"
case link = "\u{f0c1}"
case liraSign = "\u{f195}"
case list = "\u{f03a}"
case listAlt = "\u{f022}"
case listOl = "\u{f0cb}"
case listUl = "\u{f0ca}"
case locationArrow = "\u{f124}"
case lock = "\u{f023}"
case lockOpen = "\u{f3c1}"
case longArrowAltDown = "\u{f309}"
case longArrowAltLeft = "\u{f30a}"
case longArrowAltRight = "\u{f30b}"
case longArrowAltUp = "\u{f30c}"
case lowVision = "\u{f2a8}"
case luggageCart = "\u{f59d}"
case lungs = "\u{f604}"
case lungsVirus = "\u{e067}"
case magic = "\u{f0d0}"
case magnet = "\u{f076}"
case mailBulk = "\u{f674}"
case male = "\u{f183}"
case map = "\u{f279}"
case mapMarked = "\u{f59f}"
case mapMarkedAlt = "\u{f5a0}"
case mapMarker = "\u{f041}"
case mapMarkerAlt = "\u{f3c5}"
case mapPin = "\u{f276}"
case mapSigns = "\u{f277}"
case marker = "\u{f5a1}"
case mars = "\u{f222}"
case marsDouble = "\u{f227}"
case marsStroke = "\u{f229}"
case marsStrokeH = "\u{f22b}"
case marsStrokeV = "\u{f22a}"
case mask = "\u{f6fa}"
case medal = "\u{f5a2}"
case medkit = "\u{f0fa}"
case meh = "\u{f11a}"
case mehBlank = "\u{f5a4}"
case mehRollingEyes = "\u{f5a5}"
case memory = "\u{f538}"
case menorah = "\u{f676}"
case mercury = "\u{f223}"
case meteor = "\u{f753}"
case microchip = "\u{f2db}"
case microphone = "\u{f130}"
case microphoneAlt = "\u{f3c9}"
case microphoneAltSlash = "\u{f539}"
case microphoneSlash = "\u{f131}"
case microscope = "\u{f610}"
case minus = "\u{f068}"
case minusCircle = "\u{f056}"
case minusSquare = "\u{f146}"
case mitten = "\u{f7b5}"
case mobile = "\u{f10b}"
case mobileAlt = "\u{f3cd}"
case moneyBill = "\u{f0d6}"
case moneyBillAlt = "\u{f3d1}"
case moneyBillWave = "\u{f53a}"
case moneyBillWaveAlt = "\u{f53b}"
case moneyCheck = "\u{f53c}"
case moneyCheckAlt = "\u{f53d}"
case monument = "\u{f5a6}"
case moon = "\u{f186}"
case mortarPestle = "\u{f5a7}"
case mosque = "\u{f678}"
case motorcycle = "\u{f21c}"
case mountain = "\u{f6fc}"
case mouse = "\u{f8cc}"
case mousePointer = "\u{f245}"
case mugHot = "\u{f7b6}"
case music = "\u{f001}"
case networkWired = "\u{f6ff}"
case neuter = "\u{f22c}"
case newspaper = "\u{f1ea}"
case notEqual = "\u{f53e}"
case notesMedical = "\u{f481}"
case objectGroup = "\u{f247}"
case objectUngroup = "\u{f248}"
case oilCan = "\u{f613}"
case om = "\u{f679}"
case otter = "\u{f700}"
case outdent = "\u{f03b}"
case pager = "\u{f815}"
case paintBrush = "\u{f1fc}"
case paintRoller = "\u{f5aa}"
case palette = "\u{f53f}"
case pallet = "\u{f482}"
case paperPlane = "\u{f1d8}"
case paperclip = "\u{f0c6}"
case parachuteBox = "\u{f4cd}"
case paragraph = "\u{f1dd}"
case parking = "\u{f540}"
case passport = "\u{f5ab}"
case pastafarianism = "\u{f67b}"
case paste = "\u{f0ea}"
case pause = "\u{f04c}"
case pauseCircle = "\u{f28b}"
case paw = "\u{f1b0}"
case peace = "\u{f67c}"
case pen = "\u{f304}"
case penAlt = "\u{f305}"
case penFancy = "\u{f5ac}"
case penNib = "\u{f5ad}"
case penSquare = "\u{f14b}"
case pencilAlt = "\u{f303}"
case pencilRuler = "\u{f5ae}"
case peopleArrows = "\u{e068}"
case peopleCarry = "\u{f4ce}"
case pepperHot = "\u{f816}"
case percent = "\u{f295}"
case percentage = "\u{f541}"
case personBooth = "\u{f756}"
case phone = "\u{f095}"
case phoneAlt = "\u{f879}"
case phoneSlash = "\u{f3dd}"
case phoneSquare = "\u{f098}"
case phoneSquareAlt = "\u{f87b}"
case phoneVolume = "\u{f2a0}"
case photoVideo = "\u{f87c}"
case piggyBank = "\u{f4d3}"
case pills = "\u{f484}"
case pizzaSlice = "\u{f818}"
case placeOfWorship = "\u{f67f}"
case plane = "\u{f072}"
case planeArrival = "\u{f5af}"
case planeDeparture = "\u{f5b0}"
case planeSlash = "\u{e069}"
case play = "\u{f04b}"
case playCircle = "\u{f144}"
case plug = "\u{f1e6}"
case plus = "\u{f067}"
case plusCircle = "\u{f055}"
case plusSquare = "\u{f0fe}"
case podcast = "\u{f2ce}"
case poll = "\u{f681}"
case pollH = "\u{f682}"
case poo = "\u{f2fe}"
case pooStorm = "\u{f75a}"
case poop = "\u{f619}"
case portrait = "\u{f3e0}"
case poundSign = "\u{f154}"
case powerOff = "\u{f011}"
case pray = "\u{f683}"
case prayingHands = "\u{f684}"
case prescription = "\u{f5b1}"
case prescriptionBottle = "\u{f485}"
case prescriptionBottleAlt = "\u{f486}"
case print = "\u{f02f}"
case procedures = "\u{f487}"
case projectDiagram = "\u{f542}"
case pumpMedical = "\u{e06a}"
case pumpSoap = "\u{e06b}"
case puzzlePiece = "\u{f12e}"
case qrcode = "\u{f029}"
case question = "\u{f128}"
case questionCircle = "\u{f059}"
case quidditch = "\u{f458}"
case quoteLeft = "\u{f10d}"
case quoteRight = "\u{f10e}"
case quran = "\u{f687}"
case radiation = "\u{f7b9}"
case radiationAlt = "\u{f7ba}"
case rainbow = "\u{f75b}"
case random = "\u{f074}"
case receipt = "\u{f543}"
case recordVinyl = "\u{f8d9}"
case recycle = "\u{f1b8}"
case redo = "\u{f01e}"
case redoAlt = "\u{f2f9}"
case registered = "\u{f25d}"
case removeFormat = "\u{f87d}"
case reply = "\u{f3e5}"
case replyAll = "\u{f122}"
case republican = "\u{f75e}"
case restroom = "\u{f7bd}"
case retweet = "\u{f079}"
case ribbon = "\u{f4d6}"
case ring = "\u{f70b}"
case road = "\u{f018}"
case robot = "\u{f544}"
case rocket = "\u{f135}"
case route = "\u{f4d7}"
case rss = "\u{f09e}"
case rssSquare = "\u{f143}"
case rubleSign = "\u{f158}"
case ruler = "\u{f545}"
case rulerCombined = "\u{f546}"
case rulerHorizontal = "\u{f547}"
case rulerVertical = "\u{f548}"
case running = "\u{f70c}"
case rupeeSign = "\u{f156}"
case sadCry = "\u{f5b3}"
case sadTear = "\u{f5b4}"
case satellite = "\u{f7bf}"
case satelliteDish = "\u{f7c0}"
case save = "\u{f0c7}"
case school = "\u{f549}"
case screwdriver = "\u{f54a}"
case scroll = "\u{f70e}"
case sdCard = "\u{f7c2}"
case search = "\u{f002}"
case searchDollar = "\u{f688}"
case searchLocation = "\u{f689}"
case searchMinus = "\u{f010}"
case searchPlus = "\u{f00e}"
case seedling = "\u{f4d8}"
case server = "\u{f233}"
case shapes = "\u{f61f}"
case share = "\u{f064}"
case shareAlt = "\u{f1e0}"
case shareAltSquare = "\u{f1e1}"
case shareSquare = "\u{f14d}"
case shekelSign = "\u{f20b}"
case shieldAlt = "\u{f3ed}"
case shieldVirus = "\u{e06c}"
case ship = "\u{f21a}"
case shippingFast = "\u{f48b}"
case shoePrints = "\u{f54b}"
case shoppingBag = "\u{f290}"
case shoppingBasket = "\u{f291}"
case shoppingCart = "\u{f07a}"
case shower = "\u{f2cc}"
case shuttleVan = "\u{f5b6}"
case sign = "\u{f4d9}"
case signInAlt = "\u{f2f6}"
case signLanguage = "\u{f2a7}"
case signOutAlt = "\u{f2f5}"
case signal = "\u{f012}"
case signature = "\u{f5b7}"
case simCard = "\u{f7c4}"
case sink = "\u{e06d}"
case sitemap = "\u{f0e8}"
case skating = "\u{f7c5}"
case skiing = "\u{f7c9}"
case skiingNordic = "\u{f7ca}"
case skull = "\u{f54c}"
case skullCrossbones = "\u{f714}"
case slash = "\u{f715}"
case sleigh = "\u{f7cc}"
case slidersH = "\u{f1de}"
case smile = "\u{f118}"
case smileBeam = "\u{f5b8}"
case smileWink = "\u{f4da}"
case smog = "\u{f75f}"
case smoking = "\u{f48d}"
case smokingBan = "\u{f54d}"
case sms = "\u{f7cd}"
case snowboarding = "\u{f7ce}"
case snowflake = "\u{f2dc}"
case snowman = "\u{f7d0}"
case snowplow = "\u{f7d2}"
case soap = "\u{e06e}"
case socks = "\u{f696}"
case solarPanel = "\u{f5ba}"
case sort = "\u{f0dc}"
case sortAlphaDown = "\u{f15d}"
case sortAlphaDownAlt = "\u{f881}"
case sortAlphaUp = "\u{f15e}"
case sortAlphaUpAlt = "\u{f882}"
case sortAmountDown = "\u{f160}"
case sortAmountDownAlt = "\u{f884}"
case sortAmountUp = "\u{f161}"
case sortAmountUpAlt = "\u{f885}"
case sortDown = "\u{f0dd}"
case sortNumericDown = "\u{f162}"
case sortNumericDownAlt = "\u{f886}"
case sortNumericUp = "\u{f163}"
case sortNumericUpAlt = "\u{f887}"
case sortUp = "\u{f0de}"
case spa = "\u{f5bb}"
case spaceShuttle = "\u{f197}"
case spellCheck = "\u{f891}"
case spider = "\u{f717}"
case spinner = "\u{f110}"
case splotch = "\u{f5bc}"
case sprayCan = "\u{f5bd}"
case square = "\u{f0c8}"
case squareFull = "\u{f45c}"
case squareRootAlt = "\u{f698}"
case stamp = "\u{f5bf}"
case star = "\u{f005}"
case starAndCrescent = "\u{f699}"
case starHalf = "\u{f089}"
case starHalfAlt = "\u{f5c0}"
case starOfDavid = "\u{f69a}"
case starOfLife = "\u{f621}"
case stepBackward = "\u{f048}"
case stepForward = "\u{f051}"
case stethoscope = "\u{f0f1}"
case stickyNote = "\u{f249}"
case stop = "\u{f04d}"
case stopCircle = "\u{f28d}"
case stopwatch = "\u{f2f2}"
case stopwatch20 = "\u{e06f}"
case store = "\u{f54e}"
case storeAlt = "\u{f54f}"
case storeAltSlash = "\u{e070}"
case storeSlash = "\u{e071}"
case stream = "\u{f550}"
case streetView = "\u{f21d}"
case strikethrough = "\u{f0cc}"
case stroopwafel = "\u{f551}"
case `subscript` = "\u{f12c}"
case subway = "\u{f239}"
case suitcase = "\u{f0f2}"
case suitcaseRolling = "\u{f5c1}"
case sun = "\u{f185}"
case superscript = "\u{f12b}"
case surprise = "\u{f5c2}"
case swatchbook = "\u{f5c3}"
case swimmer = "\u{f5c4}"
case swimmingPool = "\u{f5c5}"
case synagogue = "\u{f69b}"
case sync = "\u{f021}"
case syncAlt = "\u{f2f1}"
case syringe = "\u{f48e}"
case table = "\u{f0ce}"
case tableTennis = "\u{f45d}"
case tablet = "\u{f10a}"
case tabletAlt = "\u{f3fa}"
case tablets = "\u{f490}"
case tachometerAlt = "\u{f3fd}"
case tag = "\u{f02b}"
case tags = "\u{f02c}"
case tape = "\u{f4db}"
case tasks = "\u{f0ae}"
case taxi = "\u{f1ba}"
case teeth = "\u{f62e}"
case teethOpen = "\u{f62f}"
case temperatureHigh = "\u{f769}"
case temperatureLow = "\u{f76b}"
case tenge = "\u{f7d7}"
case terminal = "\u{f120}"
case textHeight = "\u{f034}"
case textWidth = "\u{f035}"
case th = "\u{f00a}"
case thLarge = "\u{f009}"
case thList = "\u{f00b}"
case theaterMasks = "\u{f630}"
case thermometer = "\u{f491}"
case thermometerEmpty = "\u{f2cb}"
case thermometerFull = "\u{f2c7}"
case thermometerHalf = "\u{f2c9}"
case thermometerQuarter = "\u{f2ca}"
case thermometerThreeQuarters = "\u{f2c8}"
case thumbsDown = "\u{f165}"
case thumbsUp = "\u{f164}"
case thumbtack = "\u{f08d}"
case ticketAlt = "\u{f3ff}"
case times = "\u{f00d}"
case timesCircle = "\u{f057}"
case tint = "\u{f043}"
case tintSlash = "\u{f5c7}"
case tired = "\u{f5c8}"
case toggleOff = "\u{f204}"
case toggleOn = "\u{f205}"
case toilet = "\u{f7d8}"
case toiletPaper = "\u{f71e}"
case toiletPaperSlash = "\u{e072}"
case toolbox = "\u{f552}"
case tools = "\u{f7d9}"
case tooth = "\u{f5c9}"
case torah = "\u{f6a0}"
case toriiGate = "\u{f6a1}"
case tractor = "\u{f722}"
case trademark = "\u{f25c}"
case trafficLight = "\u{f637}"
case trailer = "\u{e041}"
case train = "\u{f238}"
case tram = "\u{f7da}"
case transgender = "\u{f224}"
case transgenderAlt = "\u{f225}"
case trash = "\u{f1f8}"
case trashAlt = "\u{f2ed}"
case trashRestore = "\u{f829}"
case trashRestoreAlt = "\u{f82a}"
case tree = "\u{f1bb}"
case trophy = "\u{f091}"
case truck = "\u{f0d1}"
case truckLoading = "\u{f4de}"
case truckMonster = "\u{f63b}"
case truckMoving = "\u{f4df}"
case truckPickup = "\u{f63c}"
case tshirt = "\u{f553}"
case tty = "\u{f1e4}"
case tv = "\u{f26c}"
case umbrella = "\u{f0e9}"
case umbrellaBeach = "\u{f5ca}"
case underline = "\u{f0cd}"
case undo = "\u{f0e2}"
case undoAlt = "\u{f2ea}"
case universalAccess = "\u{f29a}"
case university = "\u{f19c}"
case unlink = "\u{f127}"
case unlock = "\u{f09c}"
case unlockAlt = "\u{f13e}"
case upload = "\u{f093}"
case user = "\u{f007}"
case userAlt = "\u{f406}"
case userAltSlash = "\u{f4fa}"
case userAstronaut = "\u{f4fb}"
case userCheck = "\u{f4fc}"
case userCircle = "\u{f2bd}"
case userClock = "\u{f4fd}"
case userCog = "\u{f4fe}"
case userEdit = "\u{f4ff}"
case userFriends = "\u{f500}"
case userGraduate = "\u{f501}"
case userInjured = "\u{f728}"
case userLock = "\u{f502}"
case userMd = "\u{f0f0}"
case userMinus = "\u{f503}"
case userNinja = "\u{f504}"
case userNurse = "\u{f82f}"
case userPlus = "\u{f234}"
case userSecret = "\u{f21b}"
case userShield = "\u{f505}"
case userSlash = "\u{f506}"
case userTag = "\u{f507}"
case userTie = "\u{f508}"
case userTimes = "\u{f235}"
case users = "\u{f0c0}"
case usersCog = "\u{f509}"
case usersSlash = "\u{e073}"
case utensilSpoon = "\u{f2e5}"
case utensils = "\u{f2e7}"
case vectorSquare = "\u{f5cb}"
case venus = "\u{f221}"
case venusDouble = "\u{f226}"
case venusMars = "\u{f228}"
case vest = "\u{e085}"
case vestPatches = "\u{e086}"
case vial = "\u{f492}"
case vials = "\u{f493}"
case video = "\u{f03d}"
case videoSlash = "\u{f4e2}"
case vihara = "\u{f6a7}"
case virus = "\u{e074}"
case virusSlash = "\u{e075}"
case viruses = "\u{e076}"
case voicemail = "\u{f897}"
case volleyballBall = "\u{f45f}"
case volumeDown = "\u{f027}"
case volumeMute = "\u{f6a9}"
case volumeOff = "\u{f026}"
case volumeUp = "\u{f028}"
case voteYea = "\u{f772}"
case vrCardboard = "\u{f729}"
case walking = "\u{f554}"
case wallet = "\u{f555}"
case warehouse = "\u{f494}"
case water = "\u{f773}"
case waveSquare = "\u{f83e}"
case weight = "\u{f496}"
case weightHanging = "\u{f5cd}"
case wheelchair = "\u{f193}"
case wifi = "\u{f1eb}"
case wind = "\u{f72e}"
case windowClose = "\u{f410}"
case windowMaximize = "\u{f2d0}"
case windowMinimize = "\u{f2d1}"
case windowRestore = "\u{f2d2}"
case wineBottle = "\u{f72f}"
case wineGlass = "\u{f4e3}"
case wineGlassAlt = "\u{f5ce}"
case wonSign = "\u{f159}"
case wrench = "\u{f0ad}"
case xRay = "\u{f497}"
case yenSign = "\u{f157}"
case yinYang = "\u{f6ad}"
public var fontType: AwesomeFont {
return Awesome.Font.solid
}
}
public enum Regular: String, Amazing {
case addressBook = "\u{f2b9}"
case addressCard = "\u{f2bb}"
case angry = "\u{f556}"
case arrowAltCircleDown = "\u{f358}"
case arrowAltCircleLeft = "\u{f359}"
case arrowAltCircleRight = "\u{f35a}"
case arrowAltCircleUp = "\u{f35b}"
case bell = "\u{f0f3}"
case bellSlash = "\u{f1f6}"
case bookmark = "\u{f02e}"
case building = "\u{f1ad}"
case calendar = "\u{f133}"
case calendarAlt = "\u{f073}"
case calendarCheck = "\u{f274}"
case calendarMinus = "\u{f272}"
case calendarPlus = "\u{f271}"
case calendarTimes = "\u{f273}"
case caretSquareDown = "\u{f150}"
case caretSquareLeft = "\u{f191}"
case caretSquareRight = "\u{f152}"
case caretSquareUp = "\u{f151}"
case chartBar = "\u{f080}"
case checkCircle = "\u{f058}"
case checkSquare = "\u{f14a}"
case circle = "\u{f111}"
case clipboard = "\u{f328}"
case clock = "\u{f017}"
case clone = "\u{f24d}"
case closedCaptioning = "\u{f20a}"
case comment = "\u{f075}"
case commentAlt = "\u{f27a}"
case commentDots = "\u{f4ad}"
case comments = "\u{f086}"
case compass = "\u{f14e}"
case copy = "\u{f0c5}"
case copyright = "\u{f1f9}"
case creditCard = "\u{f09d}"
case dizzy = "\u{f567}"
case dotCircle = "\u{f192}"
case edit = "\u{f044}"
case envelope = "\u{f0e0}"
case envelopeOpen = "\u{f2b6}"
case eye = "\u{f06e}"
case eyeSlash = "\u{f070}"
case file = "\u{f15b}"
case fileAlt = "\u{f15c}"
case fileArchive = "\u{f1c6}"
case fileAudio = "\u{f1c7}"
case fileCode = "\u{f1c9}"
case fileExcel = "\u{f1c3}"
case fileImage = "\u{f1c5}"
case filePdf = "\u{f1c1}"
case filePowerpoint = "\u{f1c4}"
case fileVideo = "\u{f1c8}"
case fileWord = "\u{f1c2}"
case flag = "\u{f024}"
case flushed = "\u{f579}"
case folder = "\u{f07b}"
case folderOpen = "\u{f07c}"
case frown = "\u{f119}"
case frownOpen = "\u{f57a}"
case futbol = "\u{f1e3}"
case gem = "\u{f3a5}"
case grimace = "\u{f57f}"
case grin = "\u{f580}"
case grinAlt = "\u{f581}"
case grinBeam = "\u{f582}"
case grinBeamSweat = "\u{f583}"
case grinHearts = "\u{f584}"
case grinSquint = "\u{f585}"
case grinSquintTears = "\u{f586}"
case grinStars = "\u{f587}"
case grinTears = "\u{f588}"
case grinTongue = "\u{f589}"
case grinTongueSquint = "\u{f58a}"
case grinTongueWink = "\u{f58b}"
case grinWink = "\u{f58c}"
case handLizard = "\u{f258}"
case handPaper = "\u{f256}"
case handPeace = "\u{f25b}"
case handPointDown = "\u{f0a7}"
case handPointLeft = "\u{f0a5}"
case handPointRight = "\u{f0a4}"
case handPointUp = "\u{f0a6}"
case handPointer = "\u{f25a}"
case handRock = "\u{f255}"
case handScissors = "\u{f257}"
case handSpock = "\u{f259}"
case handshake = "\u{f2b5}"
case hdd = "\u{f0a0}"
case heart = "\u{f004}"
case hospital = "\u{f0f8}"
case hourglass = "\u{f254}"
case idBadge = "\u{f2c1}"
case idCard = "\u{f2c2}"
case image = "\u{f03e}"
case images = "\u{f302}"
case keyboard = "\u{f11c}"
case kiss = "\u{f596}"
case kissBeam = "\u{f597}"
case kissWinkHeart = "\u{f598}"
case laugh = "\u{f599}"
case laughBeam = "\u{f59a}"
case laughSquint = "\u{f59b}"
case laughWink = "\u{f59c}"
case lemon = "\u{f094}"
case lifeRing = "\u{f1cd}"
case lightbulb = "\u{f0eb}"
case listAlt = "\u{f022}"
case map = "\u{f279}"
case meh = "\u{f11a}"
case mehBlank = "\u{f5a4}"
case mehRollingEyes = "\u{f5a5}"
case minusSquare = "\u{f146}"
case moneyBillAlt = "\u{f3d1}"
case moon = "\u{f186}"
case newspaper = "\u{f1ea}"
case objectGroup = "\u{f247}"
case objectUngroup = "\u{f248}"
case paperPlane = "\u{f1d8}"
case pauseCircle = "\u{f28b}"
case playCircle = "\u{f144}"
case plusSquare = "\u{f0fe}"
case questionCircle = "\u{f059}"
case registered = "\u{f25d}"
case sadCry = "\u{f5b3}"
case sadTear = "\u{f5b4}"
case save = "\u{f0c7}"
case shareSquare = "\u{f14d}"
case smile = "\u{f118}"
case smileBeam = "\u{f5b8}"
case smileWink = "\u{f4da}"
case snowflake = "\u{f2dc}"
case square = "\u{f0c8}"
case star = "\u{f005}"
case starHalf = "\u{f089}"
case stickyNote = "\u{f249}"
case stopCircle = "\u{f28d}"
case sun = "\u{f185}"
case surprise = "\u{f5c2}"
case thumbsDown = "\u{f165}"
case thumbsUp = "\u{f164}"
case timesCircle = "\u{f057}"
case tired = "\u{f5c8}"
case trashAlt = "\u{f2ed}"
case user = "\u{f007}"
case userCircle = "\u{f2bd}"
case windowClose = "\u{f410}"
case windowMaximize = "\u{f2d0}"
case windowMinimize = "\u{f2d1}"
case windowRestore = "\u{f2d2}"
public var fontType: AwesomeFont {
return Awesome.Font.regular
}
}
public enum Brand: String, Amazing {
case fa500px = "\u{f26e}"
case accessibleIcon = "\u{f368}"
case accusoft = "\u{f369}"
case acquisitionsIncorporated = "\u{f6af}"
case adn = "\u{f170}"
case adversal = "\u{f36a}"
case affiliatetheme = "\u{f36b}"
case airbnb = "\u{f834}"
case algolia = "\u{f36c}"
case alipay = "\u{f642}"
case amazon = "\u{f270}"
case amazonPay = "\u{f42c}"
case amilia = "\u{f36d}"
case android = "\u{f17b}"
case angellist = "\u{f209}"
case angrycreative = "\u{f36e}"
case angular = "\u{f420}"
case appStore = "\u{f36f}"
case appStoreIos = "\u{f370}"
case apper = "\u{f371}"
case apple = "\u{f179}"
case applePay = "\u{f415}"
case artstation = "\u{f77a}"
case asymmetrik = "\u{f372}"
case atlassian = "\u{f77b}"
case audible = "\u{f373}"
case autoprefixer = "\u{f41c}"
case avianex = "\u{f374}"
case aviato = "\u{f421}"
case aws = "\u{f375}"
case bandcamp = "\u{f2d5}"
case battleNet = "\u{f835}"
case behance = "\u{f1b4}"
case behanceSquare = "\u{f1b5}"
case bimobject = "\u{f378}"
case bitbucket = "\u{f171}"
case bitcoin = "\u{f379}"
case bity = "\u{f37a}"
case blackTie = "\u{f27e}"
case blackberry = "\u{f37b}"
case blogger = "\u{f37c}"
case bloggerB = "\u{f37d}"
case bluetooth = "\u{f293}"
case bluetoothB = "\u{f294}"
case bootstrap = "\u{f836}"
case btc = "\u{f15a}"
case buffer = "\u{f837}"
case buromobelexperte = "\u{f37f}"
case buyNLarge = "\u{f8a6}"
case buysellads = "\u{f20d}"
case canadianMapleLeaf = "\u{f785}"
case ccAmazonPay = "\u{f42d}"
case ccAmex = "\u{f1f3}"
case ccApplePay = "\u{f416}"
case ccDinersClub = "\u{f24c}"
case ccDiscover = "\u{f1f2}"
case ccJcb = "\u{f24b}"
case ccMastercard = "\u{f1f1}"
case ccPaypal = "\u{f1f4}"
case ccStripe = "\u{f1f5}"
case ccVisa = "\u{f1f0}"
case centercode = "\u{f380}"
case centos = "\u{f789}"
case chrome = "\u{f268}"
case chromecast = "\u{f838}"
case cloudflare = "\u{e07d}"
case cloudscale = "\u{f383}"
case cloudsmith = "\u{f384}"
case cloudversify = "\u{f385}"
case codepen = "\u{f1cb}"
case codiepie = "\u{f284}"
case confluence = "\u{f78d}"
case connectdevelop = "\u{f20e}"
case contao = "\u{f26d}"
case cottonBureau = "\u{f89e}"
case cpanel = "\u{f388}"
case creativeCommons = "\u{f25e}"
case creativeCommonsBy = "\u{f4e7}"
case creativeCommonsNc = "\u{f4e8}"
case creativeCommonsNcEu = "\u{f4e9}"
case creativeCommonsNcJp = "\u{f4ea}"
case creativeCommonsNd = "\u{f4eb}"
case creativeCommonsPd = "\u{f4ec}"
case creativeCommonsPdAlt = "\u{f4ed}"
case creativeCommonsRemix = "\u{f4ee}"
case creativeCommonsSa = "\u{f4ef}"
case creativeCommonsSampling = "\u{f4f0}"
case creativeCommonsSamplingPlus = "\u{f4f1}"
case creativeCommonsShare = "\u{f4f2}"
case creativeCommonsZero = "\u{f4f3}"
case criticalRole = "\u{f6c9}"
case css3 = "\u{f13c}"
case css3Alt = "\u{f38b}"
case cuttlefish = "\u{f38c}"
case dAndD = "\u{f38d}"
case dAndDBeyond = "\u{f6ca}"
case dailymotion = "\u{e052}"
case dashcube = "\u{f210}"
case deezer = "\u{e077}"
case delicious = "\u{f1a5}"
case deploydog = "\u{f38e}"
case deskpro = "\u{f38f}"
case dev = "\u{f6cc}"
case deviantart = "\u{f1bd}"
case dhl = "\u{f790}"
case diaspora = "\u{f791}"
case digg = "\u{f1a6}"
case digitalOcean = "\u{f391}"
case discord = "\u{f392}"
case discourse = "\u{f393}"
case dochub = "\u{f394}"
case docker = "\u{f395}"
case draft2digital = "\u{f396}"
case dribbble = "\u{f17d}"
case dribbbleSquare = "\u{f397}"
case dropbox = "\u{f16b}"
case drupal = "\u{f1a9}"
case dyalog = "\u{f399}"
case earlybirds = "\u{f39a}"
case ebay = "\u{f4f4}"
case edge = "\u{f282}"
case edgeLegacy = "\u{e078}"
case elementor = "\u{f430}"
case ello = "\u{f5f1}"
case ember = "\u{f423}"
case empire = "\u{f1d1}"
case envira = "\u{f299}"
case erlang = "\u{f39d}"
case ethereum = "\u{f42e}"
case etsy = "\u{f2d7}"
case evernote = "\u{f839}"
case expeditedssl = "\u{f23e}"
case facebook = "\u{f09a}"
case facebookF = "\u{f39e}"
case facebookMessenger = "\u{f39f}"
case facebookSquare = "\u{f082}"
case fantasyFlightGames = "\u{f6dc}"
case fedex = "\u{f797}"
case fedora = "\u{f798}"
case figma = "\u{f799}"
case firefox = "\u{f269}"
case firefoxBrowser = "\u{e007}"
case firstOrder = "\u{f2b0}"
case firstOrderAlt = "\u{f50a}"
case firstdraft = "\u{f3a1}"
case flickr = "\u{f16e}"
case flipboard = "\u{f44d}"
case fly = "\u{f417}"
case fontAwesome = "\u{f2b4}"
case fontAwesomeAlt = "\u{f35c}"
case fontAwesomeFlag = "\u{f425}"
case fonticons = "\u{f280}"
case fonticonsFi = "\u{f3a2}"
case fortAwesome = "\u{f286}"
case fortAwesomeAlt = "\u{f3a3}"
case forumbee = "\u{f211}"
case foursquare = "\u{f180}"
case freeCodeCamp = "\u{f2c5}"
case freebsd = "\u{f3a4}"
case fulcrum = "\u{f50b}"
case galacticRepublic = "\u{f50c}"
case galacticSenate = "\u{f50d}"
case getPocket = "\u{f265}"
case gg = "\u{f260}"
case ggCircle = "\u{f261}"
case git = "\u{f1d3}"
case gitAlt = "\u{f841}"
case gitSquare = "\u{f1d2}"
case github = "\u{f09b}"
case githubAlt = "\u{f113}"
case githubSquare = "\u{f092}"
case gitkraken = "\u{f3a6}"
case gitlab = "\u{f296}"
case gitter = "\u{f426}"
case glide = "\u{f2a5}"
case glideG = "\u{f2a6}"
case gofore = "\u{f3a7}"
case goodreads = "\u{f3a8}"
case goodreadsG = "\u{f3a9}"
case google = "\u{f1a0}"
case googleDrive = "\u{f3aa}"
case googlePay = "\u{e079}"
case googlePlay = "\u{f3ab}"
case googlePlus = "\u{f2b3}"
case googlePlusG = "\u{f0d5}"
case googlePlusSquare = "\u{f0d4}"
case googleWallet = "\u{f1ee}"
case gratipay = "\u{f184}"
case grav = "\u{f2d6}"
case gripfire = "\u{f3ac}"
case grunt = "\u{f3ad}"
case guilded = "\u{e07e}"
case gulp = "\u{f3ae}"
case hackerNews = "\u{f1d4}"
case hackerNewsSquare = "\u{f3af}"
case hackerrank = "\u{f5f7}"
case hips = "\u{f452}"
case hireAHelper = "\u{f3b0}"
case hive = "\u{e07f}"
case hooli = "\u{f427}"
case hornbill = "\u{f592}"
case hotjar = "\u{f3b1}"
case houzz = "\u{f27c}"
case html5 = "\u{f13b}"
case hubspot = "\u{f3b2}"
case ideal = "\u{e013}"
case imdb = "\u{f2d8}"
case innosoft = "\u{e080}"
case instagram = "\u{f16d}"
case instagramSquare = "\u{e055}"
case instalod = "\u{e081}"
case intercom = "\u{f7af}"
case internetExplorer = "\u{f26b}"
case invision = "\u{f7b0}"
case ioxhost = "\u{f208}"
case itchIo = "\u{f83a}"
case itunes = "\u{f3b4}"
case itunesNote = "\u{f3b5}"
case java = "\u{f4e4}"
case jediOrder = "\u{f50e}"
case jenkins = "\u{f3b6}"
case jira = "\u{f7b1}"
case joget = "\u{f3b7}"
case joomla = "\u{f1aa}"
case js = "\u{f3b8}"
case jsSquare = "\u{f3b9}"
case jsfiddle = "\u{f1cc}"
case kaggle = "\u{f5fa}"
case keybase = "\u{f4f5}"
case keycdn = "\u{f3ba}"
case kickstarter = "\u{f3bb}"
case kickstarterK = "\u{f3bc}"
case korvue = "\u{f42f}"
case laravel = "\u{f3bd}"
case lastfm = "\u{f202}"
case lastfmSquare = "\u{f203}"
case leanpub = "\u{f212}"
case less = "\u{f41d}"
case line = "\u{f3c0}"
case linkedin = "\u{f08c}"
case linkedinIn = "\u{f0e1}"
case linode = "\u{f2b8}"
case linux = "\u{f17c}"
case lyft = "\u{f3c3}"
case magento = "\u{f3c4}"
case mailchimp = "\u{f59e}"
case mandalorian = "\u{f50f}"
case markdown = "\u{f60f}"
case mastodon = "\u{f4f6}"
case maxcdn = "\u{f136}"
case mdb = "\u{f8ca}"
case medapps = "\u{f3c6}"
case medium = "\u{f23a}"
case mediumM = "\u{f3c7}"
case medrt = "\u{f3c8}"
case meetup = "\u{f2e0}"
case megaport = "\u{f5a3}"
case mendeley = "\u{f7b3}"
case microblog = "\u{e01a}"
case microsoft = "\u{f3ca}"
case mix = "\u{f3cb}"
case mixcloud = "\u{f289}"
case mixer = "\u{e056}"
case mizuni = "\u{f3cc}"
case modx = "\u{f285}"
case monero = "\u{f3d0}"
case napster = "\u{f3d2}"
case neos = "\u{f612}"
case nimblr = "\u{f5a8}"
case node = "\u{f419}"
case nodeJs = "\u{f3d3}"
case npm = "\u{f3d4}"
case ns8 = "\u{f3d5}"
case nutritionix = "\u{f3d6}"
case octopusDeploy = "\u{e082}"
case odnoklassniki = "\u{f263}"
case odnoklassnikiSquare = "\u{f264}"
case oldRepublic = "\u{f510}"
case opencart = "\u{f23d}"
case openid = "\u{f19b}"
case opera = "\u{f26a}"
case optinMonster = "\u{f23c}"
case orcid = "\u{f8d2}"
case osi = "\u{f41a}"
case page4 = "\u{f3d7}"
case pagelines = "\u{f18c}"
case palfed = "\u{f3d8}"
case patreon = "\u{f3d9}"
case paypal = "\u{f1ed}"
case pennyArcade = "\u{f704}"
case perbyte = "\u{e083}"
case periscope = "\u{f3da}"
case phabricator = "\u{f3db}"
case phoenixFramework = "\u{f3dc}"
case phoenixSquadron = "\u{f511}"
case php = "\u{f457}"
case piedPiper = "\u{f2ae}"
case piedPiperAlt = "\u{f1a8}"
case piedPiperHat = "\u{f4e5}"
case piedPiperPp = "\u{f1a7}"
case piedPiperSquare = "\u{e01e}"
case pinterest = "\u{f0d2}"
case pinterestP = "\u{f231}"
case pinterestSquare = "\u{f0d3}"
case playstation = "\u{f3df}"
case productHunt = "\u{f288}"
case pushed = "\u{f3e1}"
case python = "\u{f3e2}"
case qq = "\u{f1d6}"
case quinscape = "\u{f459}"
case quora = "\u{f2c4}"
case rProject = "\u{f4f7}"
case raspberryPi = "\u{f7bb}"
case ravelry = "\u{f2d9}"
case react = "\u{f41b}"
case reacteurope = "\u{f75d}"
case readme = "\u{f4d5}"
case rebel = "\u{f1d0}"
case redRiver = "\u{f3e3}"
case reddit = "\u{f1a1}"
case redditAlien = "\u{f281}"
case redditSquare = "\u{f1a2}"
case redhat = "\u{f7bc}"
case renren = "\u{f18b}"
case replyd = "\u{f3e6}"
case researchgate = "\u{f4f8}"
case resolving = "\u{f3e7}"
case rev = "\u{f5b2}"
case rocketchat = "\u{f3e8}"
case rockrms = "\u{f3e9}"
case rust = "\u{e07a}"
case safari = "\u{f267}"
case salesforce = "\u{f83b}"
case sass = "\u{f41e}"
case schlix = "\u{f3ea}"
case scribd = "\u{f28a}"
case searchengin = "\u{f3eb}"
case sellcast = "\u{f2da}"
case sellsy = "\u{f213}"
case servicestack = "\u{f3ec}"
case shirtsinbulk = "\u{f214}"
case shopify = "\u{e057}"
case shopware = "\u{f5b5}"
case simplybuilt = "\u{f215}"
case sistrix = "\u{f3ee}"
case sith = "\u{f512}"
case sketch = "\u{f7c6}"
case skyatlas = "\u{f216}"
case skype = "\u{f17e}"
case slack = "\u{f198}"
case slackHash = "\u{f3ef}"
case slideshare = "\u{f1e7}"
case snapchat = "\u{f2ab}"
case snapchatGhost = "\u{f2ac}"
case snapchatSquare = "\u{f2ad}"
case soundcloud = "\u{f1be}"
case sourcetree = "\u{f7d3}"
case speakap = "\u{f3f3}"
case speakerDeck = "\u{f83c}"
case spotify = "\u{f1bc}"
case squarespace = "\u{f5be}"
case stackExchange = "\u{f18d}"
case stackOverflow = "\u{f16c}"
case stackpath = "\u{f842}"
case staylinked = "\u{f3f5}"
case steam = "\u{f1b6}"
case steamSquare = "\u{f1b7}"
case steamSymbol = "\u{f3f6}"
case stickerMule = "\u{f3f7}"
case strava = "\u{f428}"
case stripe = "\u{f429}"
case stripeS = "\u{f42a}"
case studiovinari = "\u{f3f8}"
case stumbleupon = "\u{f1a4}"
case stumbleuponCircle = "\u{f1a3}"
case superpowers = "\u{f2dd}"
case supple = "\u{f3f9}"
case suse = "\u{f7d6}"
case swift = "\u{f8e1}"
case symfony = "\u{f83d}"
case teamspeak = "\u{f4f9}"
case telegram = "\u{f2c6}"
case telegramPlane = "\u{f3fe}"
case tencentWeibo = "\u{f1d5}"
case theRedYeti = "\u{f69d}"
case themeco = "\u{f5c6}"
case themeisle = "\u{f2b2}"
case thinkPeaks = "\u{f731}"
case tiktok = "\u{e07b}"
case tradeFederation = "\u{f513}"
case trello = "\u{f181}"
case tumblr = "\u{f173}"
case tumblrSquare = "\u{f174}"
case twitch = "\u{f1e8}"
case twitter = "\u{f099}"
case twitterSquare = "\u{f081}"
case typo3 = "\u{f42b}"
case uber = "\u{f402}"
case ubuntu = "\u{f7df}"
case uikit = "\u{f403}"
case umbraco = "\u{f8e8}"
case uncharted = "\u{e084}"
case uniregistry = "\u{f404}"
case unity = "\u{e049}"
case unsplash = "\u{e07c}"
case untappd = "\u{f405}"
case ups = "\u{f7e0}"
case usb = "\u{f287}"
case usps = "\u{f7e1}"
case ussunnah = "\u{f407}"
case vaadin = "\u{f408}"
case viacoin = "\u{f237}"
case viadeo = "\u{f2a9}"
case viadeoSquare = "\u{f2aa}"
case viber = "\u{f409}"
case vimeo = "\u{f40a}"
case vimeoSquare = "\u{f194}"
case vimeoV = "\u{f27d}"
case vine = "\u{f1ca}"
case vk = "\u{f189}"
case vnv = "\u{f40b}"
case vuejs = "\u{f41f}"
case watchmanMonitoring = "\u{e087}"
case waze = "\u{f83f}"
case weebly = "\u{f5cc}"
case weibo = "\u{f18a}"
case weixin = "\u{f1d7}"
case whatsapp = "\u{f232}"
case whatsappSquare = "\u{f40c}"
case whmcs = "\u{f40d}"
case wikipediaW = "\u{f266}"
case windows = "\u{f17a}"
case wix = "\u{f5cf}"
case wizardsOfTheCoast = "\u{f730}"
case wodu = "\u{e088}"
case wolfPackBattalion = "\u{f514}"
case wordpress = "\u{f19a}"
case wordpressSimple = "\u{f411}"
case wpbeginner = "\u{f297}"
case wpexplorer = "\u{f2de}"
case wpforms = "\u{f298}"
case wpressr = "\u{f3e4}"
case xbox = "\u{f412}"
case xing = "\u{f168}"
case xingSquare = "\u{f169}"
case yCombinator = "\u{f23b}"
case yahoo = "\u{f19e}"
case yammer = "\u{f840}"
case yandex = "\u{f413}"
case yandexInternational = "\u{f414}"
case yarn = "\u{f7e3}"
case yelp = "\u{f1e9}"
case yoast = "\u{f2b1}"
case youtube = "\u{f167}"
case youtubeSquare = "\u{f431}"
case zhihu = "\u{f63f}"
public var fontType: AwesomeFont {
return Awesome.Font.brand
}
}
}
| 35.472019 | 58 | 0.499108 |
eb9a3b562de29f2849971409014792ea61c2dde8 | 6,371 | //
// AppDelegate.swift
// attendo1
//
// Created by Nik Howlett on 11/7/15.
// Copyright (c) 2015 NikHowlett. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.nikhowlett.attendo1" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("attendo1", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("attendo1.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch var error1 as NSError {
error = error1
coordinator = nil
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
} catch {
fatalError()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges {
do {
try moc.save()
} catch let error1 as NSError {
error = error1
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
}
| 52.221311 | 290 | 0.698477 |
1db85c88c9b810c5cea4687739183e7f1acc161e | 6,878 | //
// MenuContainerViewController.swift
//
// Copyright 2017 Handsome LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
/**
Container for menu view controller.
*/
open class MenuContainerViewController: UIViewController {
open override var preferredStatusBarStyle: UIStatusBarStyle {
return currentContentViewController?.preferredStatusBarStyle ?? .lightContent
}
fileprivate weak var currentContentViewController: UIViewController?
fileprivate var navigationMenuTransitionDelegate: MenuTransitioningDelegate!
/**
Flag indicating if the side menu is being shown.
*/
fileprivate var isShown = false
public var currentItemOptions = SideMenuItemOptions() {
didSet {
navigationMenuTransitionDelegate?.currentItemOptions = currentItemOptions
}
}
/**
The view controller for side menu.
*/
public var menuViewController: MenuViewController! {
didSet {
if menuViewController == nil {
fatalError("Invalid `menuViewController` value. It should not be nil")
}
menuViewController.menuContainerViewController = self
menuViewController.transitioningDelegate = navigationMenuTransitionDelegate
menuViewController.navigationMenuTransitionDelegate = navigationMenuTransitionDelegate
}
}
/**
The options defining side menu transitioning.
Could be set at any time of controller lifecycle.
*/
public var transitionOptions: TransitionOptions {
get {
return navigationMenuTransitionDelegate?.interactiveTransition.options ?? TransitionOptions()
}
set {
navigationMenuTransitionDelegate?.interactiveTransition.options = newValue
}
}
/**
The list of all content view controllers corresponding to side menu items.
*/
public var contentViewControllers = [UIViewController]()
// MARK: - Controller lifecycle
//
override open func viewDidLoad() {
super.viewDidLoad()
let interactiveTransition = MenuInteractiveTransition(
currentItemOptions: currentItemOptions,
presentAction: { [unowned self] in
self.presentNavigationMenu()
},
dismissAction: { [unowned self] in
self.dismissNavigationMenu()
}
)
navigationMenuTransitionDelegate = MenuTransitioningDelegate(interactiveTransition: interactiveTransition)
let screenEdgePanRecognizer = UIScreenEdgePanGestureRecognizer(
target: navigationMenuTransitionDelegate.interactiveTransition,
action: #selector(MenuInteractiveTransition.handlePanPresentation(recognizer:))
)
screenEdgePanRecognizer.edges = .left
view.addGestureRecognizer(screenEdgePanRecognizer)
}
override open func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
let viewBounds = CGRect(x:0, y:0, width:size.width, height:size.height)
let viewCenter = CGPoint(x:size.width/2, y:size.height/2)
coordinator.animate(alongsideTransition: { _ in
if self.menuViewController == nil {
fatalError("Invalid `menuViewController` value. It should not be nil")
}
self.menuViewController.view.bounds = viewBounds
self.menuViewController.view.center = viewCenter
self.view.bounds = viewBounds
self.view.center = viewCenter
if self.isShown {
self.hideSideMenu()
}
}, completion: nil)
}
}
// MARK: - Public
extension MenuContainerViewController {
/**
Shows left side menu.
*/
public func showSideMenu() {
presentNavigationMenu()
}
/**
Hides left side menu.
Controller from the right side will be visible.
*/
public func hideSideMenu() {
dismissNavigationMenu()
}
/**
Embeds menu item content view controller.
- parameter selectedContentVC: The view controller to be embedded.
*/
public func selectContentViewController(_ selectedContentVC: UIViewController) {
if let currentContentVC = currentContentViewController {
if currentContentVC != selectedContentVC {
currentContentVC.view.removeFromSuperview()
currentContentVC.removeFromParent()
setCurrentView(selectedContentVC)
}
} else {
setCurrentView(selectedContentVC)
}
}
}
// MARK: - Private
fileprivate extension MenuContainerViewController {
/**
Adds proper content view controller as a child.
- parameter selectedContentVC: The view controller to be added.
*/
func setCurrentView(_ selectedContentVC: UIViewController) {
addChild(selectedContentVC)
view.addSubviewWithFullSizeConstraints(view: selectedContentVC.view)
currentContentViewController = selectedContentVC
}
/**
Presents left side menu.
*/
func presentNavigationMenu() {
if menuViewController == nil {
fatalError("Invalid `menuViewController` value. It should not be nil")
}
present(menuViewController, animated: true, completion: nil)
isShown = true
}
/**
Dismisses left side menu.
*/
func dismissNavigationMenu() {
self.dismiss(animated: true, completion: nil)
isShown = false
}
}
extension UIView {
func addSubviewWithFullSizeConstraints(view : UIView) {
insertSubviewWithFullSizeConstraints(view: view, atIndex: subviews.count)
}
func insertSubviewWithFullSizeConstraints(view : UIView, atIndex: Int) {
view.translatesAutoresizingMaskIntoConstraints = false
insertSubview(view, at: atIndex)
let top = view.topAnchor.constraint(equalTo: self.topAnchor)
let leading = view.leadingAnchor.constraint(equalTo: self.leadingAnchor)
let trailing = self.trailingAnchor.constraint(equalTo: view.trailingAnchor)
let bottom = self.bottomAnchor.constraint(equalTo: view.bottomAnchor)
NSLayoutConstraint.activate([top, leading, trailing, bottom])
}
}
| 32.909091 | 117 | 0.676069 |
1d74b8e52fab9a3492c55d3095ecb7c6cee9ddb6 | 286 | import Foundation
extension ExploreTokensScene {
struct Routing {
let onDidSelectToken: (_ tokenId: ExploreTokensScene.TokenIdentifier) -> Void
let onDidSelectHistoryForBalance: (_ balanceId: String) -> Void
let onError: (_ message: String) -> Void
}
}
| 28.6 | 85 | 0.695804 |
2f5cde76c10a50907c98c75fce81dc406ea4b608 | 3,039 | //
// OnViewController2.swift
// Waller
//
// Created by Pasquale Mauriello on 14/02/18.
// Copyright © 2018 madeinchain. All rights reserved.
//
import UIKit
class OnViewController2: UIViewController {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var subTitle: UILabel!
@IBOutlet weak var multisignLabel: UILabel!
@IBOutlet weak var importingLabel: UILabel!
@IBOutlet weak var subStandardCrypto: UITextView!
@IBOutlet weak var iconLogo: UIImageView!
@IBOutlet weak var incoming: UIImageView!
@IBOutlet weak var outComing: UIImageView!
@IBOutlet weak var multisignDescription: UITextView!
@IBOutlet weak var exportImage: UIImageView!
@IBOutlet weak var qrCode2: UIImageView!
@IBOutlet weak var qrCode1: UIImageView!
@IBOutlet weak var multiSign: UIImageView!
let gradientView:GradientView = GradientView()
override func viewDidLoad() {
super.viewDidLoad()
self.iconLogo.alpha = 0
self.outComing.alpha = 0
self.incoming.alpha = 0
self.exportImage.alpha = 0
self.qrCode1.alpha = 0
self.qrCode2.alpha = 0
//let onBoardingBackgroundColor1 = UIColor(red: 26/255, green: 44/255, blue: 59/255, alpha: 1)
//let onBoardingBackgroundColor2 = UIColor(red: 53/255, green: 74/255, blue: 94/255, alpha: 1)
gradientView.frame = CGRect.init(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height)
gradientView.FirstColor = Props.myBlack
gradientView.SecondColor = Props.myBlack
self.view.addSubview(gradientView)
self.view.addSubview(titleLabel)
self.view.addSubview(subTitle)
self.view.addSubview(multisignLabel)
self.view.addSubview(importingLabel)
self.view.addSubview(subStandardCrypto)
self.view.addSubview(multisignDescription)
self.view.addSubview(iconLogo)
self.view.addSubview(outComing)
self.view.addSubview(incoming)
self.view.addSubview(exportImage)
self.view.addSubview(qrCode1)
self.view.addSubview(qrCode2)
self.view.addSubview(multiSign)
}
override func viewDidAppear(_ animated: Bool) {
UIView.animate(withDuration: 1, animations: {
self.outComing.frame.origin.x = self.outComing.frame.size.height
self.incoming.frame.origin.x = 265
self.exportImage.transform = CGAffineTransform(rotationAngle: 3.14)
self.outComing.alpha = 1
self.iconLogo.alpha = 1
self.incoming.alpha = 1
self.exportImage.alpha = 1
self.qrCode1.alpha = 1
self.qrCode2.alpha = 1
}) { (true) in
UIView.animate(withDuration: 1, animations: {
}, completion: nil)
}
}
}
| 33.032609 | 118 | 0.615334 |
f768b6f3474f3d80ef76241603c4f58539f4e63f | 4,762 | //
// DesignReviewViewModel.swift
//
//
// Created by Alex Lee on 3/3/22.
//
import Foundation
import os.log
import UIKit
/// Represents the spacing between two `CGRect`s on each side (top, bottom, left, right).
struct Specs {
enum Side {
case top, left, bottom, right
}
let top: CGFloat
let left: CGFloat
let bottom: CGFloat
let right: CGFloat
func shouldHideSpec(for side: Side) -> Bool {
switch side {
case .top:
return top == 0
case .left:
return left == 0
case .bottom:
return bottom == 0
case .right:
return right == 0
}
}
}
class DesignReviewViewModel {
private(set) var reviewables = [DesignReviewable]()
weak var coordinator: DesignReviewCoordinator?
var selectedReviewableIndices = [Int]()
var recalculateSelectionBorders: (() -> Void)?
var toggleHUDVisibility: ((_ isVisible: Bool) -> Void)?
func refreshSelectionBorders() {
recalculateSelectionBorders?()
}
func startDesignReview() {
guard let reviewableIndex = selectedReviewableIndices.last, reviewableIndex < reviewables.count else {
os_log("Error: tried to start a design review, but no valid index was found")
return
}
coordinator?.presentDesignReview(for: reviewables[reviewableIndex])
}
func updateReviewables() {
reviewables = parse(coordinator?.appWindow)
reviewables.reverse()
}
func updateSelectedIndices(index: Int, isPanning: Bool) {
if !selectedReviewableIndices.isEmpty, isPanning {
selectedReviewableIndices.removeLast()
} else if selectedReviewableIndices.count > 1 {
selectedReviewableIndices.removeFirst()
}
selectedReviewableIndices.append(index)
}
}
// MARK: - Helpers
extension DesignReviewViewModel {
/// Recursively extracts all reviewable content from the given container
private func parse(_ reviewableContainer: DesignReviewable?) -> [DesignReviewable] {
var newReviewables = [DesignReviewable]()
for subReviewable in reviewableContainer?.subReviewables ?? [] {
if subReviewable.isOnScreen {
newReviewables.append(subReviewable)
}
if subReviewable.subReviewables.isEmpty { continue }
newReviewables.append(contentsOf: parse(subReviewable))
}
return newReviewables
}
}
// MARK: - Distance calculation
extension DesignReviewViewModel {
/// Constructs the `Specs` representing the space between each corresponding side of two given `CGRect`s.
static func specs(between rect1: CGRect, and rect2: CGRect, in bounds: CGRect) -> Specs {
let (left, right) = horizontalSpecs(between: rect1, and: rect2, in: bounds)
let (top, bottom) = verticalSpecs(between: rect1, and: rect2, in: bounds)
return Specs(top: top, left: left, bottom: bottom, right: right)
}
/// Calculates the horizontal (left + right) spaces between the corresponding sides of two given `CGRect`s.
private static func horizontalSpecs(between rect1: CGRect,
and rect2: CGRect,
in bounds: CGRect) -> (left: CGFloat, right: CGFloat) {
var left: CGFloat = 0
var right: CGFloat = 0
if rect1.minX == rect2.minX, rect1.maxX == rect2.maxX {
left = 0
right = 0
} else if rect1.minX >= rect2.minX, rect1.maxX <= rect2.maxX {
left = rect1.minX - rect2.minX
right = rect2.maxX - rect1.maxX
} else if rect1.minX <= rect2.minX, rect1.maxX >= rect2.maxX {
left = rect2.minX - rect1.minX
right = rect1.maxX - rect2.maxX
} else if rect1.minX > rect2.minX {
left = 0
right = bounds.width - (rect1.width + rect2.width)
} else {
left = bounds.width - (rect1.width + rect2.width)
right = 0
}
return (left, right)
}
/// Calculates the vertical (top + bottom) spaces between the corresponding sides of two given `CGRect`s.
private static func verticalSpecs(between rect1: CGRect,
and rect2: CGRect,
in bounds: CGRect) -> (top: CGFloat, bottom: CGFloat) {
var top: CGFloat = 0
var bottom: CGFloat = 0
if rect1.minY == rect2.minY, rect1.maxY == rect2.maxY {
top = 0
bottom = 0
} else if rect1.minY >= rect2.minY, rect1.maxY <= rect2.maxY {
top = rect1.minY - rect2.minY
bottom = rect2.maxY - rect1.maxY
} else if rect1.minY <= rect2.minY, rect1.maxY >= rect2.maxY {
top = rect2.minY - rect1.minY
bottom = rect1.maxY - rect2.maxY
} else if rect1.minY > rect2.minY {
top = 0
bottom = bounds.height - (rect1.height + rect2.height)
} else {
top = bounds.height - (rect1.height + rect2.height)
bottom = 0
}
return (top, bottom)
}
}
| 29.57764 | 109 | 0.648257 |
c1e150c38bf9fb540ab2e787e7df7bf78a8ac947 | 1,911 | //
// Copyright (c) 2016 Commercetools. All rights reserved.
//
import Foundation
/**
All endpoints capable of being deleted by UUID should conform to this protocol.
Default implementation provides deletion by UUID capability for all Commercetools endpoints which do support it.
*/
public protocol DeleteEndpoint: Endpoint {
/**
Deletes an object by UUID at the endpoint specified with `path` value.
- parameter id: Unique ID of the object to be deleted.
- parameter version: Version of the object (for optimistic concurrency control).
- parameter expansion: An optional array of expansion property names.
- parameter result: The code to be executed after processing the response, providing model
instance in case of a successful result.
*/
static func delete(_ id: String, version: UInt, expansion: [String]?, result: @escaping (Result<ResponseType>) -> Void)
}
public extension DeleteEndpoint {
static func delete(_ id: String, version: UInt, expansion: [String]? = nil, result: @escaping (Result<ResponseType>) -> Void) {
delete(id, version: version, expansion: expansion, path: Self.path, result: result)
}
static func delete(_ id: String, version: UInt, expansion: [String]? = nil, path: String, result: @escaping (Result<ResponseType>) -> Void) {
requestWithTokenAndPath(relativePath: path, result: result) { token, path in
let fullPath = pathWithExpansion(path + id, expansion: expansion)
let request = self.request(url: fullPath, method: .delete, urlParameters: ["version": String(version)], headers: self.headers(token))
perform(request: request) { (response: Result<ResponseType>) in
result(response)
}
}
}
}
| 43.431818 | 145 | 0.644689 |
7a0e5a60873f1bb4ac6b27f4c2c9566b2a1ae651 | 986 | /*
Copyright 2016 Ryuichi Laboratories and the Yanagiba project contributors
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.
*/
public class ProtocolCompositionType : TypeBase {
public let protocolTypes: [Type]
public init(protocolTypes: [Type]) {
self.protocolTypes = protocolTypes
}
// MARK: - ASTTextRepresentable
override public var textDescription: String {
return "protocol<\(protocolTypes.map({ $0.textDescription }).joined(separator: ", "))>"
}
}
| 32.866667 | 91 | 0.739351 |
bf3c82c84ca7fdc35ff5768dc844093cffc8c26d | 8,821 | //
// BarcodeScannerViewController.swift
// barcode_scan
//
// Created by Julian Finkler on 20.02.20.
//
import Foundation
import MTBBarcodeScanner
class BarcodeScannerViewController: UIViewController {
private var previewView: UIView?
private var scanRect: ScannerOverlay?
private var scanner: MTBBarcodeScanner?
private var useCamera = -1
var config: Configuration = Configuration.with {
$0.strings = [
"title" : "",
"cancel" : "Cancel",
"flash_on" : "Flash on",
"flash_off" : "Flash off",
"switch": "Switch",
"icon": "",
]
$0.useCamera = -1 // Default camera
$0.autoEnableFlash = false
}
private let formatMap = [
BarcodeFormat.aztec : AVMetadataObject.ObjectType.aztec,
BarcodeFormat.code39 : AVMetadataObject.ObjectType.code39,
BarcodeFormat.code93 : AVMetadataObject.ObjectType.code93,
BarcodeFormat.code128 : AVMetadataObject.ObjectType.code128,
BarcodeFormat.dataMatrix : AVMetadataObject.ObjectType.dataMatrix,
BarcodeFormat.ean8 : AVMetadataObject.ObjectType.ean8,
BarcodeFormat.ean13 : AVMetadataObject.ObjectType.ean13,
BarcodeFormat.interleaved2Of5 : AVMetadataObject.ObjectType.interleaved2of5,
BarcodeFormat.pdf417 : AVMetadataObject.ObjectType.pdf417,
BarcodeFormat.qr : AVMetadataObject.ObjectType.qr,
BarcodeFormat.upce : AVMetadataObject.ObjectType.upce,
]
var delegate: BarcodeScannerViewControllerDelegate?
private var device: AVCaptureDevice? {
return AVCaptureDevice.default(for: .video)
}
private var isFlashOn: Bool {
return device != nil && (device?.flashMode == AVCaptureDevice.FlashMode.on || device?.torchMode == .on)
}
private var buttonText: Bool {
return config.strings["icon"] != nil && (config.strings["icon"] != "true")
}
private var hasTorch: Bool {
return device?.hasTorch ?? false
}
override func viewDidLoad() {
super.viewDidLoad()
#if targetEnvironment(simulator)
view.backgroundColor = .lightGray
#endif
previewView = UIView(frame: view.bounds)
if let previewView = previewView {
previewView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(previewView)
}
setupScanRect(view.bounds)
let restrictedBarcodeTypes = mapRestrictedBarcodeTypes()
if restrictedBarcodeTypes.isEmpty {
scanner = MTBBarcodeScanner(previewView: previewView)
} else {
scanner = MTBBarcodeScanner(metadataObjectTypes: restrictedBarcodeTypes,
previewView: previewView
)
}
if config.strings["icon"] != "true" {
navigationItem.leftBarButtonItem = UIBarButtonItem(title: config.strings["cancel"],
style: .plain,
target: self,
action: #selector(cancel))
} else {
self.navigationController!.navigationBar.barStyle = .black
self.navigationController!.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.white]
self.title = config.strings["title"]
let closeButton = UIButton(type: .custom)
closeButton.setImage(UIImage(named: "ic_close"), for: .normal)
closeButton.addTarget(self, action: #selector(cancel), for: .touchUpInside)
navigationItem.leftBarButtonItem = UIBarButtonItem(customView: closeButton)
}
updateMenuButtons()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if scanner!.isScanning() {
scanner!.stopScanning()
}
scanRect?.startAnimating()
MTBBarcodeScanner.requestCameraPermission(success: { success in
if success {
self.startScan()
} else {
#if !targetEnvironment(simulator)
self.errorResult(errorCode: "PERMISSION_NOT_GRANTED")
#endif
}
})
}
override func viewWillDisappear(_ animated: Bool) {
scanner?.stopScanning()
scanRect?.stopAnimating()
if isFlashOn {
setFlashState(false)
}
super.viewWillDisappear(animated)
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
setupScanRect(CGRect(origin: CGPoint(x: 0, y:0),
size: size
))
}
private func setupScanRect(_ bounds: CGRect) {
if scanRect != nil {
scanRect?.stopAnimating()
scanRect?.removeFromSuperview()
}
scanRect = ScannerOverlay(frame: bounds)
if let scanRect = scanRect {
scanRect.translatesAutoresizingMaskIntoConstraints = false
scanRect.backgroundColor = UIColor.clear
view.addSubview(scanRect)
scanRect.startAnimating()
}
}
private func startScan() {
do {
try scanner!.startScanning(with: cameraFromConfig, resultBlock: { codes in
if let code = codes?.first {
let codeType = self.formatMap.first(where: { $0.value == code.type });
let scanResult = ScanResult.with {
$0.type = .barcode
$0.rawContent = code.stringValue ?? ""
$0.format = codeType?.key ?? .unknown
$0.formatNote = codeType == nil ? code.type.rawValue : ""
}
self.scanner!.stopScanning()
self.scanResult(scanResult)
}
})
if(config.autoEnableFlash){
DispatchQueue.main.asyncAfter(deadline: .now() + 0.15) {
self.setFlashState(true)
}
}
} catch {
self.scanResult(ScanResult.with {
$0.type = .error
$0.rawContent = "\(error)"
$0.format = .unknown
})
}
}
@objc private func cancel() {
scanResult( ScanResult.with {
$0.type = .cancelled
$0.format = .unknown
});
}
@objc private func onToggleFlash() {
setFlashState(!isFlashOn)
}
@objc private func switchCamera() {
if (useCamera == -1 || useCamera == 0) {
useCamera = 1
}else if (useCamera == 1){
useCamera = 0
} else {
useCamera = -1
}
viewDidAppear(true)
}
private func updateMenuButtons() {
if config.strings["icon"] != "true" {
let buttonText = isFlashOn ? config.strings["flash_off"] : config.strings["flash_on"]
let btnFlash = UIBarButtonItem(title: buttonText, style: .plain, target: self, action: #selector(onToggleFlash))
let btnSwitch = UIBarButtonItem(title: "Switch", style: .plain, target: self, action: #selector(switchCamera))
self.navigationItem.setRightBarButtonItems([btnFlash, btnSwitch], animated: true)
} else {
let buttonFlash = UIButton(type: .custom)
if isFlashOn {
buttonFlash.setImage(UIImage(named: "ic_flash_off"), for: .normal)
} else {
buttonFlash.setImage(UIImage(named: "ic_flash_on"), for: .normal)
}
buttonFlash.addTarget(self, action: #selector(onToggleFlash), for: .touchUpInside)
buttonFlash.contentEdgeInsets = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 8)
let barButtonFlash = UIBarButtonItem(customView: buttonFlash)
let buttonSwitch = UIButton(type: .custom)
buttonSwitch.setImage(UIImage(named: "ic_switch"), for: .normal)
buttonSwitch.addTarget(self, action: #selector(switchCamera), for: .touchUpInside)
buttonSwitch.contentEdgeInsets = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 2)
let barButtonSwitch = UIBarButtonItem(customView: buttonSwitch)
self.navigationItem.setRightBarButtonItems([barButtonSwitch, barButtonFlash], animated: true)
}
}
private func setFlashState(_ on: Bool) {
if let device = device {
guard device.hasFlash && device.hasTorch else {
return
}
do {
try device.lockForConfiguration()
} catch {
return
}
device.flashMode = on ? .on : .off
device.torchMode = on ? .on : .off
device.unlockForConfiguration()
updateMenuButtons()
}
}
private func errorResult(errorCode: String){
delegate?.didFailWithErrorCode(self, errorCode: errorCode)
dismiss(animated: false)
}
private func scanResult(_ scanResult: ScanResult){
self.delegate?.didScanBarcodeWithResult(self, scanResult: scanResult)
dismiss(animated: false)
}
private func mapRestrictedBarcodeTypes() -> [String] {
var types: [AVMetadataObject.ObjectType] = []
config.restrictFormat.forEach({ format in
if let mappedFormat = formatMap[format]{
types.append(mappedFormat)
}
})
return types.map({ t in t.rawValue})
}
private var cameraFromConfig: MTBCamera {
return useCamera == 1 ? .front : .back
}
} | 31.503571 | 118 | 0.647206 |
bb0d002154568b03ddc359fbd03f9195361aa444 | 3,147 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import Basic
import PackageGraph
import SourceControl
import Utility
/// A checkout state represents the current state of a repository.
///
/// A state will always has a revision. It can also have a branch or a version but not both.
public struct CheckoutState: Equatable {
/// The revision of the checkout.
public let revision: Revision
/// The version of the checkout, if known.
public let version: Version?
/// The branch of the checkout, if known.
public let branch: String?
/// Create a checkout state with given data. It is invalid to provide both version and branch.
///
/// This is deliberately fileprivate so CheckoutState is not initialized
/// with both version and branch. All other initializers should delegate to it.
fileprivate init(revision: Revision, version: Version?, branch: String?) {
assert(version == nil || branch == nil, "Can't set both branch and version.")
self.revision = revision
self.version = version
self.branch = branch
}
/// Create a checkout state with given revision and branch.
public init(revision: Revision, branch: String? = nil) {
self.init(revision: revision, version: nil, branch: branch)
}
/// Create a checkout state with given revision and version.
public init(revision: Revision, version: Version) {
self.init(revision: revision, version: version, branch: nil)
}
public var description: String {
return version?.description ?? branch ?? revision.identifier
}
public static func == (lhs: CheckoutState, rhs: CheckoutState) -> Bool {
return lhs.revision == rhs.revision &&
lhs.version == rhs.version &&
lhs.branch == rhs.branch
}
}
extension CheckoutState {
/// Returns requirement induced by this state.
func requirement() -> RepositoryPackageConstraint.Requirement {
if let version = version {
return .versionSet(.exact(version))
} else if let branch = branch {
return .revision(branch)
}
return .revision(revision.identifier)
}
}
// MARK: - JSON
extension CheckoutState: JSONMappable, JSONSerializable {
public init(json: JSON) throws {
self.init(
revision: try json.get("revision"),
version: json.get("version"),
branch: json.get("branch")
)
}
public func toJSON() -> JSON {
return .init([
"revision": revision.identifier,
"version": version.toJSON(),
"branch": branch.toJSON(),
])
}
}
extension ManagedDependency {
public var checkoutState: CheckoutState? {
if case .checkout(let checkoutState) = state {
return checkoutState
}
return nil
}
}
| 30.259615 | 98 | 0.649507 |
8ac58c71d2e4965c7f9aa591b97f7e0e8868ac39 | 2,387 | //
// LoginViewController+TextFieldDelegate.swift
// On The Map
//
// Created by Rajanikant Deshmukh on 17/03/18.
// Copyright © 2018 Rajanikant Deshmukh. All rights reserved.
//
import Foundation
import UIKit
extension LoginViewController : UITextFieldDelegate {
// MARK: UITextFieldDelegate Methods
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if (textField == emailTextField) {
passwordTextField.becomeFirstResponder()
} else {
textField.resignFirstResponder()
startLogin()
}
return true
}
// MARK: Keyboard Methods
func subscribeToKeyboardNotifications() {
// Use UIKeyboard WillChangeFrame instead of WillShow for supporting multiple keyboards
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(_:)), name: .UIKeyboardWillChangeFrame, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: .UIKeyboardWillHide, object: nil)
}
func unsubscribeFromKeyboardNotifications() {
// Removes all notification observers
NotificationCenter.default.removeObserver(self)
}
@objc func keyboardWillChange(_ notification:Notification) {
// Bottom Y point of the stack view
let safeBottom = self.stackView.frame.maxY + 16
// Top Y point of keyboard
let keyboardTop = self.view.frame.height - getKeyboardHeight(notification)
let offset = safeBottom - keyboardTop
// If the stackview is completely visible, no need to shift view
if (offset <= 0) {
return
}
UIView.animate(withDuration: 0.3, animations: {
self.view.frame.origin.y = 0
self.view.frame.origin.y -= offset
})
}
@objc func keyboardWillHide(_ notification:Notification) {
// Reset the view to it's original position
UIView.animate(withDuration: 0.3, animations: {
self.view.frame.origin.y = 0
})
}
func getKeyboardHeight(_ notification:Notification) -> CGFloat {
let userInfo = notification.userInfo
let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue
return keyboardSize.cgRectValue.height
}
}
| 33.152778 | 144 | 0.651864 |
e4db37694bb946a0af807f1f4db3d1419a474694 | 906 | //
// GradientImageView.swift
// tmdb-mvvm-pure
//
// Created by krawiecp-home on 30/01/2019.
// Copyright © 2019 tailec. All rights reserved.
//
import UIKit
final class GradientImageView: UIImageView {
override init(image: UIImage?) {
super.init(image: image)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private func setup() {
layer.backgroundColor = UIColor.black.cgColor
layer.opacity = 0.1
let gradient = CAGradientLayer()
gradient.frame = bounds
gradient.colors = [UIColor.clear.cgColor, UIColor(red: 18/255, green: 18/255, blue: 18/255, alpha: 1.0).cgColor, UIColor(red: 18/255, green: 18/255, blue: 18/255, alpha: 1.0).cgColor, UIColor.clear.cgColor]
gradient.locations = [0, 0.1, 0.9, 1]
layer.mask = gradient
}
}
| 27.454545 | 214 | 0.616998 |
5b3be92122fc5d5fa230a09d093f0e8b8d4e9dbf | 25,776 | //
// Differentiator.swift
// RxDataSources
//
// Created by Krunoslav Zaher on 6/27/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
public enum DifferentiatorError
: Error
, CustomDebugStringConvertible {
case duplicateItem(item: Any)
case duplicateSection(section: Any)
case invalidInitializerImplementation(section: Any, expectedItems: Any, expectedIdentifier: Any)
}
extension DifferentiatorError {
public var debugDescription: String {
switch self {
case let .duplicateItem(item):
return "Duplicate item \(item)"
case let .duplicateSection(section):
return "Duplicate section \(section)"
case let .invalidInitializerImplementation(section, expectedItems, expectedIdentifier):
return "Wrong initializer implementation for: \(section)\n" +
"Expected it should return items: \(expectedItems)\n" +
"Expected it should have id: \(expectedIdentifier)"
}
}
}
enum EditEvent : CustomDebugStringConvertible {
case inserted // can't be found in old sections
case insertedAutomatically // Item inside section being inserted
case deleted // Was in old, not in new, in it's place is something "not new" :(, otherwise it's Updated
case deletedAutomatically // Item inside section that is being deleted
case moved // same item, but was on different index, and needs explicit move
case movedAutomatically // don't need to specify any changes for those rows
case untouched
}
extension EditEvent {
var debugDescription: String {
get {
switch self {
case .inserted:
return "Inserted"
case .insertedAutomatically:
return "InsertedAutomatically"
case .deleted:
return "Deleted"
case .deletedAutomatically:
return "DeletedAutomatically"
case .moved:
return "Moved"
case .movedAutomatically:
return "MovedAutomatically"
case .untouched:
return "Untouched"
}
}
}
}
struct SectionAssociatedData {
var event: EditEvent
var indexAfterDelete: Int?
var moveIndex: Int?
}
extension SectionAssociatedData : CustomDebugStringConvertible {
var debugDescription: String {
get {
return "\(event), \(String(describing: indexAfterDelete))"
}
}
}
extension SectionAssociatedData {
static var initial: SectionAssociatedData {
return SectionAssociatedData(event: .untouched, indexAfterDelete: nil, moveIndex: nil)
}
}
struct ItemAssociatedData {
var event: EditEvent
var indexAfterDelete: Int?
var moveIndex: ItemPath?
}
extension ItemAssociatedData : CustomDebugStringConvertible {
var debugDescription: String {
get {
return "\(event) \(String(describing: indexAfterDelete))"
}
}
}
extension ItemAssociatedData {
static var initial : ItemAssociatedData {
return ItemAssociatedData(event: .untouched, indexAfterDelete: nil, moveIndex: nil)
}
}
func indexSections<S: AnimatableSectionModelType>(_ sections: [S]) throws -> [S.Identity : Int] {
var indexedSections: [S.Identity : Int] = [:]
for (i, section) in sections.enumerated() {
guard indexedSections[section.identity] == nil else {
#if DEBUG
if indexedSections[section.identity] != nil {
print("Section \(section) has already been indexed at \(indexedSections[section.identity]!)")
}
#endif
throw DifferentiatorError.duplicateItem(item: section)
}
indexedSections[section.identity] = i
}
return indexedSections
}
func indexSectionItems<S: AnimatableSectionModelType>(_ sections: [S]) throws -> [S.Item.Identity : (Int, Int)] {
var totalItems = 0
for i in 0 ..< sections.count {
totalItems += sections[i].items.count
}
// let's make sure it's enough
var indexedItems: [S.Item.Identity : (Int, Int)] = Dictionary(minimumCapacity: totalItems * 3)
for i in 0 ..< sections.count {
for (j, item) in sections[i].items.enumerated() {
guard indexedItems[item.identity] == nil else {
#if DEBUG
if indexedItems[item.identity] != nil {
print("Item \(item) has already been indexed at \(indexedItems[item.identity]!)" )
}
#endif
throw DifferentiatorError.duplicateItem(item: item)
}
indexedItems[item.identity] = (i, j)
}
}
return indexedItems
}
/*
I've uncovered this case during random stress testing of logic.
This is the hardest generic update case that causes two passes, first delete, and then move/insert
[
NumberSection(model: "1", items: [1111]),
NumberSection(model: "2", items: [2222]),
]
[
NumberSection(model: "2", items: [0]),
NumberSection(model: "1", items: []),
]
If update is in the form
* Move section from 2 to 1
* Delete Items at paths 0 - 0, 1 - 0
* Insert Items at paths 0 - 0
or
* Move section from 2 to 1
* Delete Items at paths 0 - 0
* Reload Items at paths 1 - 0
or
* Move section from 2 to 1
* Delete Items at paths 0 - 0
* Reload Items at paths 0 - 0
it crashes table view.
No matter what change is performed, it fails for me.
If anyone knows how to make this work for one Changeset, PR is welcome.
*/
// If you are considering working out your own algorithm, these are tricky
// transition cases that you can use.
// case 1
/*
from = [
NumberSection(model: "section 4", items: [10, 11, 12]),
NumberSection(model: "section 9", items: [25, 26, 27]),
]
to = [
HashableSectionModel(model: "section 9", items: [11, 26, 27]),
HashableSectionModel(model: "section 4", items: [10, 12])
]
*/
// case 2
/*
from = [
HashableSectionModel(model: "section 10", items: [26]),
HashableSectionModel(model: "section 7", items: [5, 29]),
HashableSectionModel(model: "section 1", items: [14]),
HashableSectionModel(model: "section 5", items: [16]),
HashableSectionModel(model: "section 4", items: []),
HashableSectionModel(model: "section 8", items: [3, 15, 19, 23]),
HashableSectionModel(model: "section 3", items: [20])
]
to = [
HashableSectionModel(model: "section 10", items: [26]),
HashableSectionModel(model: "section 1", items: [14]),
HashableSectionModel(model: "section 9", items: [3]),
HashableSectionModel(model: "section 5", items: [16, 8]),
HashableSectionModel(model: "section 8", items: [15, 19, 23]),
HashableSectionModel(model: "section 3", items: [20]),
HashableSectionModel(model: "Section 2", items: [7])
]
*/
// case 3
/*
from = [
HashableSectionModel(model: "section 4", items: [5]),
HashableSectionModel(model: "section 6", items: [20, 14]),
HashableSectionModel(model: "section 9", items: []),
HashableSectionModel(model: "section 2", items: [2, 26]),
HashableSectionModel(model: "section 8", items: [23]),
HashableSectionModel(model: "section 10", items: [8, 18, 13]),
HashableSectionModel(model: "section 1", items: [28, 25, 6, 11, 10, 29, 24, 7, 19])
]
to = [
HashableSectionModel(model: "section 4", items: [5]),
HashableSectionModel(model: "section 6", items: [20, 14]),
HashableSectionModel(model: "section 9", items: [16]),
HashableSectionModel(model: "section 7", items: [17, 15, 4]),
HashableSectionModel(model: "section 2", items: [2, 26, 23]),
HashableSectionModel(model: "section 8", items: []),
HashableSectionModel(model: "section 10", items: [8, 18, 13]),
HashableSectionModel(model: "section 1", items: [28, 25, 6, 11, 10, 29, 24, 7, 19])
]
*/
// Generates differential changes suitable for sectioned view consumption.
// It will not only detect changes between two states, but it will also try to compress those changes into
// almost minimal set of changes.
//
// I know, I know, it's ugly :( Totally agree, but this is the only general way I could find that works 100%, and
// avoids UITableView quirks.
//
// Please take into consideration that I was also convinced about 20 times that I've found a simple general
// solution, but then UITableView falls apart under stress testing :(
//
// Sincerely, if somebody else would present me this 250 lines of code, I would call him a mad man. I would think
// that there has to be a simpler solution. Well, after 3 days, I'm not convinced any more :)
//
// Maybe it can be made somewhat simpler, but don't think it can be made much simpler.
//
// The algorithm could take anywhere from 1 to 3 table view transactions to finish the updates.
//
// * stage 1 - remove deleted sections and items
// * stage 2 - move sections into place
// * stage 3 - fix moved and new items
//
// There maybe exists a better division, but time will tell.
//
public func differencesForSectionedView<S: AnimatableSectionModelType>(
_ initialSections: [S],
finalSections: [S]
)
throws -> [Changeset<S>] {
typealias I = S.Item
var result: [Changeset<S>] = []
var sectionCommands = try CommandGenerator<S>.generatorForInitialSections(initialSections, finalSections: finalSections)
result.append(contentsOf: try sectionCommands.generateDeleteSections())
result.append(contentsOf: try sectionCommands.generateInsertAndMoveSections())
result.append(contentsOf: try sectionCommands.generateNewAndMovedItems())
return result
}
private extension AnimatableSectionModelType {
init(safeOriginal: Self, safeItems: [Item]) throws {
self.init(original: safeOriginal, items: safeItems)
if self.items != safeItems || self.identity != safeOriginal.identity {
throw DifferentiatorError.invalidInitializerImplementation(section: self, expectedItems: safeItems, expectedIdentifier: safeOriginal.identity)
}
}
}
struct CommandGenerator<S: AnimatableSectionModelType> {
let initialSections: [S]
let finalSections: [S]
let initialSectionData: [SectionAssociatedData]
let finalSectionData: [SectionAssociatedData]
let initialItemData: [[ItemAssociatedData]]
let finalItemData: [[ItemAssociatedData]]
static func generatorForInitialSections(
_ initialSections: [S],
finalSections: [S]
) throws -> CommandGenerator<S> {
let (initialSectionData, finalSectionData) = try calculateSectionMovementsForInitialSections(initialSections, finalSections: finalSections)
let (initialItemData, finalItemData) = try calculateItemMovementsForInitialSections(initialSections,
finalSections: finalSections,
initialSectionData: initialSectionData,
finalSectionData: finalSectionData
)
return CommandGenerator<S>(
initialSections: initialSections,
finalSections: finalSections,
initialSectionData: initialSectionData,
finalSectionData: finalSectionData,
initialItemData: initialItemData,
finalItemData: finalItemData
)
}
static func calculateItemMovementsForInitialSections(_ initialSections: [S], finalSections: [S],
initialSectionData: [SectionAssociatedData], finalSectionData: [SectionAssociatedData]) throws -> ([[ItemAssociatedData]], [[ItemAssociatedData]]) {
var initialItemData = initialSections.map { s in
return [ItemAssociatedData](repeating: ItemAssociatedData.initial, count: s.items.count)
}
var finalItemData = finalSections.map { s in
return [ItemAssociatedData](repeating: ItemAssociatedData.initial, count: s.items.count)
}
let initialItemIndexes = try indexSectionItems(initialSections)
for i in 0 ..< finalSections.count {
for (j, item) in finalSections[i].items.enumerated() {
guard let initialItemIndex = initialItemIndexes[item.identity] else {
continue
}
if initialItemData[initialItemIndex.0][initialItemIndex.1].moveIndex != nil {
throw DifferentiatorError.duplicateItem(item: item)
}
initialItemData[initialItemIndex.0][initialItemIndex.1].moveIndex = ItemPath(sectionIndex: i, itemIndex: j)
finalItemData[i][j].moveIndex = ItemPath(sectionIndex: initialItemIndex.0, itemIndex: initialItemIndex.1)
}
}
let findNextUntouchedOldIndex = { (initialSectionIndex: Int, initialSearchIndex: Int?) -> Int? in
guard var i2 = initialSearchIndex else {
return nil
}
while i2 < initialSections[initialSectionIndex].items.count {
if initialItemData[initialSectionIndex][i2].event == .untouched {
return i2
}
i2 = i2 + 1
}
return nil
}
// first mark deleted items
for i in 0 ..< initialSections.count {
guard let _ = initialSectionData[i].moveIndex else {
continue
}
var indexAfterDelete = 0
for j in 0 ..< initialSections[i].items.count {
guard let finalIndexPath = initialItemData[i][j].moveIndex else {
initialItemData[i][j].event = .deleted
continue
}
// from this point below, section has to be move type because it's initial and not deleted
// because there is no move to inserted section
if finalSectionData[finalIndexPath.sectionIndex].event == .inserted {
initialItemData[i][j].event = .deleted
continue
}
initialItemData[i][j].indexAfterDelete = indexAfterDelete
indexAfterDelete += 1
}
}
// mark moved or moved automatically
for i in 0 ..< finalSections.count {
guard let originalSectionIndex = finalSectionData[i].moveIndex else {
continue
}
var untouchedIndex: Int? = 0
for j in 0 ..< finalSections[i].items.count {
untouchedIndex = findNextUntouchedOldIndex(originalSectionIndex, untouchedIndex)
guard let originalIndex = finalItemData[i][j].moveIndex else {
finalItemData[i][j].event = .inserted
continue
}
// In case trying to move from deleted section, abort, otherwise it will crash table view
if initialSectionData[originalIndex.sectionIndex].event == .deleted {
finalItemData[i][j].event = .inserted
continue
}
// original section can't be inserted
else if initialSectionData[originalIndex.sectionIndex].event == .inserted {
try rxPrecondition(false, "New section in initial sections, that is wrong")
}
let initialSectionEvent = initialSectionData[originalIndex.sectionIndex].event
try rxPrecondition(initialSectionEvent == .moved || initialSectionEvent == .movedAutomatically, "Section not moved")
let eventType = originalIndex == ItemPath(sectionIndex: originalSectionIndex, itemIndex: untouchedIndex ?? -1)
? EditEvent.movedAutomatically : EditEvent.moved
initialItemData[originalIndex.sectionIndex][originalIndex.itemIndex].event = eventType
finalItemData[i][j].event = eventType
}
}
return (initialItemData, finalItemData)
}
static func calculateSectionMovementsForInitialSections(_ initialSections: [S], finalSections: [S]) throws -> ([SectionAssociatedData], [SectionAssociatedData]) {
let initialSectionIndexes = try indexSections(initialSections)
var initialSectionData = [SectionAssociatedData](repeating: SectionAssociatedData.initial, count: initialSections.count)
var finalSectionData = [SectionAssociatedData](repeating: SectionAssociatedData.initial, count: finalSections.count)
for (i, section) in finalSections.enumerated() {
guard let initialSectionIndex = initialSectionIndexes[section.identity] else {
continue
}
if initialSectionData[initialSectionIndex].moveIndex != nil {
throw DifferentiatorError.duplicateSection(section: section)
}
initialSectionData[initialSectionIndex].moveIndex = i
finalSectionData[i].moveIndex = initialSectionIndex
}
var sectionIndexAfterDelete = 0
// deleted sections
for i in 0 ..< initialSectionData.count {
if initialSectionData[i].moveIndex == nil {
initialSectionData[i].event = .deleted
continue
}
initialSectionData[i].indexAfterDelete = sectionIndexAfterDelete
sectionIndexAfterDelete += 1
}
// moved sections
var untouchedOldIndex: Int? = 0
let findNextUntouchedOldIndex = { (initialSearchIndex: Int?) -> Int? in
guard var i = initialSearchIndex else {
return nil
}
while i < initialSections.count {
if initialSectionData[i].event == .untouched {
return i
}
i = i + 1
}
return nil
}
// inserted and moved sections {
// this should fix all sections and move them into correct places
// 2nd stage
for i in 0 ..< finalSections.count {
untouchedOldIndex = findNextUntouchedOldIndex(untouchedOldIndex)
// oh, it did exist
if let oldSectionIndex = finalSectionData[i].moveIndex {
let moveType = oldSectionIndex != untouchedOldIndex ? EditEvent.moved : EditEvent.movedAutomatically
finalSectionData[i].event = moveType
initialSectionData[oldSectionIndex].event = moveType
}
else {
finalSectionData[i].event = .inserted
}
}
// inserted sections
for (i, section) in finalSectionData.enumerated() {
if section.moveIndex == nil {
_ = finalSectionData[i].event == .inserted
}
}
return (initialSectionData, finalSectionData)
}
mutating func generateDeleteSections() throws -> [Changeset<S>] {
var deletedSections = [Int]()
var deletedItems = [ItemPath]()
var updatedItems = [ItemPath]()
var afterDeleteState = [S]()
// mark deleted items {
// 1rst stage again (I know, I know ...)
for (i, initialSection) in initialSections.enumerated() {
let event = initialSectionData[i].event
// Deleted section will take care of deleting child items.
// In case of moving an item from deleted section, tableview will
// crash anyway, so this is not limiting anything.
if event == .deleted {
deletedSections.append(i)
continue
}
var afterDeleteItems: [S.Item] = []
for j in 0 ..< initialSection.items.count {
let event = initialItemData[i][j].event
switch event {
case .deleted:
deletedItems.append(ItemPath(sectionIndex: i, itemIndex: j))
case .moved, .movedAutomatically:
let finalItemIndex = try initialItemData[i][j].moveIndex.unwrap()
let finalItem = finalSections[finalItemIndex]
if finalItem != initialSections[i].items[j] {
updatedItems.append(ItemPath(sectionIndex: i, itemIndex: j))
}
afterDeleteItems.append(finalItem)
default:
try rxPrecondition(false, "Unhandled case")
}
}
afterDeleteState.append(try S(safeOriginal: initialSection, safeItems: afterDeleteItems))
}
// }
if deletedItems.count == 0 && deletedSections.count == 0 && updatedItems.count == 0 {
return []
}
return [Changeset(
finalSections: afterDeleteState,
deletedSections: deletedSections,
deletedItems: deletedItems,
updatedItems: updatedItems
)]
}
func generateInsertAndMoveSections() throws -> [Changeset<S>] {
var movedSections = [(from: Int, to: Int)]()
var insertedSections = [Int]()
for i in 0 ..< initialSections.count {
switch initialSectionData[i].event {
case .deleted:
break
case .moved:
movedSections.append((from: try initialSectionData[i].indexAfterDelete.unwrap(), to: try initialSectionData[i].moveIndex.unwrap()))
case .movedAutomatically:
break
default:
try rxPrecondition(false, "Unhandled case in initial sections")
}
}
for i in 0 ..< finalSections.count {
switch finalSectionData[i].event {
case .inserted:
insertedSections.append(i)
default:
break
}
}
if insertedSections.count == 0 && movedSections.count == 0 {
return []
}
// sections should be in place, but items should be original without deleted ones
let sectionsAfterChange: [S] = try self.finalSections.enumerated().map { pair -> S in
let event = self.finalSectionData[pair.offset].event
if event == .inserted {
// it's already set up
return pair.element
}
else if event == .moved || event == .movedAutomatically {
let originalSectionIndex = try finalSectionData[pair.offset].moveIndex.unwrap()
let originalSection = initialSections[originalSectionIndex]
var items: [S.Item] = []
for (j, _) in originalSection.items.enumerated() {
let initialData = self.initialItemData[originalSectionIndex][j]
guard initialData.event != .deleted else {
continue
}
guard let finalIndex = initialData.moveIndex else {
try rxPrecondition(false, "Item was moved, but no final location.")
continue
}
items.append(self.finalSections[finalIndex.sectionIndex].items[finalIndex.itemIndex])
}
let modifiedSection = try S(safeOriginal: pair.element, safeItems: items)
return modifiedSection
}
else {
try rxPrecondition(false, "This is weird, this shouldn't happen")
return pair.element
}
}
return [Changeset(
finalSections: sectionsAfterChange,
insertedSections: insertedSections,
movedSections: movedSections
)]
}
mutating func generateNewAndMovedItems() throws -> [Changeset<S>] {
var insertedItems = [ItemPath]()
var movedItems = [(from: ItemPath, to: ItemPath)]()
// mark new and moved items {
// 3rd stage
for i in 0 ..< finalSections.count {
let finalSection = finalSections[i]
let sectionEvent = finalSectionData[i].event
// new and deleted sections cause reload automatically
if sectionEvent != .moved && sectionEvent != .movedAutomatically {
continue
}
for j in 0 ..< finalSection.items.count {
let currentItemEvent = finalItemData[i][j].event
try rxPrecondition(currentItemEvent != .untouched, "Current event is not untouched")
let event = finalItemData[i][j].event
switch event {
case .inserted:
insertedItems.append(ItemPath(sectionIndex: i, itemIndex: j))
case .moved:
let originalIndex = try finalItemData[i][j].moveIndex.unwrap()
let finalSectionIndex = try initialSectionData[originalIndex.sectionIndex].moveIndex.unwrap()
let moveFromItemWithIndex = try initialItemData[originalIndex.sectionIndex][originalIndex.itemIndex].indexAfterDelete.unwrap()
let moveCommand = (
from: ItemPath(sectionIndex: finalSectionIndex, itemIndex: moveFromItemWithIndex),
to: ItemPath(sectionIndex: i, itemIndex: j)
)
movedItems.append(moveCommand)
default:
break
}
}
}
// }
if insertedItems.count == 0 && movedItems.count == 0 {
return []
}
return [Changeset(
finalSections: finalSections,
insertedItems: insertedItems,
movedItems: movedItems
)]
}
}
| 36.458274 | 166 | 0.605563 |
224316e57e19f7a5470d1ae5d3ff7a010bdfc064 | 1,269 | //
// FLTypeButton.swift
// flash
//
// Created by Songwut Maneefun on 4/7/2564 BE.
//
import UIKit
class FLTypeButton: UIButton {
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
}
class RotationGesture: UIRotationGestureRecognizer {
}
class PanGesture: UIPanGestureRecognizer {
}
class TapGesture: UITapGestureRecognizer {
}
class PinchGesture: UIPinchGestureRecognizer {
}
class FLTextView: UITextView {
override open func layoutSubviews() {
super.layoutSubviews()
print("FLTextView layoutSubviews")
}
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
// if action == #selector(UIResponderStandardEditActions.paste(_:)) {
// return false
// } else if action == #selector(UIResponderStandardEditActions.copy(_:)) {
// return false
// } else if action == #selector(UIResponderStandardEditActions.cut(_:)) {
// return false
// }
// return false
return super.canPerformAction(action, withSender: sender)
}
}
| 23.072727 | 89 | 0.64539 |
9cee1147b7de2a9c93124ee7e5f8d90f745bff1a | 2,401 | extension Publisher {
/// Ingores all upstream elements, but passes along a completion state (finished or failed).
///
/// The output type of this publisher is `Never`.
/// - Returns: A publisher that ignores all upstream elements.
public func ignoreOutput() -> Publishers.IgnoreOutput<Self> {
return .init(upstream: self)
}
}
extension Publishers.IgnoreOutput : Equatable where Upstream : Equatable {
/// Returns a Boolean value that indicates whether two publishers are equivalent.
///
/// - Parameters:
/// - lhs: An ignore output publisher to compare for equality.
/// - rhs: Another ignore output publisher to compare for equality.
/// - Returns: `true` if the two publishers have equal upstream publishers, `false` otherwise.
public static func == (lhs: Publishers.IgnoreOutput<Upstream>, rhs: Publishers.IgnoreOutput<Upstream>) -> Bool {
return lhs.upstream == rhs.upstream
}
}
extension Publishers {
/// A publisher that ignores all upstream elements, but passes along a completion state (finish or failed).
public struct IgnoreOutput<Upstream> : Publisher where Upstream : Publisher {
/// The kind of values published by this publisher.
public typealias Output = Never
/// The kind of errors this publisher might publish.
///
/// Use `Never` if this `Publisher` does not publish errors.
public typealias Failure = Upstream.Failure
/// The publisher from which this publisher receives elements.
public let upstream: Upstream
public init(upstream: Upstream) {
self.upstream = upstream
}
/// 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, Upstream.Failure == S.Failure, S.Input == Publishers.IgnoreOutput<Upstream>.Output {
self.upstream
.filter { _ in false }
.map { _ in fatalError() }
.receive(subscriber: subscriber)
}
}
}
| 40.694915 | 152 | 0.624323 |
11e329c96932ebfa15ff54e2701dc0f384d7043a | 424 | import XCTest
@testable import NMOutlineView
final class NMOutlineViewTests: XCTestCase {
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct
// results.
XCTAssertEqual(NMOutlineView().text, "Hello, World!")
}
static var allTests = [
("testExample", testExample),
]
}
| 26.5 | 87 | 0.660377 |
09c79503adae82c165491f3a2c7555c40b835ac5 | 6,652 | /*
* Copyright (c) 2019, Okta, Inc. and/or its affiliates. All rights reserved.
* The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (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 XCTest
@testable import OktaOidc
class OktaOidcConfigTests: XCTestCase {
func testCreation() {
let dict = [
"clientId" : "test_client_id",
"issuer" : "test_issuer",
"scopes" : "test_scope",
"redirectUri" : "com.test:/callback",
"logoutRedirectUri" : "com.test:/logout"
]
let config: OktaOidcConfig
do {
config = try OktaOidcConfig(with: dict)
} catch let error {
XCTFail("Unexpected error: \(error)")
return
}
XCTAssertEqual("test_client_id", config.clientId)
XCTAssertEqual("test_issuer", config.issuer)
XCTAssertEqual("test_scope", config.scopes)
XCTAssertEqual(URL(string: "com.test:/callback"), config.redirectUri)
XCTAssertEqual(URL(string: "com.test:/logout"), config.logoutRedirectUri)
XCTAssertEqual(true, config.additionalParams?.isEmpty)
}
func testCreationWithAdditionalParams() {
let dict = [
"clientId" : "test_client_id",
"issuer" : "test_issuer",
"scopes" : "test_scope",
"redirectUri" : "com.test:/callback",
"logoutRedirectUri" : "com.test:/logout",
"additionalParam" : "test_param",
]
let config: OktaOidcConfig
do {
config = try OktaOidcConfig(with: dict)
} catch let error {
XCTFail("Unexpected error: \(error)")
return
}
XCTAssertEqual("test_client_id", config.clientId)
XCTAssertEqual("test_issuer", config.issuer)
XCTAssertEqual("test_scope", config.scopes)
XCTAssertEqual(URL(string: "com.test:/callback"), config.redirectUri)
XCTAssertEqual(URL(string: "com.test:/logout"), config.logoutRedirectUri)
XCTAssertEqual(1, config.additionalParams?.count)
XCTAssertEqual("test_param", config.additionalParams?["additionalParam"])
}
func testCreationWithInvalidConfig() {
var dict = [
"clientId" : "test_client_id",
"issuer" : "",
"scopes" : "test_scope",
"redirectUri" : "com.test:/callback"
]
do {
let _ = try OktaOidcConfig(with: dict)
} catch let error {
XCTAssertTrue(error.localizedDescription == OktaOidcError.missingConfigurationValues.errorDescription)
return
}
dict = [
"clientId" : "",
"issuer" : "http://www.test.com",
"scopes" : "test_scope",
"redirectUri" : "com.test:/callback"
]
do {
let _ = try OktaOidcConfig(with: dict)
} catch let error {
XCTAssertTrue(error.localizedDescription == OktaOidcError.missingConfigurationValues.errorDescription)
return
}
dict = [
"clientId" : "test_client_id",
"issuer" : "http://www.test.com",
"scopes" : "test_scope",
"redirectUri" : ""
]
do {
let _ = try OktaOidcConfig(with: dict)
} catch let error {
XCTAssertTrue(error.localizedDescription == OktaOidcError.missingConfigurationValues.errorDescription)
return
}
}
func testDefaultConfig() {
do {
let _ = try OktaOidcConfig.default()
} catch let error {
XCTAssertEqual(
OktaOidcError.missingConfigurationValues.localizedDescription,
error.localizedDescription
)
}
}
func testOktaPlist() {
do {
let _ = try OktaOidcConfig(fromPlist: "Okta")
} catch let error {
XCTAssertEqual(
OktaOidcError.missingConfigurationValues.localizedDescription,
error.localizedDescription
)
}
}
func testNoPListGiven() {
// name of file which does not exists
let plistName = UUID().uuidString
var config: OktaOidcConfig? = nil
do {
config = try OktaOidcConfig(fromPlist: plistName)
} catch let error {
XCTAssertEqual(
error.localizedDescription,
OktaOidcError.noPListGiven.localizedDescription
)
}
XCTAssertNil(config)
}
func testPListParseFailure() {
// Info.plist does not correspond to expected structure of Okta file
let plistName = "Info"
var config: OktaOidcConfig? = nil
do {
config = try OktaOidcConfig(fromPlist: plistName)
} catch let error {
XCTAssertEqual(
error.localizedDescription,
OktaOidcError.pListParseFailure.localizedDescription
)
}
XCTAssertNil(config)
}
func testUserAgent() {
OktaOidcConfig.setUserAgent(value: "some user agent")
XCTAssertEqual(OktaUserAgent.userAgentHeaderValue(), "some user agent")
}
func testNoSSOOption() {
do {
if #available(iOS 13.0, *) {
let config = try OktaOidcConfig.default()
var oidc = OktaOidcBrowserTaskIOS(presenter: UIViewController(), config: config, oktaAPI: OktaOidcRestApi())
var externalUA = oidc.externalUserAgent()
XCTAssertTrue(externalUA is OIDExternalUserAgentIOS)
config.noSSO = true
oidc = OktaOidcBrowserTaskIOS(presenter: UIViewController(), config: config, oktaAPI: OktaOidcRestApi())
externalUA = oidc.externalUserAgent()
XCTAssertTrue(externalUA is OIDExternalUserAgentNoSsoIOS)
}
} catch let error {
XCTAssertEqual(
OktaOidcError.missingConfigurationValues.localizedDescription,
error.localizedDescription
)
}
}
}
| 34.112821 | 124 | 0.58178 |
1178fd3934671d8b372452677225ec5fa1b452ea | 5,190 | //
// PayoutRoutes.swift
// Stripe
//
// Created by Andrew Edwards on 8/20/18.
//
import Vapor
import Foundation
public protocol PayoutRoutes {
func create(amount: Int, currency: StripeCurrency, description: String?, destination: String?, metadata: [String: String]?, method: StripePayoutMethod?, sourceType: StripePayoutSourceType?, statementDescriptor: String?) throws -> Future<StripePayout>
func retrieve(payout: String) throws -> Future<StripePayout>
func update(payout: String, metadata: [String: String]?) throws -> Future<StripePayout>
func listAll(filter: [String: Any]?) throws -> Future<StripePayoutsList>
func cancel(payout: String) throws -> Future<StripePayout>
}
extension PayoutRoutes {
func create(amount: Int,
currency: StripeCurrency,
description: String? = nil,
destination: String? = nil,
metadata: [String: String]? = nil,
method: StripePayoutMethod? = nil,
sourceType: StripePayoutSourceType? = nil,
statementDescriptor: String? = nil) throws -> Future<StripePayout> {
return try create(amount: amount,
currency: currency,
description: description,
destination: destination,
metadata: metadata,
method: method,
sourceType: sourceType,
statementDescriptor: statementDescriptor)
}
func retrieve(payout: String) throws -> Future<StripePayout> {
return try retrieve(payout: payout)
}
func update(payout: String, metadata: [String: String]? = nil) throws -> Future<StripePayout> {
return try update(payout: payout, metadata: metadata)
}
func listAll(filter: [String: Any]? = nil) throws -> Future<StripePayoutsList> {
return try listAll(filter: filter)
}
func cancel(payout: String) throws -> Future<StripePayout> {
return try cancel(payout: payout)
}
}
public struct StripePayoutRoutes: PayoutRoutes {
private let request: StripeRequest
init(request: StripeRequest) {
self.request = request
}
/// Create a payout
/// [Learn More →](https://stripe.com/docs/api/curl#create_payout)
public func create(amount: Int,
currency: StripeCurrency,
description: String?,
destination: String?,
metadata: [String: String]?,
method: StripePayoutMethod?,
sourceType: StripePayoutSourceType?,
statementDescriptor: String?) throws -> Future<StripePayout> {
var body: [String: Any] = [:]
body["amount"] = amount
body["currency"] = currency.rawValue
if let description = description {
body["description"] = description
}
if let destination = destination {
body["destination"] = destination
}
if let metadata = metadata {
metadata.forEach { body["metadata[\($0)]"] = $1 }
}
if let method = method {
body["method"] = method.rawValue
}
if let sourceType = sourceType {
body["source_type"] = sourceType.rawValue
}
if let statementDescriptor = statementDescriptor {
body["statement_descriptor"] = statementDescriptor
}
return try request.send(method: .POST, path: StripeAPIEndpoint.payout.endpoint, body: body.queryParameters)
}
/// Retrieve a payout
/// [Learn More →](https://stripe.com/docs/api/curl#retrieve_payout)
public func retrieve(payout: String) throws -> Future<StripePayout> {
return try request.send(method: .GET, path: StripeAPIEndpoint.payouts(payout).endpoint)
}
/// Update a payout
/// [Learn More →](https://stripe.com/docs/api/curl#update_payout)
public func update(payout: String, metadata: [String: String]?) throws -> Future<StripePayout> {
var body: [String: Any] = [:]
if let metadata = metadata {
metadata.forEach { body["metadata[\($0)]"] = $1 }
}
return try request.send(method: .POST, path: StripeAPIEndpoint.payouts(payout).endpoint, body: body.queryParameters)
}
/// List payouts
/// [Learn More →](https://stripe.com/docs/api/curl#list_payouts)
public func listAll(filter: [String : Any]?) throws -> Future<StripePayoutsList> {
var queryParams = ""
if let filter = filter {
queryParams = filter.queryParameters
}
return try request.send(method: .GET, path: StripeAPIEndpoint.payout.endpoint, query: queryParams)
}
/// Cancel payout
/// [Learn More →](https://stripe.com/docs/api/curl#cancel_payout)
public func cancel(payout: String) throws -> Future<StripePayout> {
return try request.send(method: .POST, path: StripeAPIEndpoint.payoutsCancel(payout).endpoint)
}
}
| 37.883212 | 254 | 0.593642 |
1cabd05e4e56f4b7bbe37ac5f5f2508111ac4ce9 | 640 | import Foundation
import CoreNavigation
extension NSUserActivity {
enum Error: Swift.Error {
case unprocessableEntity
}
func navigate() throws {
guard
activityType == NSUserActivityTypeBrowsingWeb,
let url = webpageURL
else {
throw Error.unprocessableEntity
}
Navigate.push { $0
.to(url)
.animated(false)
.onSuccess({ (result) in
let color = result.data as? UIColor
print("Did open deep link url: \(url), data: \(color!)")
})
}
}
}
| 22.857143 | 72 | 0.50625 |
e9422f06e60e6efac931be8b76c7a2689e4efa57 | 2,080 | /*
* --------------------------------------------------------------------------------------------------------------------
* <copyright company="Aspose">
* Copyright (c) 2020 Aspose.Slides for Cloud
* </copyright>
* <summary>
* 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.
* </summary>
* --------------------------------------------------------------------------------------------------------------------
*/
import Foundation
/** Represents list of Links to Paragraphs resources */
public struct Paragraphs: Codable {
/** Gets or sets the link to this resource. */
public var selfUri: ResourceUri?
/** List of alternate links. */
public var alternateLinks: [ResourceUri]?
/** List of paragraph links. */
public var paragraphLinks: [ResourceUriElement]?
public init(selfUri: ResourceUri?, alternateLinks: [ResourceUri]?, paragraphLinks: [ResourceUriElement]?) {
self.selfUri = selfUri
self.alternateLinks = alternateLinks
self.paragraphLinks = paragraphLinks
}
}
| 40 | 119 | 0.640385 |
c1bbafc0d1267d167395d05ac82b787d527fcb45 | 1,167 | //
// HYConstants.swift
// Quick-Start-iOS
//
// Created by work on 2016/11/4.
// Copyright © 2016年 hyyy. All rights reserved.
//
import UIKit
struct HYConstants {
static let ScreenWidth = UIScreen.main.bounds.width // 屏幕宽度
static let ScreenHeight = UIScreen.main.bounds.height // 屏幕高度
static let alertCellheight: CGFloat = 44 // AlertCell的高度
static let alertSpec: CGFloat = 40 // AlertCell距离屏幕边的间距
static let alertCornerRadius: CGFloat = 8 // Alert视图圆角大小
static let shareItemHeight: CGFloat = 80 // 分享item的高度
static let shareItemWidth: CGFloat = 80 // 分享item的宽度
static let shareItemPadding: CGFloat = 14 // 分享item之间的距离
static let shareCancelItemHeight: CGFloat = 49 // 分享底部取消的高度
static let presentAnimateDuration: TimeInterval = 0.7 // present动画时间
static let dismissAnimateDuration: TimeInterval = 0.7 // dismiss动画时间
static let dimBackgroundAlpha: CGFloat = 0.4 // 半透明背景的alpha值
static let defaultCancelText: String = "取消" // 默认取消按钮文字
static let titleFont: CGFloat = 14 // title文字大小
static let messageFont: CGFloat = 12 // message文字大小
}
| 34.323529 | 74 | 0.683805 |
de241f6df19532d47d6608fcdc2e6f3fc0a0ad5d | 459 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
class B{enum S:a}struct d{struct Q{protocol P{{}struct S<g:A
| 45.9 | 79 | 0.751634 |
5bcd7b381f1ffcd568934f95d2de05784e8e9489 | 753 | //
// Array+Extensions.swift
// NVExtensions
//
// Created by Vinh Nguyen on 24/3/19.
// Copyright © 2019 Vinh Nguyen. All rights reserved.
//
import Foundation
extension Array where Element == String {
public var commonText: String {
var result = [String]()
for loop in enumerated() {
let lhs = loop.element
guard let rhs = self[safe: loop.offset + 1] else {
result.append(lhs)
break
}
let sharedText = lhs.commonPrefix(with: rhs, options: .caseInsensitive)
result.append(sharedText)
}
return result.first ?? ""
}
}
extension Array where Element: Hashable {
public var asSet: Set<Element> { Set(self) }
}
| 22.147059 | 83 | 0.580345 |
62db337bb1af23b17ca4050bf2422e5ef61886ac | 688 | protocol ISendConfirmationDelegate: class {
func onSendClicked()
func onCancelClicked()
}
protocol ISendConfirmationView: class {
func show(viewItem: SendConfirmationAmountViewItem)
func show(viewItem: SendConfirmationMemoViewItem)
func show(viewItem: SendConfirmationFeeViewItem)
func show(viewItem: SendConfirmationTotalViewItem)
func show(viewItem: SendConfirmationDurationViewItem)
func buildData()
func showCopied()
}
protocol ISendConfirmationViewDelegate {
func viewDidLoad()
func onCopy(receiver: String)
func onSendClicked()
func onCancelClicked()
}
protocol ISendConfirmationInteractor {
func copy(receiver: String)
}
| 25.481481 | 57 | 0.770349 |
0e2c99c8b859c53666787c86298f9689564d4000 | 2,937 | //
// Gradient.swift
// Charts
//
// Created by Kharyton Batkov on 09.03.2022.
//
import Foundation
import CoreGraphics
@objc
open class Gradient: NSObject {
let startColor: CGColor
let endColor: CGColor
let startPoint: CGPoint
let endPoint: CGPoint
public init(startColor: CGColor, endColor: CGColor, angle: CGFloat) {
self.startColor = startColor
self.endColor = endColor
let points = Self.calculatePoints(for: angle)
startPoint = points.0
endPoint = points.1
super.init()
}
open override var description: String {
"start: \(startColor.componentsString)\nend: \(endColor.componentsString)\n\(startPoint)-\(endPoint)"
}
open override var debugDescription: String {
description
}
}
extension Gradient {
var locations: [CGFloat] { [0, 1] }
var colors: CFArray { [startColor, endColor] as CFArray }
var cgGradient: CGGradient {
CGGradient(
colorsSpace: nil,
colors: colors,
locations: locations
)!
}
func startPoint(in rect: CGRect) -> CGPoint {
CGPoint(x: rect.midX, y: rect.minY)
}
func endPoint(in rect: CGRect) -> CGPoint {
CGPoint(x: rect.midX, y: rect.maxY)
}
}
extension Gradient {
private static func calculatePoints(for angle: CGFloat) -> (CGPoint, CGPoint) {
var ang = (-angle).truncatingRemainder(dividingBy: 360)
if ang < 0 { ang = 360 + ang }
let n: CGFloat = 0.5
switch ang {
case 0 ... 45, 315 ... 360:
let a = CGPoint(x: 0, y: n * tanx(ang) + n)
let b = CGPoint(x: 1, y: n * tanx(-ang) + n)
return (a, b)
case 45 ... 135:
let a = CGPoint(x: n * tanx(ang - 90) + n, y: 1)
let b = CGPoint(x: n * tanx(-ang - 90) + n, y: 0)
return (a, b)
case 135 ... 225:
let a = CGPoint(x: 1, y: n * tanx(-ang) + n)
let b = CGPoint(x: 0, y: n * tanx(ang) + n)
return (a, b)
case 225 ... 315:
let a = CGPoint(x: n * tanx(-ang - 90) + n, y: 0)
let b = CGPoint(x: n * tanx(ang - 90) + n, y: 1)
return (a, b)
default:
let a = CGPoint(x: 0, y: n)
let b = CGPoint(x: 1, y: n)
return (a, b)
}
}
private static func tanx(_ 𝜽: CGFloat) -> CGFloat {
return tan(𝜽 * CGFloat.pi / 180)
}
}
public extension CGColor {
class func stringFrom(color: CGColor) -> String {
guard let components = color.components else {
return "\(self)"
}
return "[\(components[0]), \(components[1]), \(components[2]), \(components[3])]"
}
var componentsString: String {
CGColor.stringFrom(color: self)
}
}
| 26.459459 | 109 | 0.52128 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.