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
|
---|---|---|---|---|---|
6967a5cf7ff671a9c56ce2db37f21fb7313590e2
| 5,471 |
// --------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// The MIT License (MIT)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the ""Software""), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
// --------------------------------------------------------------------------
import Foundation
enum ResponseBodyType: String {
/// Returns a deserialized object (most common)
case plainBody
/// Service returns a pageable response
case pagedBody
/// Service returns no response data, only a status code
case noBody
/// Service returns a String
case stringBody
/// Service returns an Int
case intBody
/// Service returns a unixTime body
case unixTimeBody
/// Service returns a byteArray body
case byteArrayBody
static func strategy(for input: String, and schema: Schema) -> ResponseBodyType {
let type = schema.type
if input == "String" {
return .stringBody
} else if input.starts(with: "Int") {
return .intBody
} else if input == "Date" {
switch type {
case .unixTime:
return .unixTimeBody
default:
return .plainBody
}
} else if type == .byteArray {
return .byteArrayBody
} else {
return .plainBody
}
}
}
/// View Model for method response handling.
struct ResponseViewModel {
/// List of allowed response status codes
let statusCodes: [String]
/// Swift type annotation, including optionality, if applicable
let type: String
/// Identifies the correct snippet to use when rendering the view model
let strategy: String
/// The `PagingNames` struct to use when generating paged objects
let pagingNames: Language.PagingNames?
/// The type name that belongs inside the `PagedCollection` generic
let pagedElementType: String?
/// If `true` the response is nullable
let isNullable: Bool
init(from response: Response, with operation: Operation) {
let httpResponse = response.protocol.http as? HttpResponse
var statusCodes = [String]()
httpResponse?.statusCodes.forEach { statusCodes.append($0.rawValue) }
self.statusCodes = statusCodes
// check if the request body schema type is object, store the object type of the response body
let schemaResponse = response as? SchemaResponse
self.isNullable = schemaResponse?.nullable ?? false
if let pagingMetadata = operation.extensions?["x-ms-pageable"]?.value as? [String: String],
let pagingNames = Language.PagingNames(from: pagingMetadata) {
var arrayElements = (schemaResponse?.schema.properties ?? []).compactMap { $0.schema as? ArraySchema }
if arrayElements.isEmpty {
let objectElements = (schemaResponse?.schema.properties ?? []).compactMap { $0.schema as? ObjectSchema }
for object in objectElements {
let objectArrays = (object.properties ?? []).compactMap { $0.schema as? ArraySchema }
arrayElements += objectArrays
}
}
// FIXME: This assumption no longer holds for storage and should be revisited
guard arrayElements.count == 1
else { fatalError("Did not find exactly one array type for paged collection.") }
self.strategy = ResponseBodyType.pagedBody.rawValue
self.pagingNames = pagingNames
self.pagedElementType = arrayElements.first!.elementType.name
if var elementType = pagedElementType, self.pagingNames != nil {
elementType = Manager.shared.args!.generateAsInternal.aliasOrName(for: elementType)
self.type = "PagedCollection<\(elementType)>"
} else {
self.type = schemaResponse?.schema.swiftType() ?? "Void"
}
} else {
self.pagingNames = nil
self.pagedElementType = nil
if let type = schemaResponse?.schema.swiftType(),
let schema = schemaResponse?.schema {
self.strategy = ResponseBodyType.strategy(for: type, and: schema).rawValue
self.type = type
} else {
self.strategy = ResponseBodyType.noBody.rawValue
self.type = "Void"
}
}
}
}
| 40.525926 | 120 | 0.627856 |
1d57f6c5b4b4e0db82ea74c0d9911aec5afcc98d
| 82 |
import Foundation
import UIKit
extension UITableViewCell: CellIdentificable {
}
| 11.714286 | 46 | 0.829268 |
723debc091fb0dd571d5a58242340b026562f363
| 3,133 |
import Foundation
protocol KeychainAttrRepresentable {
var keychainAttrValue: CFString { get }
}
// MARK: - KeychainItemAccessibility
public enum KeychainItemAccessibility {
/**
The data in the keychain item cannot be accessed after a restart until the device has been unlocked once by the user.
After the first unlock, the data remains accessible until the next restart. This is recommended for items that need to be accessed by background applications. Items with this attribute migrate to a new device when using encrypted backups.
*/
case afterFirstUnlock
/**
The data in the keychain item cannot be accessed after a restart until the device has been unlocked once by the user.
After the first unlock, the data remains accessible until the next restart. This is recommended for items that need to be accessed by background applications. Items with this attribute do not migrate to a new device. Thus, after restoring from a backup of a different device, these items will not be present.
*/
case afterFirstUnlockThisDeviceOnly
/**
The data in the keychain item can always be accessed regardless of whether the device is locked.
This is not recommended for application use. Items with this attribute migrate to a new device when using encrypted backups.
*/
case whenPasscodeSetThisDeviceOnly
/**
The data in the keychain item can always be accessed regardless of whether the device is locked.
This is not recommended for application use. Items with this attribute do not migrate to a new device. Thus, after restoring from a backup of a different device, these items will not be present.
*/
case whenUnlocked
/**
The data in the keychain item can be accessed only while the device is unlocked by the user.
This is recommended for items that need to be accessible only while the application is in the foreground. Items with this attribute do not migrate to a new device. Thus, after restoring from a backup of a different device, these items will not be present.
*/
case whenUnlockedThisDeviceOnly
static func accessibilityForAttributeValue(_ keychainAttrValue: CFString) -> KeychainItemAccessibility? {
let firstResult = keychainItemAccessibilityLookup.enumerated().first { $0.element.value == keychainAttrValue }
return firstResult?.element.key
}
}
private let keychainItemAccessibilityLookup: [KeychainItemAccessibility: CFString] = {
var lookup: [KeychainItemAccessibility: CFString] = [
.afterFirstUnlock: kSecAttrAccessibleAfterFirstUnlock,
.afterFirstUnlockThisDeviceOnly: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly,
.whenPasscodeSetThisDeviceOnly: kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly,
.whenUnlocked: kSecAttrAccessibleWhenUnlocked,
.whenUnlockedThisDeviceOnly: kSecAttrAccessibleWhenUnlockedThisDeviceOnly
]
return lookup
}()
extension KeychainItemAccessibility: KeychainAttrRepresentable {
internal var keychainAttrValue: CFString {
keychainItemAccessibilityLookup[self]!
}
}
| 44.757143 | 313 | 0.763805 |
fc82e54946de0a8451fca2a1da37b6e0976ba4b4
| 292 |
import Foundation
// LROSADsDelete202RetryInvalidHeaderHeadersProtocol is defines headers for delete202RetryInvalidHeader operation.
public protocol LROSADsDelete202RetryInvalidHeaderHeadersProtocol : Codable {
var Location: String? { get set }
var retryAfter: Int32? { get set }
}
| 41.714286 | 114 | 0.811644 |
9092869b2003d5764da982976d41ac8353323fbf
| 729 |
// This class is automatically included in FastlaneRunner during build
// This autogenerated file will be overwritten or replaced during build time, or when you initialize `deliver`
//
// ** NOTE **
// This file is provided by fastlane and WILL be overwritten in future updates
// If you want to add extra functionality to this project, create a new file in a
// new group so that it won't be marked for upgrade
//
class Deliverfile: DeliverfileProtocol {
// If you want to enable `deliver`, run `fastlane deliver init`
// After, this file will be replaced with a custom implementation that contains values you supplied
// during the `init` process, and you won't see this message
}
// Generated with fastlane 2.103.1
| 33.136364 | 110 | 0.750343 |
d6e9a52d288d87517092a70ca40892922cf7faac
| 331 |
//
// ObservationElementPhotoCell.swift
// EAO
//
// Created by Micha Volin on 2017-05-15.
// Copyright © 2017 FreshWorks. All rights reserved.
//
final class ObservationElementPhotoCell: UICollectionViewCell{
@IBOutlet private var imageView: UIImageView!
@objc func setData(image: UIImage?){
imageView.image = image
}
}
| 22.066667 | 62 | 0.740181 |
d7375a33c5ae2085b614ce421ce21a257fbf609c
| 275 |
//
// CreateEntityContainerType.swift
// TestViper
//
// Created by Alexander Kazmin on 2/11/19.
// Copyright © 2019 Alexander Kazmin. All rights reserved.
//
import Foundation
protocol CreateEntityContainerType {
var dataService: EntityDataServiceType { get }
}
| 19.642857 | 59 | 0.734545 |
2959e51a92ffbc9bf8d967f3e7d08b085ca2a99d
| 3,297 |
//
// BluetoothManager+PeripheralConnection.swift
// SwiftBluetoothKit
//
// Created by Manish Rathi on 27/11/18.
// Copyright © 2019 Manish. All rights reserved.
//
import RxBluetoothKit
import RxSwift
import CoreBluetooth
public extension BluetoothManager {
// MARK: - Peripheral Connection & Discovering Services
// When you discover a service, first you need to establish a connection with a peripheral. Then you call
// discoverServices(:_) for that peripheral object.
public func connectAndDiscoverServices(for peripheral: PeripheralProtocol, serviceUUIDs: [String]?) {
var uuids: [CBUUID]? = nil
if let serviceUUIDs = serviceUUIDs {
uuids = serviceUUIDs.map { CBUUID(string: $0) }
}
guard let peripheral = peripheral as? Peripheral else { return }
let isConnected = peripheral.rx.isConnected
let connectedObservableCreator = { return peripheral.rx.discoverServices(uuids).asObservable() }
let connectObservableCreator = {
return peripheral.rx.establishConnection()
.do(onNext: { [weak self] _ in
self?.observeDisconnect(for: peripheral)
})
.flatMap { $0.discoverServices(uuids) }
}
let observable = isConnected ? connectedObservableCreator(): connectObservableCreator()
let disposable = observable.subscribe(onNext: { [weak self] services in
let spServices = services.map { Service($0) }
self?.discoveredServicesSubject.onNext(Result(success: spServices))
}, onError: { [weak self] error in
self?.discoveredServicesSubject.onNext(Result(failure: error))
})
if isConnected {
disposeBag.insert(disposable)
} else {
peripheralConnections[peripheral.nameOrDefaultName] = disposable
}
}
// Disposal of a given connection disposable disconnects automatically from a peripheral
// So firstly, you discconect from a perpiheral and then you remove of disconnected Peripheral
// from the Peripheral's collection.
public func disconnect(_ peripheral: PeripheralProtocol) {
guard let disposable = peripheralConnections[peripheral.nameOrDefaultName] else { return }
disposable.dispose()
peripheralConnections[peripheral.nameOrDefaultName] = nil
}
// MARK: - Internal methods
// When you observe disconnection from a peripheral, you want to be sure that you take an action on both .next and
// .error events. For instance, when your device enters BluetoothState.poweredOff, you will receive an .error event.
func observeDisconnect(for peripheral: PeripheralProtocol) {
guard let peripheral = peripheral as? Peripheral else { return }
centralManager.observeDisconnect(for: peripheral.rx).subscribe(onNext: { [unowned self] (rx, reason) in
let peripheral = Peripheral(rx)
self.disconnectionSubject.onNext(Result(success: (peripheral, reason)))
self.disconnect(peripheral)
}, onError: { [unowned self] error in
self.disconnectionSubject.onNext(Result(failure: error))
}).disposed(by: disposeBag)
}
}
| 43.381579 | 120 | 0.66788 |
3870e120a3074126c20792702b5b1e0875c352ca
| 878 |
//
// NewsArticlesTests.swift
// NewsArticlesTests
//
// Created by Anil Punjabi on 4/22/21.
//
import XCTest
class NewsArticlesTests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
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 {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() throws {
// This is an example of a performance test case.
measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.606061 | 111 | 0.661731 |
ff0f8164e5f610226d684495125d28846f8e1089
| 260 |
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct d{class n{enum B{struct d{struct d{let a{{}struct d<T where I:P{struct d<T where B:a
| 52 | 91 | 0.757692 |
201b52f2a2e9b40e13522f1648b5ffc5f1e0d376
| 110 |
//
// File.swift
// JellyfinAudioPlayer
//
// Created by Lei Nelissen on 02/11/2020.
//
import Foundation
| 12.222222 | 42 | 0.672727 |
622bd30553ba97c799544c5633dd030dcb4c2092
| 34,504 |
//===----------------------------------------------------------------------===//
//
// This source file is part of the AWSSDKSwift open source project
//
// Copyright (c) 2017-2020 the AWSSDKSwift project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of AWSSDKSwift project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/swift-aws/aws-sdk-swift/blob/master/CodeGenerator/Sources/CodeGenerator/main.swift. DO NOT EDIT.
import AWSSDKSwiftCore
import Foundation
extension CodeStarNotifications {
// MARK: Enums
public enum DetailType: String, CustomStringConvertible, Codable {
case basic = "BASIC"
case full = "FULL"
public var description: String { return self.rawValue }
}
public enum ListEventTypesFilterName: String, CustomStringConvertible, Codable {
case resourceType = "RESOURCE_TYPE"
case serviceName = "SERVICE_NAME"
public var description: String { return self.rawValue }
}
public enum ListNotificationRulesFilterName: String, CustomStringConvertible, Codable {
case eventTypeId = "EVENT_TYPE_ID"
case createdBy = "CREATED_BY"
case resource = "RESOURCE"
case targetAddress = "TARGET_ADDRESS"
public var description: String { return self.rawValue }
}
public enum ListTargetsFilterName: String, CustomStringConvertible, Codable {
case targetType = "TARGET_TYPE"
case targetAddress = "TARGET_ADDRESS"
case targetStatus = "TARGET_STATUS"
public var description: String { return self.rawValue }
}
public enum NotificationRuleStatus: String, CustomStringConvertible, Codable {
case enabled = "ENABLED"
case disabled = "DISABLED"
public var description: String { return self.rawValue }
}
public enum TargetStatus: String, CustomStringConvertible, Codable {
case pending = "PENDING"
case active = "ACTIVE"
case unreachable = "UNREACHABLE"
case inactive = "INACTIVE"
case deactivated = "DEACTIVATED"
public var description: String { return self.rawValue }
}
// MARK: Shapes
public struct CreateNotificationRuleRequest: AWSEncodableShape {
/// A unique, client-generated idempotency token that, when provided in a request, ensures the request cannot be repeated with a changed parameter. If a request with the same parameters is received and a token is included, the request returns information about the initial request that used that token. The AWS SDKs prepopulate client request tokens. If you are using an AWS SDK, an idempotency token is created for you.
public let clientRequestToken: String?
/// The level of detail to include in the notifications for this resource. BASIC will include only the contents of the event as it would appear in AWS CloudWatch. FULL will include any supplemental information provided by AWS CodeStar Notifications and/or the service for the resource for which the notification is created.
public let detailType: DetailType
/// A list of event types associated with this notification rule. For a list of allowed events, see EventTypeSummary.
public let eventTypeIds: [String]
/// The name for the notification rule. Notifictaion rule names must be unique in your AWS account.
public let name: String
/// The Amazon Resource Name (ARN) of the resource to associate with the notification rule. Supported resources include pipelines in AWS CodePipeline, repositories in AWS CodeCommit, and build projects in AWS CodeBuild.
public let resource: String
/// The status of the notification rule. The default value is ENABLED. If the status is set to DISABLED, notifications aren't sent for the notification rule.
public let status: NotificationRuleStatus?
/// A list of tags to apply to this notification rule. Key names cannot start with "aws".
public let tags: [String: String]?
/// A list of Amazon Resource Names (ARNs) of SNS topics to associate with the notification rule.
public let targets: [Target]
public init(clientRequestToken: String? = CreateNotificationRuleRequest.idempotencyToken(), detailType: DetailType, eventTypeIds: [String], name: String, resource: String, status: NotificationRuleStatus? = nil, tags: [String: String]? = nil, targets: [Target]) {
self.clientRequestToken = clientRequestToken
self.detailType = detailType
self.eventTypeIds = eventTypeIds
self.name = name
self.resource = resource
self.status = status
self.tags = tags
self.targets = targets
}
public func validate(name: String) throws {
try validate(self.clientRequestToken, name: "clientRequestToken", parent: name, max: 256)
try validate(self.clientRequestToken, name: "clientRequestToken", parent: name, min: 1)
try validate(self.clientRequestToken, name: "clientRequestToken", parent: name, pattern: "^[\\w:/-]+$")
try self.eventTypeIds.forEach {
try validate($0, name: "eventTypeIds[]", parent: name, max: 200)
try validate($0, name: "eventTypeIds[]", parent: name, min: 1)
}
try validate(self.name, name: "name", parent: name, max: 64)
try validate(self.name, name: "name", parent: name, min: 1)
try validate(self.name, name: "name", parent: name, pattern: "[A-Za-z0-9\\-_ ]+$")
try validate(self.resource, name: "resource", parent: name, pattern: "^arn:aws[^:\\s]*:[^:\\s]*:[^:\\s]*:[0-9]{12}:[^\\s]+$")
try self.tags?.forEach {
try validate($0.key, name: "tags.key", parent: name, max: 128)
try validate($0.key, name: "tags.key", parent: name, min: 1)
try validate($0.key, name: "tags.key", parent: name, pattern: "^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*)$")
try validate($0.value, name: "tags[\"\($0.key)\"]", parent: name, max: 256)
try validate($0.value, name: "tags[\"\($0.key)\"]", parent: name, pattern: "^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*)$")
}
try self.targets.forEach {
try $0.validate(name: "\(name).targets[]")
}
try validate(self.targets, name: "targets", parent: name, max: 10)
}
private enum CodingKeys: String, CodingKey {
case clientRequestToken = "ClientRequestToken"
case detailType = "DetailType"
case eventTypeIds = "EventTypeIds"
case name = "Name"
case resource = "Resource"
case status = "Status"
case tags = "Tags"
case targets = "Targets"
}
}
public struct CreateNotificationRuleResult: AWSDecodableShape {
/// The Amazon Resource Name (ARN) of the notification rule.
public let arn: String?
public init(arn: String? = nil) {
self.arn = arn
}
private enum CodingKeys: String, CodingKey {
case arn = "Arn"
}
}
public struct DeleteNotificationRuleRequest: AWSEncodableShape {
/// The Amazon Resource Name (ARN) of the notification rule you want to delete.
public let arn: String
public init(arn: String) {
self.arn = arn
}
public func validate(name: String) throws {
try validate(self.arn, name: "arn", parent: name, pattern: "^arn:aws[^:\\s]*:codestar-notifications:[^:\\s]+:\\d{12}:notificationrule\\/(.*\\S)?$")
}
private enum CodingKeys: String, CodingKey {
case arn = "Arn"
}
}
public struct DeleteNotificationRuleResult: AWSDecodableShape {
/// The Amazon Resource Name (ARN) of the deleted notification rule.
public let arn: String?
public init(arn: String? = nil) {
self.arn = arn
}
private enum CodingKeys: String, CodingKey {
case arn = "Arn"
}
}
public struct DeleteTargetRequest: AWSEncodableShape {
/// A Boolean value that can be used to delete all associations with this SNS topic. The default value is FALSE. If set to TRUE, all associations between that target and every notification rule in your AWS account are deleted.
public let forceUnsubscribeAll: Bool?
/// The Amazon Resource Name (ARN) of the SNS topic to delete.
public let targetAddress: String
public init(forceUnsubscribeAll: Bool? = nil, targetAddress: String) {
self.forceUnsubscribeAll = forceUnsubscribeAll
self.targetAddress = targetAddress
}
public func validate(name: String) throws {
try validate(self.targetAddress, name: "targetAddress", parent: name, max: 320)
try validate(self.targetAddress, name: "targetAddress", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case forceUnsubscribeAll = "ForceUnsubscribeAll"
case targetAddress = "TargetAddress"
}
}
public struct DeleteTargetResult: AWSDecodableShape {
public init() {
}
}
public struct DescribeNotificationRuleRequest: AWSEncodableShape {
/// The Amazon Resource Name (ARN) of the notification rule.
public let arn: String
public init(arn: String) {
self.arn = arn
}
public func validate(name: String) throws {
try validate(self.arn, name: "arn", parent: name, pattern: "^arn:aws[^:\\s]*:codestar-notifications:[^:\\s]+:\\d{12}:notificationrule\\/(.*\\S)?$")
}
private enum CodingKeys: String, CodingKey {
case arn = "Arn"
}
}
public struct DescribeNotificationRuleResult: AWSDecodableShape {
/// The Amazon Resource Name (ARN) of the notification rule.
public let arn: String
/// The name or email alias of the person who created the notification rule.
public let createdBy: String?
/// The date and time the notification rule was created, in timestamp format.
public let createdTimestamp: TimeStamp?
/// The level of detail included in the notifications for this resource. BASIC will include only the contents of the event as it would appear in AWS CloudWatch. FULL will include any supplemental information provided by AWS CodeStar Notifications and/or the service for the resource for which the notification is created.
public let detailType: DetailType?
/// A list of the event types associated with the notification rule.
public let eventTypes: [EventTypeSummary]?
/// The date and time the notification rule was most recently updated, in timestamp format.
public let lastModifiedTimestamp: TimeStamp?
/// The name of the notification rule.
public let name: String?
/// The Amazon Resource Name (ARN) of the resource associated with the notification rule.
public let resource: String?
/// The status of the notification rule. Valid statuses are on (sending notifications) or off (not sending notifications).
public let status: NotificationRuleStatus?
/// The tags associated with the notification rule.
public let tags: [String: String]?
/// A list of the SNS topics associated with the notification rule.
public let targets: [TargetSummary]?
public init(arn: String, createdBy: String? = nil, createdTimestamp: TimeStamp? = nil, detailType: DetailType? = nil, eventTypes: [EventTypeSummary]? = nil, lastModifiedTimestamp: TimeStamp? = nil, name: String? = nil, resource: String? = nil, status: NotificationRuleStatus? = nil, tags: [String: String]? = nil, targets: [TargetSummary]? = nil) {
self.arn = arn
self.createdBy = createdBy
self.createdTimestamp = createdTimestamp
self.detailType = detailType
self.eventTypes = eventTypes
self.lastModifiedTimestamp = lastModifiedTimestamp
self.name = name
self.resource = resource
self.status = status
self.tags = tags
self.targets = targets
}
private enum CodingKeys: String, CodingKey {
case arn = "Arn"
case createdBy = "CreatedBy"
case createdTimestamp = "CreatedTimestamp"
case detailType = "DetailType"
case eventTypes = "EventTypes"
case lastModifiedTimestamp = "LastModifiedTimestamp"
case name = "Name"
case resource = "Resource"
case status = "Status"
case tags = "Tags"
case targets = "Targets"
}
}
public struct EventTypeSummary: AWSDecodableShape {
/// The system-generated ID of the event.
public let eventTypeId: String?
/// The name of the event.
public let eventTypeName: String?
/// The resource type of the event.
public let resourceType: String?
/// The name of the service for which the event applies.
public let serviceName: String?
public init(eventTypeId: String? = nil, eventTypeName: String? = nil, resourceType: String? = nil, serviceName: String? = nil) {
self.eventTypeId = eventTypeId
self.eventTypeName = eventTypeName
self.resourceType = resourceType
self.serviceName = serviceName
}
private enum CodingKeys: String, CodingKey {
case eventTypeId = "EventTypeId"
case eventTypeName = "EventTypeName"
case resourceType = "ResourceType"
case serviceName = "ServiceName"
}
}
public struct ListEventTypesFilter: AWSEncodableShape {
/// The system-generated name of the filter type you want to filter by.
public let name: ListEventTypesFilterName
/// The name of the resource type (for example, pipeline) or service name (for example, CodePipeline) that you want to filter by.
public let value: String
public init(name: ListEventTypesFilterName, value: String) {
self.name = name
self.value = value
}
private enum CodingKeys: String, CodingKey {
case name = "Name"
case value = "Value"
}
}
public struct ListEventTypesRequest: AWSEncodableShape {
/// The filters to use to return information by service or resource type.
public let filters: [ListEventTypesFilter]?
/// A non-negative integer used to limit the number of returned results. The default number is 50. The maximum number of results that can be returned is 100.
public let maxResults: Int?
/// An enumeration token that, when provided in a request, returns the next batch of the results.
public let nextToken: String?
public init(filters: [ListEventTypesFilter]? = nil, maxResults: Int? = nil, nextToken: String? = nil) {
self.filters = filters
self.maxResults = maxResults
self.nextToken = nextToken
}
public func validate(name: String) throws {
try validate(self.maxResults, name: "maxResults", parent: name, max: 100)
try validate(self.maxResults, name: "maxResults", parent: name, min: 1)
try validate(self.nextToken, name: "nextToken", parent: name, pattern: "^[\\w/+=]+$")
}
private enum CodingKeys: String, CodingKey {
case filters = "Filters"
case maxResults = "MaxResults"
case nextToken = "NextToken"
}
}
public struct ListEventTypesResult: AWSDecodableShape {
/// Information about each event, including service name, resource type, event ID, and event name.
public let eventTypes: [EventTypeSummary]?
/// An enumeration token that can be used in a request to return the next batch of the results.
public let nextToken: String?
public init(eventTypes: [EventTypeSummary]? = nil, nextToken: String? = nil) {
self.eventTypes = eventTypes
self.nextToken = nextToken
}
private enum CodingKeys: String, CodingKey {
case eventTypes = "EventTypes"
case nextToken = "NextToken"
}
}
public struct ListNotificationRulesFilter: AWSEncodableShape {
/// The name of the attribute you want to use to filter the returned notification rules.
public let name: ListNotificationRulesFilterName
/// The value of the attribute you want to use to filter the returned notification rules. For example, if you specify filtering by RESOURCE in Name, you might specify the ARN of a pipeline in AWS CodePipeline for the value.
public let value: String
public init(name: ListNotificationRulesFilterName, value: String) {
self.name = name
self.value = value
}
private enum CodingKeys: String, CodingKey {
case name = "Name"
case value = "Value"
}
}
public struct ListNotificationRulesRequest: AWSEncodableShape {
/// The filters to use to return information by service or resource type. For valid values, see ListNotificationRulesFilter. A filter with the same name can appear more than once when used with OR statements. Filters with different names should be applied with AND statements.
public let filters: [ListNotificationRulesFilter]?
/// A non-negative integer used to limit the number of returned results. The maximum number of results that can be returned is 100.
public let maxResults: Int?
/// An enumeration token that, when provided in a request, returns the next batch of the results.
public let nextToken: String?
public init(filters: [ListNotificationRulesFilter]? = nil, maxResults: Int? = nil, nextToken: String? = nil) {
self.filters = filters
self.maxResults = maxResults
self.nextToken = nextToken
}
public func validate(name: String) throws {
try validate(self.maxResults, name: "maxResults", parent: name, max: 100)
try validate(self.maxResults, name: "maxResults", parent: name, min: 1)
try validate(self.nextToken, name: "nextToken", parent: name, pattern: "^[\\w/+=]+$")
}
private enum CodingKeys: String, CodingKey {
case filters = "Filters"
case maxResults = "MaxResults"
case nextToken = "NextToken"
}
}
public struct ListNotificationRulesResult: AWSDecodableShape {
/// An enumeration token that can be used in a request to return the next batch of the results.
public let nextToken: String?
/// The list of notification rules for the AWS account, by Amazon Resource Name (ARN) and ID.
public let notificationRules: [NotificationRuleSummary]?
public init(nextToken: String? = nil, notificationRules: [NotificationRuleSummary]? = nil) {
self.nextToken = nextToken
self.notificationRules = notificationRules
}
private enum CodingKeys: String, CodingKey {
case nextToken = "NextToken"
case notificationRules = "NotificationRules"
}
}
public struct ListTagsForResourceRequest: AWSEncodableShape {
/// The Amazon Resource Name (ARN) for the notification rule.
public let arn: String
public init(arn: String) {
self.arn = arn
}
public func validate(name: String) throws {
try validate(self.arn, name: "arn", parent: name, pattern: "^arn:aws[^:\\s]*:codestar-notifications:[^:\\s]+:\\d{12}:notificationrule\\/(.*\\S)?$")
}
private enum CodingKeys: String, CodingKey {
case arn = "Arn"
}
}
public struct ListTagsForResourceResult: AWSDecodableShape {
/// The tags associated with the notification rule.
public let tags: [String: String]?
public init(tags: [String: String]? = nil) {
self.tags = tags
}
private enum CodingKeys: String, CodingKey {
case tags = "Tags"
}
}
public struct ListTargetsFilter: AWSEncodableShape {
/// The name of the attribute you want to use to filter the returned targets.
public let name: ListTargetsFilterName
/// The value of the attribute you want to use to filter the returned targets. For example, if you specify SNS for the Target type, you could specify an Amazon Resource Name (ARN) for a topic as the value.
public let value: String
public init(name: ListTargetsFilterName, value: String) {
self.name = name
self.value = value
}
private enum CodingKeys: String, CodingKey {
case name = "Name"
case value = "Value"
}
}
public struct ListTargetsRequest: AWSEncodableShape {
/// The filters to use to return information by service or resource type. Valid filters include target type, target address, and target status. A filter with the same name can appear more than once when used with OR statements. Filters with different names should be applied with AND statements.
public let filters: [ListTargetsFilter]?
/// A non-negative integer used to limit the number of returned results. The maximum number of results that can be returned is 100.
public let maxResults: Int?
/// An enumeration token that, when provided in a request, returns the next batch of the results.
public let nextToken: String?
public init(filters: [ListTargetsFilter]? = nil, maxResults: Int? = nil, nextToken: String? = nil) {
self.filters = filters
self.maxResults = maxResults
self.nextToken = nextToken
}
public func validate(name: String) throws {
try validate(self.maxResults, name: "maxResults", parent: name, max: 100)
try validate(self.maxResults, name: "maxResults", parent: name, min: 1)
try validate(self.nextToken, name: "nextToken", parent: name, pattern: "^[\\w/+=]+$")
}
private enum CodingKeys: String, CodingKey {
case filters = "Filters"
case maxResults = "MaxResults"
case nextToken = "NextToken"
}
}
public struct ListTargetsResult: AWSDecodableShape {
/// An enumeration token that can be used in a request to return the next batch of results.
public let nextToken: String?
/// The list of notification rule targets.
public let targets: [TargetSummary]?
public init(nextToken: String? = nil, targets: [TargetSummary]? = nil) {
self.nextToken = nextToken
self.targets = targets
}
private enum CodingKeys: String, CodingKey {
case nextToken = "NextToken"
case targets = "Targets"
}
}
public struct NotificationRuleSummary: AWSDecodableShape {
/// The Amazon Resource Name (ARN) of the notification rule.
public let arn: String?
/// The unique ID of the notification rule.
public let id: String?
public init(arn: String? = nil, id: String? = nil) {
self.arn = arn
self.id = id
}
private enum CodingKeys: String, CodingKey {
case arn = "Arn"
case id = "Id"
}
}
public struct SubscribeRequest: AWSEncodableShape {
/// The Amazon Resource Name (ARN) of the notification rule for which you want to create the association.
public let arn: String
/// An enumeration token that, when provided in a request, returns the next batch of the results.
public let clientRequestToken: String?
public let target: Target
public init(arn: String, clientRequestToken: String? = nil, target: Target) {
self.arn = arn
self.clientRequestToken = clientRequestToken
self.target = target
}
public func validate(name: String) throws {
try validate(self.arn, name: "arn", parent: name, pattern: "^arn:aws[^:\\s]*:codestar-notifications:[^:\\s]+:\\d{12}:notificationrule\\/(.*\\S)?$")
try validate(self.clientRequestToken, name: "clientRequestToken", parent: name, max: 256)
try validate(self.clientRequestToken, name: "clientRequestToken", parent: name, min: 1)
try validate(self.clientRequestToken, name: "clientRequestToken", parent: name, pattern: "^[\\w:/-]+$")
try self.target.validate(name: "\(name).target")
}
private enum CodingKeys: String, CodingKey {
case arn = "Arn"
case clientRequestToken = "ClientRequestToken"
case target = "Target"
}
}
public struct SubscribeResult: AWSDecodableShape {
/// The Amazon Resource Name (ARN) of the notification rule for which you have created assocations.
public let arn: String?
public init(arn: String? = nil) {
self.arn = arn
}
private enum CodingKeys: String, CodingKey {
case arn = "Arn"
}
}
public struct TagResourceRequest: AWSEncodableShape {
/// The Amazon Resource Name (ARN) of the notification rule to tag.
public let arn: String
/// The list of tags to associate with the resource. Tag key names cannot start with "aws".
public let tags: [String: String]
public init(arn: String, tags: [String: String]) {
self.arn = arn
self.tags = tags
}
public func validate(name: String) throws {
try validate(self.arn, name: "arn", parent: name, pattern: "^arn:aws[^:\\s]*:codestar-notifications:[^:\\s]+:\\d{12}:notificationrule\\/(.*\\S)?$")
try self.tags.forEach {
try validate($0.key, name: "tags.key", parent: name, max: 128)
try validate($0.key, name: "tags.key", parent: name, min: 1)
try validate($0.key, name: "tags.key", parent: name, pattern: "^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*)$")
try validate($0.value, name: "tags[\"\($0.key)\"]", parent: name, max: 256)
try validate($0.value, name: "tags[\"\($0.key)\"]", parent: name, pattern: "^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*)$")
}
}
private enum CodingKeys: String, CodingKey {
case arn = "Arn"
case tags = "Tags"
}
}
public struct TagResourceResult: AWSDecodableShape {
/// The list of tags associated with the resource.
public let tags: [String: String]?
public init(tags: [String: String]? = nil) {
self.tags = tags
}
private enum CodingKeys: String, CodingKey {
case tags = "Tags"
}
}
public struct Target: AWSEncodableShape {
/// The Amazon Resource Name (ARN) of the SNS topic.
public let targetAddress: String?
/// The target type. Can be an Amazon SNS topic.
public let targetType: String?
public init(targetAddress: String? = nil, targetType: String? = nil) {
self.targetAddress = targetAddress
self.targetType = targetType
}
public func validate(name: String) throws {
try validate(self.targetAddress, name: "targetAddress", parent: name, max: 320)
try validate(self.targetAddress, name: "targetAddress", parent: name, min: 1)
try validate(self.targetType, name: "targetType", parent: name, pattern: "^[A-Za-z]+$")
}
private enum CodingKeys: String, CodingKey {
case targetAddress = "TargetAddress"
case targetType = "TargetType"
}
}
public struct TargetSummary: AWSDecodableShape {
/// The Amazon Resource Name (ARN) of the SNS topic.
public let targetAddress: String?
/// The status of the target.
public let targetStatus: TargetStatus?
/// The type of the target (for example, SNS).
public let targetType: String?
public init(targetAddress: String? = nil, targetStatus: TargetStatus? = nil, targetType: String? = nil) {
self.targetAddress = targetAddress
self.targetStatus = targetStatus
self.targetType = targetType
}
private enum CodingKeys: String, CodingKey {
case targetAddress = "TargetAddress"
case targetStatus = "TargetStatus"
case targetType = "TargetType"
}
}
public struct UnsubscribeRequest: AWSEncodableShape {
/// The Amazon Resource Name (ARN) of the notification rule.
public let arn: String
/// The ARN of the SNS topic to unsubscribe from the notification rule.
public let targetAddress: String
public init(arn: String, targetAddress: String) {
self.arn = arn
self.targetAddress = targetAddress
}
public func validate(name: String) throws {
try validate(self.arn, name: "arn", parent: name, pattern: "^arn:aws[^:\\s]*:codestar-notifications:[^:\\s]+:\\d{12}:notificationrule\\/(.*\\S)?$")
try validate(self.targetAddress, name: "targetAddress", parent: name, max: 320)
try validate(self.targetAddress, name: "targetAddress", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case arn = "Arn"
case targetAddress = "TargetAddress"
}
}
public struct UnsubscribeResult: AWSDecodableShape {
/// The Amazon Resource Name (ARN) of the the notification rule from which you have removed a subscription.
public let arn: String
public init(arn: String) {
self.arn = arn
}
private enum CodingKeys: String, CodingKey {
case arn = "Arn"
}
}
public struct UntagResourceRequest: AWSEncodableShape {
/// The Amazon Resource Name (ARN) of the notification rule from which to remove the tags.
public let arn: String
/// The key names of the tags to remove.
public let tagKeys: [String]
public init(arn: String, tagKeys: [String]) {
self.arn = arn
self.tagKeys = tagKeys
}
public func validate(name: String) throws {
try validate(self.arn, name: "arn", parent: name, pattern: "^arn:aws[^:\\s]*:codestar-notifications:[^:\\s]+:\\d{12}:notificationrule\\/(.*\\S)?$")
try self.tagKeys.forEach {
try validate($0, name: "tagKeys[]", parent: name, max: 128)
try validate($0, name: "tagKeys[]", parent: name, min: 1)
try validate($0, name: "tagKeys[]", parent: name, pattern: "^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]*)$")
}
}
private enum CodingKeys: String, CodingKey {
case arn = "Arn"
case tagKeys = "TagKeys"
}
}
public struct UntagResourceResult: AWSDecodableShape {
public init() {
}
}
public struct UpdateNotificationRuleRequest: AWSEncodableShape {
/// The Amazon Resource Name (ARN) of the notification rule.
public let arn: String
/// The level of detail to include in the notifications for this resource. BASIC will include only the contents of the event as it would appear in AWS CloudWatch. FULL will include any supplemental information provided by AWS CodeStar Notifications and/or the service for the resource for which the notification is created.
public let detailType: DetailType?
/// A list of event types associated with this notification rule.
public let eventTypeIds: [String]?
/// The name of the notification rule.
public let name: String?
/// The status of the notification rule. Valid statuses include enabled (sending notifications) or disabled (not sending notifications).
public let status: NotificationRuleStatus?
/// The address and type of the targets to receive notifications from this notification rule.
public let targets: [Target]?
public init(arn: String, detailType: DetailType? = nil, eventTypeIds: [String]? = nil, name: String? = nil, status: NotificationRuleStatus? = nil, targets: [Target]? = nil) {
self.arn = arn
self.detailType = detailType
self.eventTypeIds = eventTypeIds
self.name = name
self.status = status
self.targets = targets
}
public func validate(name: String) throws {
try validate(self.arn, name: "arn", parent: name, pattern: "^arn:aws[^:\\s]*:codestar-notifications:[^:\\s]+:\\d{12}:notificationrule\\/(.*\\S)?$")
try self.eventTypeIds?.forEach {
try validate($0, name: "eventTypeIds[]", parent: name, max: 200)
try validate($0, name: "eventTypeIds[]", parent: name, min: 1)
}
try validate(self.name, name: "name", parent: name, max: 64)
try validate(self.name, name: "name", parent: name, min: 1)
try validate(self.name, name: "name", parent: name, pattern: "[A-Za-z0-9\\-_ ]+$")
try self.targets?.forEach {
try $0.validate(name: "\(name).targets[]")
}
try validate(self.targets, name: "targets", parent: name, max: 10)
}
private enum CodingKeys: String, CodingKey {
case arn = "Arn"
case detailType = "DetailType"
case eventTypeIds = "EventTypeIds"
case name = "Name"
case status = "Status"
case targets = "Targets"
}
}
public struct UpdateNotificationRuleResult: AWSDecodableShape {
public init() {
}
}
}
| 42.440344 | 430 | 0.619725 |
9bf83293104b9643d7d8c90caf80e8fabe92d92c
| 9,892 |
//
// CreateMenuItemView.swift
// CreateMenuItemView
//
// Created by Jordain on 16/08/2021.
//
import SwiftUI
struct CreateMenuItemView: View {
@Binding var menuItem : menuItem
@State private var favoriteColor = 0
@State var showCustomizations = false
@Binding var menuItems : [menuItem]
@State var newMenuItems : [menuItem] = []
var body: some View {
List {
StrechyImageHeader() .listRowInsets(EdgeInsets())
Section(header:Text("Would you like to customize?")){
Picker(selection: $menuItem.type, label: Text("")) {
ForEach(menuItemType.allCases, id: \.rawValue) { value in
Text(value.localizedName)
.tag(value)
}
}
.pickerStyle(SegmentedPickerStyle())
.padding()
.onChange(of: menuItem.type, perform: { (value) in
withAnimation {
menuItem.type = value
showCustomizations = value == .custom ? true : false
}
})
.onAppear{
showCustomizations = menuItem.type == .custom ? true : false
}
}
if showCustomizations {
Section(header:Text("Customize to your liking")){
ForEach(menuItem.options.indexed(), id: \.1.id) { index, option in
Toggle( isOn: $menuItem.options[index].enabled.didSet { (state) in
menuItem.options[index].enabled = state
print( menuItem.options[index].enabled)
}) {
HStack{
Text("\(option.name)").font(.body)
Text("(+\(option.price))").font(.footnote).foregroundColor(.secondary)
}
}.toggleStyle(SwitchToggleStyle(tint: Color.red))
}}
Section(header:Text("Would you like to add something more?")){
ForEach(menuItem.extras.indexed(), id: \.1.id) { index, extra in
Toggle( isOn: $menuItem.extras[index].enabled.didSet { (state) in
menuItem.extras[index].enabled = state
print( menuItem.extras[index].enabled)
}) {
HStack{
Text("\(extra.name)").font(.body)
Text("(+\(extra.price))").font(.footnote).foregroundColor(.secondary)
}
}
.toggleStyle(SwitchToggleStyle(tint: Color.red))
}
}
}
Section(header:Text("Summary")){
HStack(alignment: .center) {
VStack(alignment: .leading) {
HStack {
Text(menuItem.name)
Spacer()
Text("\(String(format: "%.2f", menuItem.price))")
}
.padding(.bottom,10)
ForEach(menuItem.options.filter{ $0.enabled == true}, id: \.self) { option in
HStack {
Text(option.name)
.font(.caption)
.foregroundColor(.secondary)
Spacer()
Text("\(option.price)")
.font(.caption)
.foregroundColor(.secondary)
}
}
ForEach(menuItem.extras.filter{ $0.enabled == true}, id: \.self) { extra in
HStack {
Text(extra.name)
.font(.caption)
.foregroundColor(.secondary)
Spacer()
Text("\(extra.price)")
.font(.caption)
.foregroundColor(.secondary)
}
}
Divider()
.padding(.top,10)
Stepper(value: $menuItem.quantity, in: 1...1000) {
Text("Quantity \(menuItem.quantity)")
}.padding(.vertical,10)
Divider()
HStack{
Text("Total")
Spacer()
Text(calculateTotal(menuItem: menuItem))
}.padding(.vertical,10)
}
.padding()
Spacer()
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
.toolbar {
ToolbarItem(placement: .principal) {
VStack {
Text(menuItem.name).font(.headline).fontWeight(.bold).foregroundColor(Color.black).lineLimit(2)
.fixedSize(horizontal: false, vertical: true)
}
}
}
.navigationBarTitleDisplayMode(.inline)
//.listStyle(PlainListStyle())
}
func calculateTotal(menuItem : menuItem) -> String {
return "$300"
}
}
struct CreateMenuItemView_Previews: PreviewProvider {
static var previews: some View {
NavigationView{
CreateMenuItemView(menuItem: .constant(menuItem.default), menuItems: .constant(menuItem.all))
}
}
}
struct IndexedCollection<Base: RandomAccessCollection>: RandomAccessCollection {
typealias Index = Base.Index
typealias Element = (index: Index, element: Base.Element)
let base: Base
var startIndex: Index { base.startIndex }
var endIndex: Index { base.endIndex }
func index(after i: Index) -> Index {
base.index(after: i)
}
func index(before i: Index) -> Index {
base.index(before: i)
}
func index(_ i: Index, offsetBy distance: Int) -> Index {
base.index(i, offsetBy: distance)
}
subscript(position: Index) -> Element {
(index: position, element: base[position])
}
}
extension RandomAccessCollection {
func indexed() -> IndexedCollection<Self> {
IndexedCollection(base: self)
}
}
extension Binding {
func didSet(execute: @escaping (Value) -> Void) -> Binding {
return Binding(
get: { self.wrappedValue },
set: {
self.wrappedValue = $0
execute($0)
}
)
}
}
struct StrechyImageHeader : View{
let screen = UIScreen.main.bounds
private func getScrollOffset(_ geometry: GeometryProxy) -> CGFloat {
geometry.frame(in: .global).minY
}
// 2
private func getOffsetForHeaderImage(_ geometry: GeometryProxy) -> CGFloat {
let offset = getScrollOffset(geometry)
// Image was pulled down
if offset > 0 {
return -offset
}
return 0
}
func getHeightForHeaderImage(_ geometry: GeometryProxy) -> CGFloat {
let offset = getScrollOffset(geometry)
let imageHeight = geometry.size.height
if offset > 0 {
return imageHeight + offset
}
return imageHeight
}
var body : some View{
VStack(alignment:.center){
ZStack{
GeometryReader { geometry in
Image("waffels")
.resizable()
.background(Color("grouped"))
.scaledToFill()
.overlay(TintOverlay().opacity(0.3))
.frame(width: geometry.size.width, height: self.getHeightForHeaderImage(geometry))
.clipped()
.offset(x: 0, y: self.getOffsetForHeaderImage(geometry))
}
.edgesIgnoringSafeArea(/*@START_MENU_TOKEN@*/.all/*@END_MENU_TOKEN@*/)
.frame(height:screen.height/3.5 , alignment: .topLeading)
.shadow(color: Color.primary.opacity(0.2), radius: 20, x: 0, y: 10)
}
}
.edgesIgnoringSafeArea(.top)
}
}
struct TintOverlay: View {
var body: some View {
ZStack {
Text(" ")
}
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
.background(Color.black)
}
}
| 34.347222 | 119 | 0.410433 |
2f91ecbb81c6d57a10876023ceee5342505868e9
| 2,939 |
// Automatically generated by the Fast Binary Encoding compiler, do not modify!
// https://github.com/chronoxor/FastBinaryEncoding
// Source: test.fbe
// Version: 1.8.0.0
import Foundation
import ChronoxorFbe
import ChronoxorProto
// Fast Binary Encoding Data array field model
class FieldModelArrayData: FieldModel {
private let _model: ChronoxorFbe.FieldModelData
var _buffer: Buffer
var _offset: Int
var size: Int
// Field size
var fbeSize: Int {
return size * _model.fbeSize
}
// Field extra size
var fbeExtra: Int = 0
// Get the vector offset
var offset: Int = 0
required init() {
let buffer = Buffer()
let offset = 0
_buffer = buffer
_offset = offset
self.size = 0
_model = ChronoxorFbe.FieldModelData(buffer: buffer, offset: offset)
}
required init(buffer: Buffer, offset: Int, size: Int) {
_buffer = buffer
_offset = offset
self.size = size
_model = ChronoxorFbe.FieldModelData(buffer: buffer, offset: offset)
}
// Vector index operator
public func getItem(index: Int) -> ChronoxorFbe.FieldModelData {
assert(_buffer.offset + fbeOffset + fbeSize <= _buffer.size, "Model is broken!")
assert(index < size, "Model is broken!")
_model.fbeOffset = fbeOffset
_model.fbeShift(size: index * _model.fbeSize)
return _model
}
public func verify() -> Bool {
if _buffer.offset + fbeOffset + fbeSize > _buffer.size {
return false
}
_model.fbeOffset = fbeOffset
var i = size
while i > 0 {
if !_model.verify() { return false }
_model.fbeShift(size: _model.fbeSize)
i -= 1
}
return true
}
public func get() -> Array<Data> {
var values = Array<Data>()
let fbeModel = getItem(index: 0)
for _ in 0..<size {
values.append(fbeModel.get())
fbeModel.fbeShift(size: fbeModel.fbeSize)
}
return values
}
public func get(values: inout Array<Data>) {
values.removeAll()
let fbeVectorSize = size
if fbeVectorSize == 0 {
return
}
values.reserveCapacity(fbeVectorSize)
let fbeModel = getItem(index: 0)
var i = size
while i > 0 {
let value = fbeModel.get()
values.append(value)
fbeModel.fbeShift(size: fbeModel.fbeSize)
i -= 1
}
}
public func set(value values: Array<Data>) throws {
if _buffer.offset + fbeOffset + fbeSize > _buffer.size {
assertionFailure("Model is broken!")
return
}
let fbeModel = getItem(index: 0)
for value in values {
try fbeModel.set(value: value)
fbeModel.fbeShift(size: fbeModel.fbeSize)
}
}
}
| 24.90678 | 88 | 0.58081 |
5da9ff4e781d78e3425432fcc648f557fc727003
| 4,919 |
// RUN: %target-swift-frontend -emit-silgen %s | FileCheck %s
struct Int {
mutating func foo() {}
}
struct Foo<T, U> {
var f: (T) -> U
var g: T
}
// CHECK-LABEL: sil hidden @_TF20property_abstraction4getF
// CHECK: bb0([[X_ORIG:%.*]] : $Foo<Int, Int>):
// CHECK: [[F_ORIG:%.*]] = struct_extract [[X_ORIG]] : $Foo<Int, Int>, #Foo.f
// CHECK: strong_retain [[F_ORIG]]
// CHECK: [[REABSTRACT_FN:%.*]] = function_ref @_TTR
// CHECK: [[F_SUBST:%.*]] = partial_apply [[REABSTRACT_FN]]([[F_ORIG]])
// CHECK: return [[F_SUBST]]
func getF(_ x: Foo<Int, Int>) -> (Int) -> Int {
return x.f
}
// CHECK-LABEL: sil hidden @_TF20property_abstraction4setF
// CHECK: [[REABSTRACT_FN:%.*]] = function_ref @_TTR
// CHECK: [[F_ORIG:%.*]] = partial_apply [[REABSTRACT_FN]]({{%.*}})
// CHECK: [[F_ADDR:%.*]] = struct_element_addr {{%.*}} : $*Foo<Int, Int>, #Foo.f
// CHECK: assign [[F_ORIG]] to [[F_ADDR]]
func setF(_ x: inout Foo<Int, Int>, f: (Int) -> Int) {
x.f = f
}
func inOutFunc(_ f: inout ((Int) -> Int)) { }
// CHECK-LABEL: sil hidden @_TF20property_abstraction6inOutF
// CHECK: [[INOUTFUNC:%.*]] = function_ref @_TF20property_abstraction9inOutFunc
// CHECK: [[F_ADDR:%.*]] = struct_element_addr {{%.*}} : $*Foo<Int, Int>, #Foo.f
// CHECK: [[F_SUBST_MAT:%.*]] = alloc_stack
// CHECK: [[F_ORIG:%.*]] = load [[F_ADDR]]
// CHECK: [[REABSTRACT_FN:%.*]] = function_ref @_TTR
// CHECK: [[F_SUBST_IN:%.*]] = partial_apply [[REABSTRACT_FN]]([[F_ORIG]])
// CHECK: store [[F_SUBST_IN]] to [[F_SUBST_MAT]]
// CHECK: apply [[INOUTFUNC]]([[F_SUBST_MAT]])
// CHECK: [[F_SUBST_OUT:%.*]] = load [[F_SUBST_MAT]]
// CHECK: [[REABSTRACT_FN:%.*]] = function_ref @_TTR
// CHECK: [[F_ORIG:%.*]] = partial_apply [[REABSTRACT_FN]]([[F_SUBST_OUT]])
// CHECK: assign [[F_ORIG]] to [[F_ADDR]]
func inOutF(_ x: Foo<Int, Int>) {
var x = x
inOutFunc(&x.f)
}
// Don't produce a writeback for generic lvalues when there's no real
// abstraction difference. <rdar://problem/16530674>
// CHECK-LABEL: sil hidden @_TF20property_abstraction23noAbstractionDifference
func noAbstractionDifference(_ x: Foo<Int, Int>) {
var x = x
// CHECK: [[ADDR:%.*]] = struct_element_addr {{%.*}}, #Foo.g
// CHECK: apply {{%.*}}([[ADDR]])
x.g.foo()
}
protocol P {}
struct AddressOnlyLet<T> {
let f: (T) -> T
let makeAddressOnly: P
}
// CHECK-LABEL: sil hidden @_TF20property_abstraction34getAddressOnlyReabstractedProperty{{.*}} : $@convention(thin) (@in AddressOnlyLet<Int>) -> @owned @callee_owned (Int) -> Int
// CHECK: [[CLOSURE_ADDR:%.*]] = struct_element_addr {{%.*}} : $*AddressOnlyLet<Int>, #AddressOnlyLet.f
// CHECK: [[CLOSURE_ORIG:%.*]] = load [[CLOSURE_ADDR]]
// CHECK: [[REABSTRACT:%.*]] = function_ref
// CHECK: [[CLOSURE_SUBST:%.*]] = partial_apply [[REABSTRACT]]([[CLOSURE_ORIG]])
// CHECK: return [[CLOSURE_SUBST]]
func getAddressOnlyReabstractedProperty(_ x: AddressOnlyLet<Int>) -> (Int) -> Int {
return x.f
}
enum Bar<T, U> {
case F((T) -> U)
}
func getF(_ x: Bar<Int, Int>) -> (Int) -> Int {
switch x {
case .F(var f):
return f
}
}
func makeF(_ f: (Int) -> Int) -> Bar<Int, Int> {
return Bar.F(f)
}
struct ArrayLike<T> {
subscript(x: ()) -> T { get {} set {} }
}
typealias Test20341012 = (title: (), action: () -> ())
struct T20341012 {
private var options: ArrayLike<Test20341012> { get {} set {} }
// CHECK-LABEL: sil hidden @_TFV20property_abstraction9T203410121t{{.*}}
// CHECK: [[TMP1:%.*]] = alloc_stack $(title: (), action: @callee_owned (@in ()) -> @out ())
// CHECK: apply {{.*}}<(title: (), action: () -> ())>([[TMP1]],
mutating func t() {
_ = self.options[].title
}
}
class MyClass {}
// When simply assigning to a property, reabstract the r-value and assign
// to the base instead of materializing and then assigning.
protocol Factory {
associatedtype Product
var builder : () -> Product { get set }
}
func setBuilder<F: Factory where F.Product == MyClass>(_ factory: inout F) {
factory.builder = { return MyClass() }
}
// CHECK: sil hidden @_TF20property_abstraction10setBuilder{{.*}} : $@convention(thin) <F where F : Factory, F.Product == MyClass> (@inout F) -> ()
// CHECK: bb0(%0 : $*F):
// CHECK: [[FACTORY:%.*]] = alloc_box $F
// CHECK: [[PB:%.*]] = project_box [[FACTORY]]
// CHECK: [[F0:%.*]] = function_ref @_TFF20property_abstraction10setBuilder{{.*}} : $@convention(thin) () -> @owned MyClass
// CHECK: [[F1:%.*]] = thin_to_thick_function [[F0]]
// CHECK: [[SETTER:%.*]] = witness_method $F, #Factory.builder!setter.1
// CHECK: [[REABSTRACTOR:%.*]] = function_ref @_TTR
// CHECK: [[F2:%.*]] = partial_apply [[REABSTRACTOR]]<F>([[F1]])
// CHECK: apply [[SETTER]]<F, MyClass>([[F2]], [[PB]])
| 36.984962 | 179 | 0.591584 |
5b7f8cc26df525b85fcc9a303641a92c0e849ba7
| 581 |
// This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
struct e {
protocol c : a {
func a: B<T : Int](t: U : a {
return "][T where S(h: Any)
}
class A {
if true {
case c<T> a {
}
}
func i: A.a(x) {
}
}
convenience init(#object1: c = B<h)
| 25.26087 | 79 | 0.688468 |
cc8efec6eaab32bb74d1bbc7a86dc6351421cb11
| 981 |
import UIKit
class SendAmountViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var errorLabel: UILabel!
@IBOutlet weak var currencyLabel: UILabel!
@IBOutlet weak var amountField: UITextField!
@IBOutlet weak var balanceAvailableLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.amountField.becomeFirstResponder()
}
@IBAction func nextPress() {
guard let amountText = self.amountField.text, amountText.count != 0 else {
self.errorLabel.text = "Please enter the amount"
self.errorLabel.isHidden = false
return
}
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
self.errorLabel.isHidden = true
return true
}
}
| 28.852941 | 129 | 0.662589 |
38d16eb5e0d850216a77869bf579dea221fe1510
| 843 |
//
// TestView.swift
// YGAlert_Example
//
// Created by Yonatan Giventer on 04/03/2019.
// Copyright © 2019 CocoaPods. All rights reserved.
//
import UIKit
class TestView : UIView{
@IBOutlet weak var lbl:UILabel!
@IBOutlet weak var segment:UISegmentedControl!
@IBOutlet weak var btn:UIButton!
static func loadViewFromNib() -> TestView? {
let bundle = Bundle.main
let nib = UINib(nibName: "TestView", bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil)[0] as? TestView
return view
}
@IBAction func segmentChanged(_ sender: UISegmentedControl){
print("segment changed to \(sender.selectedSegmentIndex)")
}
@IBAction func btnTapped(_ sender: UIButton){
print("btn tapped")
}
}
| 22.184211 | 81 | 0.622776 |
5b5606b787b6e42816f04ddf68574f34117ef8f0
| 510 |
// This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
struct a{
func e{{{
let a={{{{
{}class S<T{func a<h{func b<T where h.g=
c{
func a{
a{
class A{class b{{
}func a
| 28.333333 | 79 | 0.719608 |
ed8bc2d6e6fdfdb86254770ade01f516bfafbe8d
| 637 |
//
// ViewModel.swift
// MVVMRxSwiftExample
//
// Created by Andre Salla on 16/03/17.
// Copyright © 2017 Andre Salla. All rights reserved.
//
import Foundation
import RxSwift
class ViewModel {
private let listSubject: BehaviorSubject<[(codigo: Int, nome: String)]> = BehaviorSubject(value: [])
let listObservable: Observable<[(codigo: Int, nome: String)]>
let dispose = DisposeBag()
init() {
listObservable = listSubject.asObservable()
APIHelper.Marcas.getMarcas().map{($0.array.map{($0.codigo, $0.nome)})}.subscribe(listSubject).addDisposableTo(dispose)
}
}
| 22.75 | 126 | 0.649922 |
edf130a5831f31dcc0c39bbfd49e88f929cafa6d
| 1,050 |
//
// ViewController.swift
// SampleApp
//
// Created by Codeonomics on 07/07/2019.
// Copyright © 2019 Codeonomics.io All rights reserved.
//
import UIKit
import APIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// create a call
let endpoint = Endpoint(path: "https://jsonplaceholder.typicode.com/posts/1)",
method: .get,
authenticated: false)
let call = APICall<Post>(endpoint:endpoint)
call.execute(callback: { response in
switch response {
case .success(let post): print("POST: ", post)
case .failure(let error): print("error: ", error)
}
})
// use a prebuilt static call
API.getPost(id: 1).execute(callback: { response in
switch response {
case .success(let post): print("POST: ", post)
case .failure(let error): print("error: ", error)
}
})
}
}
| 26.25 | 86 | 0.549524 |
e8d787b05d46c4f0a107c6e6e9f2d8ab4fb1f041
| 13,360 |
//
// BarberoHorariosViewController.swift
// Gents
//
// Created by Community Manager on 8/7/19.
// Copyright © 2019 Rockyto Sánchez. All rights reserved.
//
import UIKit
class BarberoHorariosViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, HorariosModeloProtocol, UIPickerViewDelegate, UIPickerViewDataSource {
var IDCliente:String = ""
let dataSource = ["Corte de cabello", "Afeitado de bigote", "Afeitado de cabeza", "Afeitado de barba", "Delineado de bigote", "Delineado de barba", "Paquete Gents", "Paquete clásico", "Paquete Ritual", "Paquete Old School", "Padre e hijo"]
@IBOutlet weak var lista_width: NSLayoutConstraint!
@IBOutlet weak var datos_width: NSLayoutConstraint!
@IBOutlet weak var servicio_width: NSLayoutConstraint!
@IBOutlet weak var scrollView2: UIScrollView!
@IBOutlet weak var contentView2: NSLayoutConstraint!
@IBOutlet weak var servicioTxt: UITextField!
@IBOutlet weak var nombreCitaTxt: UITextField!
@IBOutlet weak var telefonoCitaTxt: UITextField!
@IBOutlet weak var continuaServicioBtn: UIButton!
@IBOutlet weak var finalizaCita: UIButton!
var servicioPicker = UIPickerView()
var nombreCita = ""
var telefonoCita = ""
var servicioSeleccionado = ""
var elIDHorario = ""
var feedItems: NSArray = NSArray()
var selectHorario: DetallesHorario = DetallesHorario()
@IBOutlet weak var listaHorariosView: UITableView!
override func viewDidAppear(_ animated: Bool) {
print("Apunto de abrir")
if resultado == "401"{
listaHorariosView.isHidden = true
}else if resultado == "202"{
self.listaHorariosView.reloadData()
listaHorariosView.isHidden = false
}
}
override func viewWillAppear(_ animated: Bool) {
print("Resultado antes de aparecer vista:", resultado)
if resultado == "401"{
listaHorariosView.isHidden = true
}else if resultado == "202"{
listaHorariosView.isHidden = false
self.listaHorariosView.reloadData()
self.listaHorariosView.delegate = self
self.listaHorariosView.dataSource = self
}
}
func itemsHorarios(losHorarios: NSArray) {
feedItems = losHorarios
self.listaHorariosView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
print("Apareciendo por primera vez")
contentView2.constant = self.view.frame.width * 3
servicio_width.constant = self.view.frame.width
datos_width.constant = self.view.frame.width
textFieldsRedondeados(for: servicioTxt)
textFieldsRedondeados(for: nombreCitaTxt)
textFieldsRedondeados(for: telefonoCitaTxt)
botonesRedondeados(for: continuaServicioBtn)
botonesRedondeados(for: finalizaCita)
padding(for: servicioTxt)
padding(for: nombreCitaTxt)
padding(for: telefonoCitaTxt)
if resultado == "401"{
self.listaHorariosView.isHidden = true
}else if resultado == "202"{
self.listaHorariosView.isHidden = false
self.listaHorariosView.delegate = self
self.listaHorariosView.dataSource = self
self.listaHorariosView.reloadData()
}
let swipe2 = UISwipeGestureRecognizer(target: self, action: #selector(self.handle2(_:)))
swipe2.direction = .right
self.view.addGestureRecognizer(swipe2)
servicioPicker.delegate = self
servicioPicker.dataSource = self
servicioTxt.inputView = servicioPicker
// Do any additional setup after loading the view.
}
func recarga(){
let horarioModelo = HorariosModelo()
horarioModelo.delegado = self
horarioModelo.verHorarios()
}
@objc func handle2(_ gesture: UISwipeGestureRecognizer){
let current_x2 = scrollView2.contentOffset.x
let screen_width2 = self.view.frame.width
let new_x2 = CGPoint(x: current_x2 - screen_width2, y:0)
if current_x2 > 0{
scrollView2.setContentOffset(new_x2, animated: true)
}
}
func padding(for textField: UITextField){
let blankView = UIView.init(frame: CGRect(x:0, y:0, width: 10, height: -10))
textField.leftView = blankView
textField.leftViewMode = .always
}
func botonesRedondeados(for view: UIView){
view.layer.cornerRadius = 20
view.layer.masksToBounds = true
}
func textFieldsRedondeados(for view: UIView){
view.layer.cornerRadius = 15
view.layer.masksToBounds = true
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return feedItems.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "celdaHorarios", for: indexPath) as! HorariosTableViewCell
let item: DetallesHorario = feedItems[indexPath.row] as! DetallesHorario
DispatchQueue.main.async {
cell.lblHorarios.text = item.elHorario
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let item: DetallesHorario = feedItems[indexPath.row] as! DetallesHorario
elIDHorario = item.idHorario!
print("ID del Horario seleccionado:", elIDHorario)
print("*/--------------------------------------*/")
let position = CGPoint(x: self.view.frame.width * 1, y:0)
scrollView2.setContentOffset(position, animated: true)
}
@IBAction func btnServicio_select(_ sender: Any) {
let position = CGPoint(x: self.view.frame.width * 2, y:0)
scrollView2.setContentOffset(position, animated: true)
if nombreCitaTxt.text!.isEmpty{
nombreCitaTxt.becomeFirstResponder()
}else if telefonoCitaTxt.text!.isEmpty{
telefonoCitaTxt.becomeFirstResponder()
}else if nombreCitaTxt.text!.isEmpty == false && telefonoCitaTxt.text!.isEmpty == false{
nombreCitaTxt.resignFirstResponder()
telefonoCitaTxt.resignFirstResponder()
}
}
@IBAction func cancelaRegistroCita(_ sender: Any){
self.dismiss(animated: true, completion: nil)
}
@IBAction func btnFinaliza_cita(_ sender: Any) {
registraInvitado()
}
func registraInvitado(){
nombreCita = nombreCitaTxt.text!
telefonoCita = telefonoCitaTxt.text!
let url = URL(string: "http://sistema.gents.mx/movilBackendGENTS/registraInvitado.php")!
let body = "cliente=\(nombreCita)&telefono=\(telefonoCita)&tipoRegistro=Invitado"
var request = URLRequest(url: url)
request.httpBody = body.data(using: .utf8)
request.httpMethod = "POST"
URLSession.shared.dataTask(with: request) { (data, response, error) in
DispatchQueue.main.async {
let helper = HelperVC()
if error != nil{
helper.showAlert(title: "Error en el servidor", message: error!.localizedDescription, in: self)
return
}
do{
guard let data = data else{
helper.showAlert(title: "Error de datos", message: error!.localizedDescription, in: self)
return
}
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? NSDictionary
guard let parsedJSON = json else{
print("Error de parseo")
return
}
if parsedJSON["status"] as! String == "200"{
UserDefaults.standard.set(parsedJSON["idCliente"], forKey: "idCliente")
self.IDCliente = UserDefaults.standard.string(forKey: "idCliente")!
UserDefaults.standard.synchronize()
self.registraCita()
print(json)
}else{
if parsedJSON["message"] != nil{
let message = parsedJSON["message"] as! String
helper.showAlert(title: "Error", message: message, in: self)
}
}
} catch {
helper.showAlert(title: "JSON Error", message: error.localizedDescription, in: self)
}
}
}.resume()
}
func registraCita(){
nombreCita = nombreCitaTxt.text!
telefonoCita = telefonoCitaTxt.text!
servicioSeleccionado = servicioTxt.text!
print("Nombre del cliente: ", nombreCita)
print("Telefono del cliente: ", telefonoCita)
print("Servicio seleccionado: ", servicioSeleccionado)
print("El ID de la cita: ", elIDHorario)
let url = URL(string: "http://sistema.gents.mx/movilBackendGENTS/agendaCita.php")!
let body = "servicio=\(servicioSeleccionado)&cliente=\(nombreCita)&idCita=\(elIDHorario)&telefono=\(telefonoCita)&idCliente=\(IDCliente)"
var request = URLRequest(url: url)
request.httpBody = body.data(using: .utf8)
request.httpMethod = "POST"
URLSession.shared.dataTask(with: request) { (data, response, error) in
DispatchQueue.main.async {
let helper = HelperVC()
if error != nil {
helper.showAlert(title: "Error en el servidor", message: error!.localizedDescription, in: self)
return
}
do{
guard let data = data else{
helper.showAlert(title: "Error de datos", message: error!.localizedDescription, in: self)
return
}
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? NSDictionary
guard let parsedJSON = json else{
print("Parseando JSON")
return
}
if parsedJSON["status"] as! String == "200"{
helper.showAlert(title: "¡Listo!", message: parsedJSON["message"] as! String, in: self)
print(json)
}else{
if parsedJSON["message"] != nil{
let message = parsedJSON["message"] as! String
helper.showAlert(title: "Error", message: message, in: self)
}
}
} catch {
helper.showAlert(title: "JSON Error", message: error.localizedDescription, in: self)
}
}
}.resume()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(false)
servicioTxt.resignFirstResponder()
nombreCitaTxt.resignFirstResponder()
telefonoCitaTxt.resignFirstResponder()
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return dataSource.count
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int){
servicioTxt.text = dataSource[row]
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return dataSource[row]
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
| 32.192771 | 243 | 0.551796 |
e969161b68fb6410b8a82218de286197e0161f9a
| 1,178 |
//
// ViewController.swift
// Tipster
//
// Created by Kymberlee Hill on 8/28/18.
// Copyright © 2018 Kymberlee Hill. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tipLabel: UILabel!
@IBOutlet weak var totalLabel: UILabel!
@IBOutlet weak var billField: UITextField!
@IBOutlet weak var tipController: UISegmentedControl!
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.
}
@IBAction func onTap(_ sender: Any) {
view.endEditing(true)
}
@IBAction func calculatingTip(_ sender: Any) {
let tipPercentages = [0.1, 0.15, 0.2]
let bill = Double(billField.text!) ?? 0
let tip = bill * tipPercentages[tipController.selectedSegmentIndex]
let total = bill + tip
tipLabel.text = String(format: "$%.2f", tip)
totalLabel.text = String(format: "$%.2f", total)
}
}
| 26.177778 | 80 | 0.636672 |
623e45eb589e6d2c12f8473ad9eb141845c6ccda
| 3,871 |
//
// VolumeMeter.swift
// AudioEngineDemo
//
// Modified by Colin Stark on 2019/10/02.
// Copyright © 2019 Bluemarblesoft. All rights reserved.
//
// Based on:
// https://developer.apple.com/documentation/avfoundation/audio_track_engineering/using_voice_processing
// See LICENSE folder for licensing information about this source material.
// Note that all audio files have been removed.
// Copyright © 2019 Apple. All rights reserved.
//
import Foundation
import AVFoundation
import Accelerate
// MARK: - VolumeMeter class
/**
Compute the audio "power" or volume.
*/
class VolumeMeter: AudioLevelProvider {
// MARK: - Variables
private let kMinLevel: Float = 0.000_000_01 //-160 dB
private struct VolumeLevels {
let average: Float
let peak: Float
}
private var values = [VolumeLevels]()
private var meterTableAvarage = MeterTable()
private var meterTablePeak = MeterTable()
var levels: AudioLevels {
guard !values.isEmpty else { return AudioLevels(level: 0.0, peakLevel: 0.0) }
return AudioLevels(level: meterTableAvarage.valueForPower(values[0].average),
peakLevel: meterTablePeak.valueForPower(values[0].peak))
}
// MARK: - Methods
func processSilence() {
if values.isEmpty { return }
values = []
}
// Calculates average (rms) and peak level of each channel in pcm buffer and caches data
func process(buffer: AVAudioPCMBuffer) {
var volumeLevels = [VolumeLevels]()
let channelCount = Int(buffer.format.channelCount)
let length = vDSP_Length(buffer.frameLength)
if let floatData = buffer.floatChannelData {
for channel in 0..<channelCount {
volumeLevels.append(calculateVolumes(data: floatData[channel], strideFrames: buffer.stride, length: length))
}
} else if let int16Data = buffer.int16ChannelData {
for channel in 0..<channelCount {
// convert data from int16 to float values before calculating power values
var floatChannelData: [Float] = Array(repeating: Float(0.0), count: Int(buffer.frameLength))
vDSP_vflt16(int16Data[channel], buffer.stride, &floatChannelData, buffer.stride, length)
var scalar = Float(INT16_MAX)
vDSP_vsdiv(floatChannelData, buffer.stride, &scalar, &floatChannelData, buffer.stride, length)
volumeLevels.append(calculateVolumes(data: floatChannelData, strideFrames: buffer.stride, length: length))
}
} else if let int32Data = buffer.int32ChannelData {
for channel in 0..<channelCount {
// convert data from int32 to float values before calculating power values
var floatChannelData: [Float] = Array(repeating: Float(0.0), count: Int(buffer.frameLength))
vDSP_vflt32(int32Data[channel], buffer.stride, &floatChannelData, buffer.stride, length)
var scalar = Float(INT32_MAX)
vDSP_vsdiv(floatChannelData, buffer.stride, &scalar, &floatChannelData, buffer.stride, length)
volumeLevels.append(calculateVolumes(data: floatChannelData, strideFrames: buffer.stride, length: length))
}
}
self.values = volumeLevels
}
private func calculateVolumes(data: UnsafePointer<Float>, strideFrames: Int, length: vDSP_Length) -> VolumeLevels {
var max: Float = 0.0
vDSP_maxv(data, strideFrames, &max, length)
if max < kMinLevel {
max = kMinLevel
}
var rms: Float = 0.0
vDSP_rmsqv(data, strideFrames, &rms, length)
if rms < kMinLevel {
rms = kMinLevel
}
return VolumeLevels(average: 20.0 * log10(rms), peak: 20.0 * log10(max))
}
}
| 36.866667 | 124 | 0.64867 |
502c368db4b862814ba00f21a6fa6d3bef7d6c13
| 2,062 |
//
// RouteMatchResult.swift
// RxRouting
//
// Created by Bas van Kuijck on 05/06/2019.
// Copyright © 2019 E-sites. All rights reserved.
//
import Foundation
public protocol ValueType {
}
extension String: ValueType { }
extension Int: ValueType { }
extension Float: ValueType { }
extension Bool: ValueType { }
extension UUID: ValueType { }
extension Date: ValueType { }
protocol RouteMatchResultValueType {
static var typeName: String { get }
static func from(pathComponents: [String], index: Int) -> Self?
}
extension RouteMatchResultValueType {
static var typeName: String {
return "\(self)".lowercased()
}
}
extension String: RouteMatchResultValueType {
static func from(pathComponents: [String], index: Int) -> String? {
return pathComponents[index]
}
}
extension Int: RouteMatchResultValueType {
static func from(pathComponents: [String], index: Int) -> Int? {
return Int(pathComponents[index])
}
}
extension Date: RouteMatchResultValueType {
static func from(pathComponents: [String], index: Int) -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "YYYY-MM-dd"
return dateFormatter.date(from: pathComponents[index])
}
}
extension Bool: RouteMatchResultValueType {
static func from(pathComponents: [String], index: Int) -> Bool? {
return pathComponents[index] == "true" || pathComponents[index] == "1"
}
}
extension UUID: RouteMatchResultValueType {
static func from(pathComponents: [String], index: Int) -> UUID? {
return UUID(uuidString: pathComponents[index])
}
}
extension Float: RouteMatchResultValueType {
static func from(pathComponents: [String], index: Int) -> Float? {
return Float(pathComponents[index])
}
}
public struct RouteMatchResult {
public let pattern: String
public let values: [String: Any]
internal(set) public var url: URL!
init(pattern: String, values: [String: Any]) {
self.pattern = pattern
self.values = values
}
}
| 25.45679 | 78 | 0.680407 |
e0d33be564bc052e6b40610f34c14add8999ae2c
| 881 |
// RUN: %target-swift-frontend %s -typecheck
// FIXME: %target-swift-frontend %s -emit-ir -- see https://github.com/apple/swift/pull/7414
protocol P {
associatedtype A
associatedtype B
}
protocol Q : P {
associatedtype M
typealias A = M
}
extension Q {
typealias B = M
}
protocol R {
associatedtype S
init()
}
extension R {
init<V : Q>(_: V) where V.M == Self {
let _ = V.A.self
let _ = V.B.self
let _ = V.M.self
let _ = Self.self
let _: V.M.Type = V.A.self
let _: V.M.Type = V.B.self
let _: V.M.Type = Self.self
let _: V.A.Type = V.M.self
let _: V.A.Type = V.B.self
let _: V.A.Type = Self.self
let _: V.B.Type = V.M.self
let _: V.B.Type = V.A.self
let _: V.B.Type = Self.self
let _: Self.Type = V.A.self
let _: Self.Type = V.B.self
let _: Self.Type = V.M.self
self.init()
}
}
| 16.622642 | 92 | 0.573212 |
8fe14b6c559b63bb70ea30278ba378d749815c87
| 1,155 |
//
// Copyright © 2020 Rosberry. All rights reserved.
//
import UIKit
final class SimpleImageContentView: UIView {
var removeActionHandler: (() -> Void)?
let imageView: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFit
return imageView
}()
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
override func layoutSubviews() {
super.layoutSubviews()
imageView.frame = bounds
}
@objc private func removeButtonPressed() {
removeActionHandler?()
}
override func sizeThatFits(_ size: CGSize) -> CGSize {
guard let image = imageView.image else {
return .zero
}
let aspect = image.size.height / image.size.width
let width = size.width
let height = width * aspect
return .init(width: width, height: height)
}
// MARK: - Private
private func setup() {
addSubview(imageView)
backgroundColor = .white
}
}
| 21.792453 | 58 | 0.594805 |
8ff71a43cb97ba5eaa4f9c4f4248a7b990039b5a
| 11,472 |
//
// fullyconnected_op_test.swift
// serrano
//
// Created by ZHONGHAO LIU on 7/16/17.
// Copyright © 2017 ZHONGHAO LIU. All rights reserved.
//
import XCTest
@testable import Serrano
import Dispatch
import Accelerate
public class OperatorDelegateConvFullyConnctOp: OperatorDelegateConv {
override public func compare() {
// Compare resutl
let inputTensor = self.veryfyTensors[0]
let weightTensor = self.veryfyTensors[1]
let biasTensor = self.veryfyTensors[2]
let tensorC = self.resultTensors[0]
let readA = inputTensor.contentsAddress
let readB = weightTensor.contentsAddress
let verifyTensor = SerranoResourceManager.globalManager.allocateTensors( [tensorC.shape]).first!
let verifyAddres = verifyTensor.contentsAddress
let M = Int32(1)
let N = Int32(weightTensor.shape.shapeArray[1])
let K = Int32(inputTensor.count)
cblas_sgemm(CblasRowMajor, cblasTrans(false), cblasTrans(false), M, N, K,
1.0, readA, K, readB, N, 0.0, verifyAddres, N)
// plus bias
vDSP_vadd(verifyAddres, 1, biasTensor.contentsAddress, 1, verifyAddres, 1, vDSP_Length(verifyTensor.count))
let verifyReader = verifyTensor.floatValueReader
let readC = tensorC.floatValueReader
for i in 0..<tensorC.count {
if verifyReader[i].isInfinite { continue }
XCTAssertEqualWithAccuracy(verifyReader[i], readC[i], accuracy: abs(verifyReader[i]*0.001), "\(biasTensor.floatValueReader[i])")
}
}
}
class FullyconnectedOpTest: 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()
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
Target:
init....
*/
func testInit() {
let numCase = 100
for i in 0..<numCase {
print("Test \(i+1)...")
let label = randomString(length: 3)
let num = randomInt([100, 250])
let dim = randomInt([100, 250])
let op = FullyconnectedOperator(inputDim: dim, numUnits: num, operatorLabel: label)
XCTAssertEqual(op.operatorLabel, label)
XCTAssertEqual(op.numUnits, num)
print("Finish Test \(i+1)...\n")
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
Target:
public func outputShape(shapeArray shapes: [TensorShape]) -> [TensorShape]?
*/
func testOutputShape() {
let numCase = 100
let op = FullyconnectedOperator(inputDim:1, numUnits: 2)
for i in 0..<numCase {
print("Test \(i+1)...")
let num = randomInt([10, 100])
op.numUnits = num
let dim = randomInt([10, 100])
op.inputDim = dim
// generate input shapes
var inputShapes = [TensorShape]()
if i % 2 == 0 {
// valid
for _ in 0..<randomInt([1, 5]) {
inputShapes.append(TensorShape(dataType: .int, shape: [dim]))
print("Input shape: \(inputShapes.last!.description)")
}
} else {
// invalid
let caseRand = randomInt([0, 2])
if caseRand % 2 == 0 {
// nil
} else {
// not same
inputShapes.append(TensorShape(dataType: .int, shape: [dim]))
print("Input shape: \(inputShapes.last!.description)")
for _ in 0..<randomInt([1, 5]) {
var shape = TensorShape(dataType: .float, shape: [dim])
while shape.count == inputShapes.last!.count {
shape = randomShape(dimensions: randomInt([1,4]), dimensionSizeRange: [1, 10], dataType: .float)
}
inputShapes.append(shape)
print("Input shape: \(inputShapes.last!.description)")
}
}
}
let outputShape = op.outputShape(shapeArray: inputShapes)
if i % 2 == 0 {
XCTAssertNotNil(outputShape)
for shape in outputShape! {
XCTAssertEqual(num, shape.count)
}
} else {
XCTAssertNil(outputShape)
}
print("Finish Test \(i+1)\n\n")
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
Target:
public func inputOutputTensorsCheck() -> (check: Bool, msg: String)
*/
func testInputOutputTensorsCheck() {
let numCase = 100
let op = FullyconnectedOperator(inputDim:1, numUnits: 1)
var numUnits = 0
var inputDim = 0
var weight:Tensor?
var bias: Tensor?
var inputTensors: [Tensor]?
var outputTensors: [Tensor]?
for i in 0..<numCase {
print("Test \(i+1)...")
inputTensors = [Tensor]()
outputTensors = [Tensor]()
// set up numUnit
numUnits = randomInt([10, 150])
op.numUnits = numUnits
inputDim = randomInt([10, 150])
op.inputDim = inputDim
// generate valid input tensor
for _ in 0..<randomInt([1, 3]) {
inputTensors!.append(randomTensor(fromShape: TensorShape(dataType: .float, shape: [op.inputDim])))
}
// generate valid output tensor
for _ in 0..<inputTensors!.count {
outputTensors!.append(randomTensor(fromShape: TensorShape(dataType: .float, shape: [op.numUnits])))
}
// generate valid weight tensor
weight = randomTensor(fromShape: TensorShape(dataType: .float, shape: [op.inputDim, op.numUnits]))
// generate valid bias tensor
bias = randomTensor(fromShape: TensorShape(dataType: .float, shape: [op.numUnits]))
// setup invalid case
if i % 4 != 0 {
let randCase = i % 11
if randCase == 0 {
// input nil
inputTensors = nil
print("Set input tensors to nil")
} else if randCase == 1 {
// output nil
outputTensors = nil
print("Set output tensors to nil")
} else if randCase == 2 {
// weight nil
weight = nil
print("Set weight tensor to nil")
} else if randCase == 3 {
// bias nil
bias = nil
print("Set bias tensor to nil")
} else if randCase == 4 {
// input not valid
var shape = randomShape(dimensions: randomInt([1,4]), dimensionSizeRange: [1, 10], dataType: .float)
while shape.count == inputTensors!.first!.count {
shape = randomShape(dimensions: randomInt([1,4]), dimensionSizeRange: [1, 10], dataType: .float)
}
inputTensors!.removeLast()
inputTensors!.append(randomTensor(fromShape: shape))
print("Set invalid input tensor: \(inputTensors!.last!.description)")
} else if randCase == 5 {
// output not same count
outputTensors!.removeLast()
print("Remove tensor from output tensors")
} else if randCase == 6 {
// output not valid
var shapeArray = outputTensors!.last!.shape.shapeArray
shapeArray[0] += randomInt([1, 5])
outputTensors!.removeLast()
outputTensors!.append(randomTensor(fromShape: TensorShape(dataType: .float, shape: shapeArray)))
print("Set invalid output tensor: \(outputTensors!.last!.description)")
} else if randCase == 7 {
// weight rank not correct
weight = randomTensor(fromShape: TensorShape(dataType: .float, shape: [3, 3, 3]))
print("Set invalid weight tensor: \(weight!.description)")
} else if randCase == 8 {
// weight shape not match
var shapeArray = weight!.shape.shapeArray
shapeArray[0] += randomInt([1, 5])
weight = randomTensor(fromShape: TensorShape(dataType: .float, shape: [shapeArray[0], shapeArray[1]]))
print("Set invalid weight tensor: \(weight!.description)")
} else if randCase == 9 {
// bias rank not correct
bias = randomTensor(fromShape: TensorShape(dataType: .float, shape: [3, 3]))
print("Set invalid bias tensor: \(bias!.description)")
} else {
// bias shape not match
var shapeArray = bias!.shape.shapeArray
shapeArray[0] += randomInt([1, 5])
bias = randomTensor(fromShape: TensorShape(dataType: .float, shape: [shapeArray[0]]))
print("Set invalid bias tensor: \(bias!.description)")
}
}
op.inputTensors = inputTensors
op.outputTensors = outputTensors
op.weight = weight
op.bias = bias
if op.inputTensors == nil {
print("Input tensor: nil")
} else {
for tensor in op.inputTensors! {
print("Input tensor: \(tensor.description)")
}
}
if op.outputTensors == nil {
print("Output tensor: nil")
} else {
for tensor in op.outputTensors! {
print("Output tensor: \(tensor.description)")
}
}
print("Weight: \(op.weight?.description)")
print("bias: \(op.bias?.description)")
let (pass, msg) = op.inputOutputTensorsCheck()
if i % 4 == 0 {
XCTAssertTrue(pass)
} else {
XCTAssertFalse(pass)
print(msg)
}
print("Finish Test \(i+1)\n\n")
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
public func compute(_ computationMode: OperatorComputationMode = SerranoEngine.configuredEngine.defaultComputationMode)
public func computeAsync(_ computationMode: OperatorComputationMode = SerranoEngine.configuredEngine.defaultComputationMode)
internal func cpu()
internal func gpu()
*/
func testCompute() {
let numCase = 10
let op = FullyconnectedOperator(inputDim: 1, numUnits: 1)
var numUnits = 0
var inputDim = 0
var weight:Tensor?
var bias: Tensor?
var inputTensors: [Tensor]?
var outputTensors: [Tensor]?
// gpu initial
_ = SerranoEngine.configuredEngine.configureEngine(computationMode: .GPU)
let workGroup = DispatchGroup()
let delegate = OperatorDelegateConvFullyConnctOp()
op.computationDelegate = delegate
delegate.dispatchGroup = workGroup
for i in 0..<numCase {
print("Test case \(i+1)...")
print("Finish Test case \(i+1)\n\n")
inputTensors = [Tensor]()
outputTensors = [Tensor]()
// set up numUnit
numUnits = randomInt([100, 150])
op.numUnits = numUnits
inputDim = randomInt([10, 150])
op.inputDim = inputDim
// generate valid input tensor
for _ in 0..<randomInt([1, 3]) {
inputTensors!.append(randomTensor(fromShape: TensorShape(dataType: .float, shape: [op.inputDim])))
}
// generate valid output tensor
for _ in 0..<inputTensors!.count {
outputTensors!.append(randomTensor(fromShape: TensorShape(dataType: .float, shape: [op.numUnits])))
}
// generate valid weight tensor
weight = randomTensor(fromShape: TensorShape(dataType: .float, shape: [op.inputDim, op.numUnits]))
// generate valid bias tensor
bias = randomTensor(fromShape: TensorShape(dataType: .float, shape: [op.numUnits]))
op.inputTensors = inputTensors!
op.outputTensors = outputTensors!
op.weight = weight!
op.bias = bias!
delegate.veryfyTensors = [inputTensors!.first!, weight!, bias!]
print("Input tensor: \(inputTensors!.first!.description)")
print("Output tensor: \(outputTensors!.first!.description)")
print("Weight: \(weight!.description)")
print("Bias: \(bias!.description)")
if i % 2 == 0 {
print("Run CPU")
workGroup.enter()
op.computeAsync(.CPU)
} else {
if !SerranoEngine.configuredEngine.hasAvailableGPU() {
print("No gpu available, give up gpu test \n\n")
continue
}
workGroup.enter()
op.computeAsync(.GPU)
}
workGroup.wait()
SerranoResourceManager.globalManager.releaseAllResources()
print("Finish test \(i+1)\n\n")
}
}
}
| 29.797403 | 131 | 0.625 |
20412790d6d5f0dc3f4853dde00fbdee8b4c7296
| 883 |
import Foundation
import FigmaExportCore
final public class XcodeImagesExporter: XcodeImagesExporterBase {
public func export(assets: [AssetPair<ImagePack>], append: Bool) throws -> [FileContents] {
// Generate assets
let assetsFolderURL = output.assetsFolderURL
// Generate metadata (Assets.xcassets/Illustrations/Contents.json)
let contentsFile = XcodeEmptyContents().makeFileContents(to: assetsFolderURL)
let imageAssetsFiles = try assets.flatMap { pair -> [FileContents] in
try pair.makeFileContents(to: assetsFolderURL, preservesVector: nil, renderMode: nil)
}
// Generate extensions
let imageNames = assets.map { $0.light.name }
let extensionFiles = try generateExtensions(names: imageNames, append: append)
return [contentsFile] + imageAssetsFiles + extensionFiles
}
}
| 35.32 | 97 | 0.706682 |
fc10b751837ff44653b17ebcd7d8fcedd7f30da0
| 2,855 |
//
// Ladder.swift
// BattleNetAPI
//
// Created by Christopher Jennewein on 4/12/18.
// Copyright © 2018 Prismatic Games. All rights reserved.
//
import Foundation
public class LadderSummary: Codable {
public let showCaseEntries: [ShowCaseEntry]
public let placementMatches: [PlacementMatch]
public let allLadderMemberships: [LadderMembership]
}
public class ShowCaseEntry: Codable {
public let ladderID: String
public let team: Team
public let leagueName: String
public let localizedDivisionName: String
public let rank: Int
public let wins: Int
public let losses: Int
enum CodingKeys: String, CodingKey {
case ladderID = "ladderId"
case team, leagueName, localizedDivisionName, rank, wins, losses
}
}
public class PlacementMatch: Codable {
public let localizedGameMode: String
public let members: [TeamMember]
public let gamesRemaining: Int
}
public class LadderMembership: Codable {
public let ladderID: String
public let localizedGameMode: String
public let rank: Int?
enum CodingKeys: String, CodingKey {
case ladderID = "ladderId"
case localizedGameMode, rank
}
}
public class Team: Codable {
public let localizedGameMode: String
public let members: [TeamMember]
}
public class TeamMember: Codable {
public let favoriteRace: FavoriteRace?
public let name: String
public let playerID: String
public let region: Int
public let clanTag: String?
enum CodingKeys: String, CodingKey {
case favoriteRace
case name
case playerID = "playerId"
case region
case clanTag
}
}
public class Ladder: Codable {
public let ladderTeams: [LadderTeam]
public let allLadderMemberships: [LadderMembership]
public let localizedDivision: String?
public let league: String?
public let currentLadderMembership: LadderMembership?
public let ranksAndPools: [RanksAndPool]
}
public class LadderTeam: Codable {
public let teamMembers: [LadderTeamMember]
public let previousRank: Int
public let points: Int
public let wins: Int
public let losses: Int
public let mmr: Int?
public let joinTimestamp: Int
}
public class LadderTeamMember: Codable {
public let id: String
public let realm: Int
public let region: Int
public let displayName: String
public let favoriteRace: FavoriteRace?
public let clanTag: String?
}
public enum FavoriteRace: String, Codable {
case protoss = "protoss"
case random = "random"
case terran = "terran"
case zerg = "zerg"
}
public class RanksAndPool: Codable {
public let rank: Int
public let mmr: Int
public let bonusPool: Int
}
public class GrandmasterLeaderboard: Codable {
public let ladderTeams: [LadderTeam]
}
| 22.65873 | 72 | 0.699475 |
d6ba784edd00b46d1f3466032c81887866987e47
| 33,155 |
import XCTest
import CPU
import LR35902
class InstructionSetTests: XCTestCase {
func testWidths() {
let widths: [LR35902.Instruction.Spec: InstructionWidth<UInt16>] = [
.nop: InstructionWidth(opcode: 1, immediate: 0),
.ld(.bc, .imm16): InstructionWidth(opcode: 1, immediate: 2),
.ld(.bcaddr, .a): InstructionWidth(opcode: 1, immediate: 0),
.inc(.bc): InstructionWidth(opcode: 1, immediate: 0),
.inc(.b): InstructionWidth(opcode: 1, immediate: 0),
.dec(.b): InstructionWidth(opcode: 1, immediate: 0),
.ld(.b, .imm8): InstructionWidth(opcode: 1, immediate: 1),
.rlca: InstructionWidth(opcode: 1, immediate: 0),
.ld(.imm16addr, .sp): InstructionWidth(opcode: 1, immediate: 2),
.add(.hl, .bc): InstructionWidth(opcode: 1, immediate: 0),
.ld(.a, .bcaddr): InstructionWidth(opcode: 1, immediate: 0),
.dec(.bc): InstructionWidth(opcode: 1, immediate: 0),
.inc(.c): InstructionWidth(opcode: 1, immediate: 0),
.dec(.c): InstructionWidth(opcode: 1, immediate: 0),
.ld(.c, .imm8): InstructionWidth(opcode: 1, immediate: 1),
.rrca: InstructionWidth(opcode: 1, immediate: 0),
.stop(.zeroimm8): InstructionWidth(opcode: 1, immediate: 1),
.ld(.de, .imm16): InstructionWidth(opcode: 1, immediate: 2),
.ld(.deaddr, .a): InstructionWidth(opcode: 1, immediate: 0),
.inc(.de): InstructionWidth(opcode: 1, immediate: 0),
.inc(.d): InstructionWidth(opcode: 1, immediate: 0),
.dec(.d): InstructionWidth(opcode: 1, immediate: 0),
.ld(.d, .imm8): InstructionWidth(opcode: 1, immediate: 1),
.rla: InstructionWidth(opcode: 1, immediate: 0),
.jr(nil, .simm8): InstructionWidth(opcode: 1, immediate: 1),
.add(.hl, .de): InstructionWidth(opcode: 1, immediate: 0),
.ld(.a, .deaddr): InstructionWidth(opcode: 1, immediate: 0),
.dec(.de): InstructionWidth(opcode: 1, immediate: 0),
.inc(.e): InstructionWidth(opcode: 1, immediate: 0),
.dec(.e): InstructionWidth(opcode: 1, immediate: 0),
.ld(.e, .imm8): InstructionWidth(opcode: 1, immediate: 1),
.rra: InstructionWidth(opcode: 1, immediate: 0),
.jr(.nz, .simm8): InstructionWidth(opcode: 1, immediate: 1),
.ld(.hl, .imm16): InstructionWidth(opcode: 1, immediate: 2),
.ldi(.hladdr, .a): InstructionWidth(opcode: 1, immediate: 0),
.inc(.hl): InstructionWidth(opcode: 1, immediate: 0),
.inc(.h): InstructionWidth(opcode: 1, immediate: 0),
.dec(.h): InstructionWidth(opcode: 1, immediate: 0),
.ld(.h, .imm8): InstructionWidth(opcode: 1, immediate: 1),
.daa: InstructionWidth(opcode: 1, immediate: 0),
.jr(.z, .simm8): InstructionWidth(opcode: 1, immediate: 1),
.add(.hl, .hl): InstructionWidth(opcode: 1, immediate: 0),
.ldi(.a, .hladdr): InstructionWidth(opcode: 1, immediate: 0),
.dec(.hl): InstructionWidth(opcode: 1, immediate: 0),
.inc(.l): InstructionWidth(opcode: 1, immediate: 0),
.dec(.l): InstructionWidth(opcode: 1, immediate: 0),
.ld(.l, .imm8): InstructionWidth(opcode: 1, immediate: 1),
.cpl: InstructionWidth(opcode: 1, immediate: 0),
.jr(.nc, .simm8): InstructionWidth(opcode: 1, immediate: 1),
.ld(.sp, .imm16): InstructionWidth(opcode: 1, immediate: 2),
.ldd(.hladdr, .a): InstructionWidth(opcode: 1, immediate: 0),
.inc(.sp): InstructionWidth(opcode: 1, immediate: 0),
.inc(.hladdr): InstructionWidth(opcode: 1, immediate: 0),
.dec(.hladdr): InstructionWidth(opcode: 1, immediate: 0),
.ld(.hladdr, .imm8): InstructionWidth(opcode: 1, immediate: 1),
.scf: InstructionWidth(opcode: 1, immediate: 0),
.jr(.c, .simm8): InstructionWidth(opcode: 1, immediate: 1),
.add(.hl, .sp): InstructionWidth(opcode: 1, immediate: 0),
.ldd(.a, .hladdr): InstructionWidth(opcode: 1, immediate: 0),
.dec(.sp): InstructionWidth(opcode: 1, immediate: 0),
.inc(.a): InstructionWidth(opcode: 1, immediate: 0),
.dec(.a): InstructionWidth(opcode: 1, immediate: 0),
.ld(.a, .imm8): InstructionWidth(opcode: 1, immediate: 1),
.ccf: InstructionWidth(opcode: 1, immediate: 0),
.ld(.b, .b): InstructionWidth(opcode: 1, immediate: 0),
.ld(.b, .c): InstructionWidth(opcode: 1, immediate: 0),
.ld(.b, .d): InstructionWidth(opcode: 1, immediate: 0),
.ld(.b, .e): InstructionWidth(opcode: 1, immediate: 0),
.ld(.b, .h): InstructionWidth(opcode: 1, immediate: 0),
.ld(.b, .l): InstructionWidth(opcode: 1, immediate: 0),
.ld(.b, .hladdr): InstructionWidth(opcode: 1, immediate: 0),
.ld(.b, .a): InstructionWidth(opcode: 1, immediate: 0),
.ld(.c, .b): InstructionWidth(opcode: 1, immediate: 0),
.ld(.c, .c): InstructionWidth(opcode: 1, immediate: 0),
.ld(.c, .d): InstructionWidth(opcode: 1, immediate: 0),
.ld(.c, .e): InstructionWidth(opcode: 1, immediate: 0),
.ld(.c, .h): InstructionWidth(opcode: 1, immediate: 0),
.ld(.c, .l): InstructionWidth(opcode: 1, immediate: 0),
.ld(.c, .hladdr): InstructionWidth(opcode: 1, immediate: 0),
.ld(.c, .a): InstructionWidth(opcode: 1, immediate: 0),
.ld(.d, .b): InstructionWidth(opcode: 1, immediate: 0),
.ld(.d, .c): InstructionWidth(opcode: 1, immediate: 0),
.ld(.d, .d): InstructionWidth(opcode: 1, immediate: 0),
.ld(.d, .e): InstructionWidth(opcode: 1, immediate: 0),
.ld(.d, .h): InstructionWidth(opcode: 1, immediate: 0),
.ld(.d, .l): InstructionWidth(opcode: 1, immediate: 0),
.ld(.d, .hladdr): InstructionWidth(opcode: 1, immediate: 0),
.ld(.d, .a): InstructionWidth(opcode: 1, immediate: 0),
.ld(.e, .b): InstructionWidth(opcode: 1, immediate: 0),
.ld(.e, .c): InstructionWidth(opcode: 1, immediate: 0),
.ld(.e, .d): InstructionWidth(opcode: 1, immediate: 0),
.ld(.e, .e): InstructionWidth(opcode: 1, immediate: 0),
.ld(.e, .h): InstructionWidth(opcode: 1, immediate: 0),
.ld(.e, .l): InstructionWidth(opcode: 1, immediate: 0),
.ld(.e, .hladdr): InstructionWidth(opcode: 1, immediate: 0),
.ld(.e, .a): InstructionWidth(opcode: 1, immediate: 0),
.ld(.h, .b): InstructionWidth(opcode: 1, immediate: 0),
.ld(.h, .c): InstructionWidth(opcode: 1, immediate: 0),
.ld(.h, .d): InstructionWidth(opcode: 1, immediate: 0),
.ld(.h, .e): InstructionWidth(opcode: 1, immediate: 0),
.ld(.h, .h): InstructionWidth(opcode: 1, immediate: 0),
.ld(.h, .l): InstructionWidth(opcode: 1, immediate: 0),
.ld(.h, .hladdr): InstructionWidth(opcode: 1, immediate: 0),
.ld(.h, .a): InstructionWidth(opcode: 1, immediate: 0),
.ld(.l, .b): InstructionWidth(opcode: 1, immediate: 0),
.ld(.l, .c): InstructionWidth(opcode: 1, immediate: 0),
.ld(.l, .d): InstructionWidth(opcode: 1, immediate: 0),
.ld(.l, .e): InstructionWidth(opcode: 1, immediate: 0),
.ld(.l, .h): InstructionWidth(opcode: 1, immediate: 0),
.ld(.l, .l): InstructionWidth(opcode: 1, immediate: 0),
.ld(.l, .hladdr): InstructionWidth(opcode: 1, immediate: 0),
.ld(.l, .a): InstructionWidth(opcode: 1, immediate: 0),
.ld(.hladdr, .b): InstructionWidth(opcode: 1, immediate: 0),
.ld(.hladdr, .c): InstructionWidth(opcode: 1, immediate: 0),
.ld(.hladdr, .d): InstructionWidth(opcode: 1, immediate: 0),
.ld(.hladdr, .e): InstructionWidth(opcode: 1, immediate: 0),
.ld(.hladdr, .h): InstructionWidth(opcode: 1, immediate: 0),
.ld(.hladdr, .l): InstructionWidth(opcode: 1, immediate: 0),
.halt: InstructionWidth(opcode: 1, immediate: 0),
.ld(.hladdr, .a): InstructionWidth(opcode: 1, immediate: 0),
.ld(.a, .b): InstructionWidth(opcode: 1, immediate: 0),
.ld(.a, .c): InstructionWidth(opcode: 1, immediate: 0),
.ld(.a, .d): InstructionWidth(opcode: 1, immediate: 0),
.ld(.a, .e): InstructionWidth(opcode: 1, immediate: 0),
.ld(.a, .h): InstructionWidth(opcode: 1, immediate: 0),
.ld(.a, .l): InstructionWidth(opcode: 1, immediate: 0),
.ld(.a, .hladdr): InstructionWidth(opcode: 1, immediate: 0),
.ld(.a, .a): InstructionWidth(opcode: 1, immediate: 0),
.add(.a, .b): InstructionWidth(opcode: 1, immediate: 0),
.add(.a, .c): InstructionWidth(opcode: 1, immediate: 0),
.add(.a, .d): InstructionWidth(opcode: 1, immediate: 0),
.add(.a, .e): InstructionWidth(opcode: 1, immediate: 0),
.add(.a, .h): InstructionWidth(opcode: 1, immediate: 0),
.add(.a, .l): InstructionWidth(opcode: 1, immediate: 0),
.add(.a, .hladdr): InstructionWidth(opcode: 1, immediate: 0),
.add(.a, .a): InstructionWidth(opcode: 1, immediate: 0),
.adc(.b): InstructionWidth(opcode: 1, immediate: 0),
.adc(.c): InstructionWidth(opcode: 1, immediate: 0),
.adc(.d): InstructionWidth(opcode: 1, immediate: 0),
.adc(.e): InstructionWidth(opcode: 1, immediate: 0),
.adc(.h): InstructionWidth(opcode: 1, immediate: 0),
.adc(.l): InstructionWidth(opcode: 1, immediate: 0),
.adc(.hladdr): InstructionWidth(opcode: 1, immediate: 0),
.adc(.a): InstructionWidth(opcode: 1, immediate: 0),
.sub(.a, .b): InstructionWidth(opcode: 1, immediate: 0),
.sub(.a, .c): InstructionWidth(opcode: 1, immediate: 0),
.sub(.a, .d): InstructionWidth(opcode: 1, immediate: 0),
.sub(.a, .e): InstructionWidth(opcode: 1, immediate: 0),
.sub(.a, .h): InstructionWidth(opcode: 1, immediate: 0),
.sub(.a, .l): InstructionWidth(opcode: 1, immediate: 0),
.sub(.a, .hladdr): InstructionWidth(opcode: 1, immediate: 0),
.sub(.a, .a): InstructionWidth(opcode: 1, immediate: 0),
.sbc(.b): InstructionWidth(opcode: 1, immediate: 0),
.sbc(.c): InstructionWidth(opcode: 1, immediate: 0),
.sbc(.d): InstructionWidth(opcode: 1, immediate: 0),
.sbc(.e): InstructionWidth(opcode: 1, immediate: 0),
.sbc(.h): InstructionWidth(opcode: 1, immediate: 0),
.sbc(.l): InstructionWidth(opcode: 1, immediate: 0),
.sbc(.hladdr): InstructionWidth(opcode: 1, immediate: 0),
.sbc(.a): InstructionWidth(opcode: 1, immediate: 0),
.and(.b): InstructionWidth(opcode: 1, immediate: 0),
.and(.c): InstructionWidth(opcode: 1, immediate: 0),
.and(.d): InstructionWidth(opcode: 1, immediate: 0),
.and(.e): InstructionWidth(opcode: 1, immediate: 0),
.and(.h): InstructionWidth(opcode: 1, immediate: 0),
.and(.l): InstructionWidth(opcode: 1, immediate: 0),
.and(.hladdr): InstructionWidth(opcode: 1, immediate: 0),
.and(.a): InstructionWidth(opcode: 1, immediate: 0),
.xor(.b): InstructionWidth(opcode: 1, immediate: 0),
.xor(.c): InstructionWidth(opcode: 1, immediate: 0),
.xor(.d): InstructionWidth(opcode: 1, immediate: 0),
.xor(.e): InstructionWidth(opcode: 1, immediate: 0),
.xor(.h): InstructionWidth(opcode: 1, immediate: 0),
.xor(.l): InstructionWidth(opcode: 1, immediate: 0),
.xor(.hladdr): InstructionWidth(opcode: 1, immediate: 0),
.xor(.a): InstructionWidth(opcode: 1, immediate: 0),
.or(.b): InstructionWidth(opcode: 1, immediate: 0),
.or(.c): InstructionWidth(opcode: 1, immediate: 0),
.or(.d): InstructionWidth(opcode: 1, immediate: 0),
.or(.e): InstructionWidth(opcode: 1, immediate: 0),
.or(.h): InstructionWidth(opcode: 1, immediate: 0),
.or(.l): InstructionWidth(opcode: 1, immediate: 0),
.or(.hladdr): InstructionWidth(opcode: 1, immediate: 0),
.or(.a): InstructionWidth(opcode: 1, immediate: 0),
.cp(.b): InstructionWidth(opcode: 1, immediate: 0),
.cp(.c): InstructionWidth(opcode: 1, immediate: 0),
.cp(.d): InstructionWidth(opcode: 1, immediate: 0),
.cp(.e): InstructionWidth(opcode: 1, immediate: 0),
.cp(.h): InstructionWidth(opcode: 1, immediate: 0),
.cp(.l): InstructionWidth(opcode: 1, immediate: 0),
.cp(.hladdr): InstructionWidth(opcode: 1, immediate: 0),
.cp(.a): InstructionWidth(opcode: 1, immediate: 0),
.ret(.nz): InstructionWidth(opcode: 1, immediate: 0),
.pop(.bc): InstructionWidth(opcode: 1, immediate: 0),
.jp(.nz, .imm16): InstructionWidth(opcode: 1, immediate: 2),
.jp(nil, .imm16): InstructionWidth(opcode: 1, immediate: 2),
.call(.nz, .imm16): InstructionWidth(opcode: 1, immediate: 2),
.push(.bc): InstructionWidth(opcode: 1, immediate: 0),
.add(.a, .imm8): InstructionWidth(opcode: 1, immediate: 1),
.rst(.x00): InstructionWidth(opcode: 1, immediate: 0),
.ret(.z): InstructionWidth(opcode: 1, immediate: 0),
.ret(): InstructionWidth(opcode: 1, immediate: 0),
.jp(.z, .imm16): InstructionWidth(opcode: 1, immediate: 2),
.prefix(.cb): InstructionWidth(opcode: 1, immediate: 0),
.call(.z, .imm16): InstructionWidth(opcode: 1, immediate: 2),
.call(nil, .imm16): InstructionWidth(opcode: 1, immediate: 2),
.adc(.imm8): InstructionWidth(opcode: 1, immediate: 1),
.rst(.x08): InstructionWidth(opcode: 1, immediate: 0),
.ret(.nc): InstructionWidth(opcode: 1, immediate: 0),
.pop(.de): InstructionWidth(opcode: 1, immediate: 0),
.jp(.nc, .imm16): InstructionWidth(opcode: 1, immediate: 2),
.call(.nc, .imm16): InstructionWidth(opcode: 1, immediate: 2),
.push(.de): InstructionWidth(opcode: 1, immediate: 0),
.sub(.a, .imm8): InstructionWidth(opcode: 1, immediate: 1),
.rst(.x10): InstructionWidth(opcode: 1, immediate: 0),
.ret(.c): InstructionWidth(opcode: 1, immediate: 0),
.reti: InstructionWidth(opcode: 1, immediate: 0),
.jp(.c, .imm16): InstructionWidth(opcode: 1, immediate: 2),
.call(.c, .imm16): InstructionWidth(opcode: 1, immediate: 2),
.sbc(.imm8): InstructionWidth(opcode: 1, immediate: 1),
.rst(.x18): InstructionWidth(opcode: 1, immediate: 0),
.ld(.ffimm8addr, .a): InstructionWidth(opcode: 1, immediate: 1),
.pop(.hl): InstructionWidth(opcode: 1, immediate: 0),
.ld(.ffccaddr, .a): InstructionWidth(opcode: 1, immediate: 0),
.push(.hl): InstructionWidth(opcode: 1, immediate: 0),
.and(.imm8): InstructionWidth(opcode: 1, immediate: 1),
.rst(.x20): InstructionWidth(opcode: 1, immediate: 0),
.add(.sp, .imm8): InstructionWidth(opcode: 1, immediate: 1),
.jp(nil, .hl): InstructionWidth(opcode: 1, immediate: 0),
.ld(.imm16addr, .a): InstructionWidth(opcode: 1, immediate: 2),
.xor(.imm8): InstructionWidth(opcode: 1, immediate: 1),
.rst(.x28): InstructionWidth(opcode: 1, immediate: 0),
.ld(.a, .ffimm8addr): InstructionWidth(opcode: 1, immediate: 1),
.pop(.af): InstructionWidth(opcode: 1, immediate: 0),
.ld(.a, .ffccaddr): InstructionWidth(opcode: 1, immediate: 0),
.di: InstructionWidth(opcode: 1, immediate: 0),
.push(.af): InstructionWidth(opcode: 1, immediate: 0),
.or(.imm8): InstructionWidth(opcode: 1, immediate: 1),
.rst(.x30): InstructionWidth(opcode: 1, immediate: 0),
.ld(.hl, .sp_plus_simm8): InstructionWidth(opcode: 1, immediate: 1),
.ld(.sp, .hl): InstructionWidth(opcode: 1, immediate: 0),
.ld(.a, .imm16addr): InstructionWidth(opcode: 1, immediate: 2),
.ei: InstructionWidth(opcode: 1, immediate: 0),
.cp(.imm8): InstructionWidth(opcode: 1, immediate: 1),
.rst(.x38): InstructionWidth(opcode: 1, immediate: 0),
.invalid: InstructionWidth(opcode: 1, immediate: 0),
.cb(.rlc(.b)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.rlc(.c)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.rlc(.d)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.rlc(.e)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.rlc(.h)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.rlc(.l)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.rlc(.hladdr)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.rlc(.a)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.rrc(.b)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.rrc(.c)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.rrc(.d)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.rrc(.e)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.rrc(.h)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.rrc(.l)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.rrc(.hladdr)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.rrc(.a)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.rl(.b)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.rl(.c)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.rl(.d)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.rl(.e)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.rl(.h)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.rl(.l)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.rl(.hladdr)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.rl(.a)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.rr(.b)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.rr(.c)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.rr(.d)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.rr(.e)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.rr(.h)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.rr(.l)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.rr(.hladdr)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.rr(.a)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.sla(.b)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.sla(.c)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.sla(.d)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.sla(.e)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.sla(.h)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.sla(.l)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.sla(.hladdr)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.sla(.a)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.sra(.b)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.sra(.c)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.sra(.d)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.sra(.e)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.sra(.h)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.sra(.l)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.sra(.hladdr)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.sra(.a)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.swap(.b)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.swap(.c)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.swap(.d)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.swap(.e)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.swap(.h)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.swap(.l)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.swap(.hladdr)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.swap(.a)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.srl(.b)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.srl(.c)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.srl(.d)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.srl(.e)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.srl(.h)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.srl(.l)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.srl(.hladdr)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.srl(.a)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b0, .b)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b0, .c)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b0, .d)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b0, .e)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b0, .h)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b0, .l)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b0, .hladdr)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b0, .a)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b1, .b)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b1, .c)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b1, .d)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b1, .e)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b1, .h)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b1, .l)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b1, .hladdr)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b1, .a)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b2, .b)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b2, .c)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b2, .d)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b2, .e)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b2, .h)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b2, .l)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b2, .hladdr)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b2, .a)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b3, .b)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b3, .c)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b3, .d)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b3, .e)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b3, .h)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b3, .l)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b3, .hladdr)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b3, .a)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b4, .b)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b4, .c)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b4, .d)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b4, .e)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b4, .h)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b4, .l)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b4, .hladdr)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b4, .a)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b5, .b)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b5, .c)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b5, .d)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b5, .e)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b5, .h)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b5, .l)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b5, .hladdr)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b5, .a)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b6, .b)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b6, .c)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b6, .d)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b6, .e)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b6, .h)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b6, .l)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b6, .hladdr)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b6, .a)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b7, .b)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b7, .c)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b7, .d)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b7, .e)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b7, .h)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b7, .l)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b7, .hladdr)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.bit(.b7, .a)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b0, .b)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b0, .c)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b0, .d)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b0, .e)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b0, .h)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b0, .l)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b0, .hladdr)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b0, .a)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b1, .b)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b1, .c)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b1, .d)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b1, .e)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b1, .h)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b1, .l)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b1, .hladdr)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b1, .a)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b2, .b)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b2, .c)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b2, .d)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b2, .e)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b2, .h)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b2, .l)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b2, .hladdr)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b2, .a)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b3, .b)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b3, .c)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b3, .d)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b3, .e)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b3, .h)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b3, .l)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b3, .hladdr)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b3, .a)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b4, .b)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b4, .c)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b4, .d)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b4, .e)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b4, .h)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b4, .l)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b4, .hladdr)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b4, .a)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b5, .b)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b5, .c)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b5, .d)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b5, .e)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b5, .h)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b5, .l)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b5, .hladdr)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b5, .a)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b6, .b)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b6, .c)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b6, .d)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b6, .e)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b6, .h)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b6, .l)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b6, .hladdr)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b6, .a)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b7, .b)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b7, .c)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b7, .d)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b7, .e)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b7, .h)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b7, .l)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b7, .hladdr)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.res(.b7, .a)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b0, .b)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b0, .c)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b0, .d)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b0, .e)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b0, .h)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b0, .l)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b0, .hladdr)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b0, .a)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b1, .b)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b1, .c)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b1, .d)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b1, .e)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b1, .h)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b1, .l)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b1, .hladdr)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b1, .a)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b2, .b)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b2, .c)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b2, .d)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b2, .e)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b2, .h)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b2, .l)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b2, .hladdr)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b2, .a)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b3, .b)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b3, .c)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b3, .d)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b3, .e)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b3, .h)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b3, .l)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b3, .hladdr)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b3, .a)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b4, .b)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b4, .c)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b4, .d)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b4, .e)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b4, .h)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b4, .l)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b4, .hladdr)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b4, .a)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b5, .b)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b5, .c)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b5, .d)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b5, .e)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b5, .h)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b5, .l)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b5, .hladdr)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b5, .a)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b6, .b)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b6, .c)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b6, .d)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b6, .e)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b6, .h)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b6, .l)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b6, .hladdr)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b6, .a)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b7, .b)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b7, .c)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b7, .d)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b7, .e)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b7, .h)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b7, .l)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b7, .hladdr)): InstructionWidth(opcode: 2, immediate: 0),
.cb(.set(.b7, .a)): InstructionWidth(opcode: 2, immediate: 0),
]
for (key, value) in LR35902.InstructionSet.widths {
XCTAssertEqual(value, widths[key], "\(key) mismatched")
}
}
}
| 60.391621 | 74 | 0.611974 |
de067efb58ed1c2ce3b3fab5d21180443b349b5f
| 1,608 |
//
// MusicTask.swift
// Karenina
//
// Created by Matt Luedke on 10/1/15.
// Copyright © 2015 Razeware. All rights reserved.
//
import ResearchKit
public var MusicTask: ORKOrderedTask {
var steps = [ORKStep]()
let instructionStep = ORKInstructionStep(identifier: "intruction")
instructionStep.title = "Music + Heart Rate"
instructionStep.text = "Please listen to a randomized music clip for 30 seconds, and we'll record your heart rate."
steps += [instructionStep]
let configuration = ORKHealthQuantityTypeRecorderConfiguration(identifier: "heartRateConfig",
healthQuantityType: HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)!,
unit: HKUnit(fromString: "count/min"))
let musicStep = MusicStep(identifier: "music")
musicStep.clip = MusicClip.random()
musicStep.stepDuration = 30
musicStep.recorderConfigurations = [configuration]
// a bunch of boilerplate configuration
musicStep.shouldShowDefaultTimer = true
musicStep.shouldStartTimerAutomatically = true
musicStep.shouldContinueOnFinish = true
musicStep.shouldPlaySoundOnStart = true
musicStep.shouldPlaySoundOnFinish = true
musicStep.shouldVibrateOnStart = true
musicStep.shouldVibrateOnFinish = true
musicStep.title = "Please listen for 30 seconds."
steps += [musicStep]
let summaryStep = ORKCompletionStep(identifier: "SummaryStep")
summaryStep.title = "Thank you!"
summaryStep.text = "You have helped us research music and heart rate!"
steps += [summaryStep]
return ORKOrderedTask(identifier: "MusicTask", steps: steps)
}
| 30.923077 | 117 | 0.754353 |
71d8379f3b945ece8235a2b5dcc66263b7a16af7
| 288 |
//
// ViewController.swift
// Xcode Unit Test
//
// Created by Spemai-Macbook on 2021-08-13.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
| 14.4 | 58 | 0.652778 |
f83a12573bd0b566eb50a71f2dd67a31b49ba25d
| 3,107 |
//
// KYUserInfoViewController.swift
// KYMart
//
// Created by Jun on 2017/6/18.
// Copyright © 2017年 JUN. All rights reserved.
//
import UIKit
class KYUserInfoViewController: BaseViewController {
@IBOutlet weak var nickNameL: UITextField!
@IBOutlet weak var oldPassL: UITextField!
@IBOutlet weak var newPassL: UITextField!
var sexSelect:Int = 0
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
self.tabBarController?.tabBar.isHidden = true
}
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
// Do any additional setup after loading the view.
}
func setupUI() {
setBackButtonInNav()
if let text = SingleManager.instance.loginInfo?.nickname {
nickNameL.text = text
}
}
@IBAction func selectAction(_ sender: UITapGestureRecognizer) {
let tag = sender.view?.tag
sexSelect = tag! - 1
for i in 1..<4 {
let imageView = view.viewWithTag(i)?.viewWithTag(11) as! UIImageView
imageView.image = (i == tag ? UIImage(named: "cart_select_yes") : UIImage(named: "cart_select_no"))
}
}
@IBAction func saveInfoAction(_ sender: UIButton) {
if (nickNameL.text?.isEmpty)! {
Toast(content: "昵称不能为空")
}
let params = ["nickname":nickNameL.text!,"sex":String(sexSelect)]
sender.isUserInteractionEnabled = false
SJBRequestModel.push_fetchChangeUserInfoData(params: params as [String : AnyObject]) { (response, status) in
sender.isUserInteractionEnabled = true
if status == 1 {
SingleManager.instance.loginInfo?.nickname = self.nickNameL.text
self.Toast(content: "修改成功")
}
else
{
self.Toast(content: response as! String)
}
}
}
@IBAction func savePhoneAction(_ sender: UIButton) {
//修改密码
if (oldPassL.text?.isEmpty)! {
Toast(content: "旧密码不能为空")
}
if (newPassL.text?.isEmpty)! {
Toast(content: "新密码不能为空")
}
let params = ["old_password":oldPassL.text!,"new_password":newPassL.text!]
SJBRequestModel.push_fetchChangePasswordData(params: params as [String : AnyObject]) { (response, status) in
if status == 1{
self.Toast(content: "修改密码成功!")
}
else
{
self.Toast(content: response as! String)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 32.030928 | 116 | 0.598648 |
643f290b76cb85c5d80698b25c2ed8d0c114e830
| 922 |
//
// CalculatorTests.swift
// CalculatorTests
//
// Created by Брызгалов Николай on 01.02.15.
// Copyright (c) 2015 Брызгалов Николай. All rights reserved.
//
import UIKit
import XCTest
class CalculatorTests: 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.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| 24.918919 | 111 | 0.62256 |
14c6a76fab922fa3badb260f8d532d860242cac9
| 1,292 |
import cmark_gfm
/**
A link.
From the [CommonMark Spec](https://spec.commonmark.org/0.29):
> ## [6.5 Links](https://spec.commonmark.org/0.29/#links)
>
> A link contains link text (the visible text),
> a link destination (the URI that is the link destination),
> and optionally a link title.
> ## [4.7 Link reference definitions](https://spec.commonmark.org/0.29/#link-reference-definitions)
> ## [6.7 Autolinks](https://spec.commonmark.org/0.29/#autolinks)
*/
public final class Link: Inline, Linked, InlineContainer {
override class var cmark_node_type: cmark_node_type { return CMARK_NODE_LINK }
public convenience init<Children>(destination: String, title: String = "", children: Children) where Children: Sequence, Children.Element == Inline {
self.init(newWithExtension: nil)
self.destination = destination
self.title = title
self.children.append(contentsOf: children)
}
public convenience init(destination: String, title: String = "", text string: String) {
self.init(destination: destination, title: title, children: [Text(literal: string)])
}
public override func accept<Visitor>(_ visitor: inout Visitor) -> Visitor.Result where Visitor: CommonMark.Visitor {
visitor.visit(link: self)
}
}
| 35.888889 | 153 | 0.698142 |
878ddf7ccd5f09e0c01942013e9ce09a94de56aa
| 977 |
import TwitterAPIKit
import XCTest
class GetUsersShowRequestV1Tests: XCTestCase {
override func setUpWithError() throws {
}
override func tearDownWithError() throws {
}
func test() throws {
let req = GetUsersShowRequestV1(
user: .userID("uid"),
includeEntities: true
)
XCTAssertEqual(req.method, .get)
XCTAssertEqual(req.baseURLType, .api)
XCTAssertEqual(req.path, "/1.1/users/show.json")
XCTAssertEqual(req.bodyContentType, .wwwFormUrlEncoded)
AssertEqualAnyDict(
req.parameters,
[
"user_id": "uid",
"include_entities": true,
]
)
}
func testDefaultArg() throws {
let req = GetUsersShowRequestV1(
user: .screenName("s")
)
AssertEqualAnyDict(
req.parameters,
[
"screen_name": "s"
]
)
}
}
| 22.72093 | 63 | 0.536336 |
ef15a478bc1488a4d9e417dc0a5e5eb1f612d413
| 1,939 |
//
// Copyright 2020 Swiftkube Project
//
// 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.
//
///
/// Generated by Swiftkube:ModelGen
/// Kubernetes v1.20.9
/// core.v1.VolumeDevice
///
import Foundation
public extension core.v1 {
///
/// volumeDevice describes a mapping of a raw block device within a container.
///
struct VolumeDevice: KubernetesResource {
///
/// devicePath is the path inside of the container that the device will be mapped to.
///
public var devicePath: String
///
/// name must match the name of a persistentVolumeClaim in the pod
///
public var name: String
///
/// Default memberwise initializer
///
public init(
devicePath: String,
name: String
) {
self.devicePath = devicePath
self.name = name
}
}
}
///
/// Codable conformance
///
public extension core.v1.VolumeDevice {
private enum CodingKeys: String, CodingKey {
case devicePath = "devicePath"
case name = "name"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.devicePath = try container.decode(String.self, forKey: .devicePath)
self.name = try container.decode(String.self, forKey: .name)
}
func encode(to encoder: Encoder) throws {
var encodingContainer = encoder.container(keyedBy: CodingKeys.self)
try encodingContainer.encode(devicePath, forKey: .devicePath)
try encodingContainer.encode(name, forKey: .name)
}
}
| 25.513158 | 87 | 0.71738 |
ddb86693540e5d2ef8e4c3da6dcb2e50d73a9cb2
| 438 |
//
// SVGCanvas.swift
// Macaw
//
// Created by Yuri Strot on 4/11/18.
//
class SVGCanvas: Group {
let layout: NodeLayout
public init(layout: NodeLayout, contents: [Node] = []) {
self.layout = layout
super.init(contents: contents)
}
public func layout(size: Size) -> Size {
let size = layout.computeSize(parent: size)
layout.layout(node: self, in: size)
return size
}
}
| 18.25 | 60 | 0.591324 |
76e6597932784524de99a98925d183e654ce9633
| 824 |
//
// PurchaseManagerTypealiases.swift
// MacroCosm
//
// Created by Антон Текутов on 22.05.2021.
//
import StoreKit
enum PurchaseVerification {
case active
case notPurchased
}
enum ResoreResult {
case failed
case success
case nothingToRestore
var localized: String {
switch self {
case .failed:
return NSLocalizedString("Failed", comment: "")
case .success:
return NSLocalizedString("Success", comment: "")
case .nothingToRestore:
return NSLocalizedString("Nothing to restore", comment: "")
}
}
}
typealias CheckActivePurchasesCompletion = (Result<PurchaseVerification, Error>) -> Void
typealias GetPurchaseInfoCompletion = (SKProduct) -> Void
typealias RestorePurchasesCompletion = (ResoreResult) -> Void
| 22.888889 | 88 | 0.669903 |
db32d3577e50f83fee5361f2e158d1cb3590c77a
| 5,614 |
//
// TunerCore.swift
// waka
//
// Created by Stephen on 4/15/16.
// Copyright © 2016 WellMet. All rights reserved.
//
import Foundation
import AudioKit
import Chronos
private let flats = ["C", "D♭","D","E♭","E","F","G♭","G","A♭","A","B♭","B"]
private let sharps = ["C", "C♯","D","D♯","E","F","F♯","G","G♯","A","A♯","B"]
private let frequencies: [Float] = [
16.35, 17.32, 18.35, 19.45, 20.60, 21.83, 23.12, 24.50, 25.96, 27.50, 29.14, 30.87, // 0
32.70, 34.65, 36.71, 38.89, 41.20, 43.65, 46.25, 49.00, 51.91, 55.00, 58.27, 61.74, // 1
65.41, 69.30, 73.42, 77.78, 82.41, 87.31, 92.50, 98.00, 103.8, 110.0, 116.5, 123.5, // 2
130.8, 138.6, 146.8, 155.6, 164.8, 174.6, 185.0, 196.0, 207.7, 220.0, 233.1, 246.9, // 3
261.6, 277.2, 293.7, 311.1, 329.6, 349.2, 370.0, 392.0, 415.3, 440.0, 466.2, 493.9, // 4
523.3, 554.4, 587.3, 622.3, 659.3, 698.5, 740.0, 784.0, 830.6, 880.0, 932.3, 987.8, // 5
1047, 1109, 1175, 1245, 1319, 1397, 1480, 1568, 1661, 1760, 1865, 1976, // 6
2093, 2217, 2349, 2489, 2637, 2794, 2960, 3136, 3322, 3520, 3729, 3951, // 7
4186, 4435, 4699, 4978, 5274, 5588, 5920, 6272, 6645, 7040, 7459, 7902 // 8
]
public protocol TunerDelegate {
//Called by a Tuner on each update.
// Tuner that performed the update
//output contains information decoded by the tuner
func tunerDidUpdate(tuner: Tuner, output: TunerOutput)
}
public class TunerOutput: NSObject {
//Octave of the interpreted pitch
public private(set) var octave: Int = 0
//Interpreted pitch of the microphone audio
public private(set) var pitch: String = ""
//Distance from base pitch
public private(set) var distance: Float = 0.0
//Amplitude of microphone Audio
public private(set) var amplitude: Float = 0.0
//The frequency of the microphone audio
public private(set) var frequency: Float = 0.0
public override init() {}
}
public class Tuner: NSObject {
private let updateInterval: NSTimeInterval = 0.03
private let smoothingBufferCount = 30
/**
Object adopting the TunerDelegate protocol that should receive callbacks
from this tuner.
*/
public var delegate: TunerDelegate?
private let threshold: Float
private let smoothing: Float
private let microphone: AKMicrophone
private let analyzer: AKAudioAnalyzer
private var timer: DispatchTimer?
private var smoothingBuffer: [Float] = []
/**
Initializes a new Tuner.
- parameter threshold: The minimum amplitude to recognize, 0 < threshold < 1
- parameter smoothing: Exponential smoothing factor, 0 < smoothing < 1
*/
public init(threshold: Float = 0.0, smoothing: Float = 0.25) {
self.threshold = min(abs(threshold), 1.0)
self.smoothing = min(abs(smoothing), 1.0)
microphone = AKMicrophone()
analyzer = AKAudioAnalyzer(input: microphone.output)
AKOrchestra.addInstrument(microphone)
AKOrchestra.addInstrument(analyzer)
}
/**
Starts the tuner.
*/
public func start() {
AKSettings.shared().audioInputEnabled = true
microphone.start()
analyzer.start()
if timer == nil {
timer = DispatchTimer(interval: 0.03, closure: { (t, i) -> Void in
if let d = self.delegate {
if self.analyzer.trackedAmplitude.value > self.threshold {
let amplitude = self.analyzer.trackedAmplitude.value
let frequency = self.smooth(self.analyzer.trackedFrequency.value)
let output = Tuner.newOutput(frequency, amplitude)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
d.tunerDidUpdate(self, output: output)
})
}
}
})
}
timer?.start(true)
}
/**
Stops the tuner.
*/
public func stop() {
microphone.stop()
analyzer.stop()
timer?.pause()
}
/**
Exponential smoothing:
https://en.wikipedia.org/wiki/Exponential_smoothing
*/
private func smooth(value: Float) -> Float {
var frequency = value
if smoothingBuffer.count > 0 {
let last = smoothingBuffer.last!
frequency = (smoothing * value) + (1.0 - smoothing) * last
if smoothingBuffer.count > smoothingBufferCount {
smoothingBuffer.removeFirst()
}
}
smoothingBuffer.append(frequency)
return frequency
}
static func newOutput(frequency: Float, _ amplitude: Float) -> TunerOutput {
let output = TunerOutput()
var norm = frequency
while norm > frequencies[frequencies.count - 1] {
norm = norm / 2.0
}
while norm < frequencies[0] {
norm = norm * 2.0
}
var i = -1
var min = Float.infinity
for n in 0...frequencies.count-1 {
let diff = frequencies[n] - norm
if abs(diff) < abs(min) {
min = diff
i = n
}
}
output.octave = i / 12
output.frequency = frequency
output.amplitude = amplitude
output.distance = frequency - frequencies[i]
output.pitch = String(format: "%@", sharps[i % sharps.count], flats[i % flats.count])
return output
}
}
| 32.830409 | 93 | 0.563057 |
1eea50cb6f670ab40cc0c77027316162d08ff356
| 2,142 |
//
// JSONPlaceholderAPI.swift
//
// Copyright (c) 2019 Antti Laitala (https://github.com/anlaital/Alamorest/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import Alamorest
import Promises
struct JSONPlaceholderAPI {
let server: Server
init(baseURL: String) {
server = Server(baseURL: URL(string: baseURL)!)
}
struct Post: Decodable {
let body: String
let id: Int
let title: String
let userId: Int
}
func posts() -> Promise<[Post]> {
return server.json(path: "posts", method: .get)
}
func post(id: Int) -> Promise<Post> {
return server.json(path: "posts/\(id)", method: .get)
}
func createPost(title: String, body: String, userId: Int) -> Promise<Post> {
struct Payload: Encodable {
let title: String
let body: String
let userId: Int
}
let object = Payload(title: title, body: body, userId: userId)
return server.json(object: object, path: "posts", method: .post)
}
}
| 33.46875 | 81 | 0.668067 |
29d43b0e36baaef49947feaeff982c365558c5f6
| 2,139 |
//
// TA_Enumerations.swift
// ta-lib-swift
//
// Created by Pat Sluth on 2017-09-19.
// Copyright © 2017 patsluth. All rights reserved.
//
public enum TA_CandleSettingType: Int
{
case BodyLong
case BodyVeryLong
case BodyShort
case BodyDoji
case ShadowLong
case ShadowVeryLong
case ShadowShort
case ShadowVeryShort
case Near
case Far
case Equal
static let allValues = [BodyLong,
BodyVeryLong,
BodyShort,
BodyDoji,
ShadowLong,
ShadowVeryLong,
ShadowShort,
ShadowVeryShort,
Near,
Far,
Equal]
}
public enum TA_Compatibility
{
case Default
case Metastock
}
public enum TA_FunctionUnstableId: Int
{
case Adx = 0
case Adxr = 1
case AverageTrueRange = 2
case Cmo = 3
case Dx = 4
case Ema = 5
case FuncUnstAll = 0x17
case FuncUnstNone = -1
case HtDcPeriod = 6
case HtDcPhase = 7
case HtPhasor = 8
case HtSine = 9
case HtTrendline = 10
case HtTrendMode = 11
case Kama = 12
case Mama = 13
case Mfi = 14
case MinusDI = 15
case MinusDM = 0x10
case NormalizedAverageTrueRange = 0x11
case PlusDI = 0x12
case PlusDM = 0x13
case Rsi = 20
case StochRsi = 0x15
case T3 = 0x16
}
public enum TA_MovingAverageType
{
case Sma
case Ema
case Wma
case Dema
case Tema
case Trima
case Kama
case Mama
case T3
}
public enum TA_RangeType
{
case RealBody
case HighLow
case Shadows
}
@objc public enum TA_ReturnCode: Int
{
case AllocErr = 3
case BadObject = 15
case BadParam = 2
case FuncNotFound = 5
case GroupNotFound = 4
case InputNotAllInitialize = 10
case InternalError = 0x1388
case InvalidHandle = 6
case InvalidListType = 14
case InvalidParamFunction = 9
case InvalidParamHolder = 7
case InvalidParamHolderType = 8
case LibNotInitialize = 1
case NotSupported = 0x10
case OutOfRangeEndIndex = 13
case OutOfRangeStartIndex = 12
case OutputNotAllInitialize = 11
case Success = 0
case UnknownErr = 0xffff
}
| 15.170213 | 51 | 0.647499 |
f7d25b4f7f0556b7d67c717534e030aee0a56ab7
| 412 |
//
// ImageViewController.swift
// Pods-SASBanner_Example
//
// Created by Manu Puthoor on 15/09/20.
//
import UIKit
class ImageViewController: UIViewController {
@IBOutlet weak var imgView: UIImageView!
@IBOutlet weak var testLabel: UILabel!
var testText = ""
var index = 0
override func viewDidLoad() {
super.viewDidLoad()
testLabel.text = testText
}
}
| 17.166667 | 45 | 0.650485 |
fefa391b309e4db6cc218a01129021395e8ac5be
| 995 |
//
// FullPopSwift2_3Tests.swift
// FullPopSwift2.3Tests
//
// Created by jasnig on 16/6/25.
// Copyright © 2016年 ZeroJ. All rights reserved.
//
import XCTest
@testable import FullPopSwift2_3
class FullPopSwift2_3Tests: 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.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
| 26.891892 | 111 | 0.642211 |
f7fb27bfb1585d5936c7eb3e2a96f1870f994608
| 996 |
class LRUCache {
private let capacity: Int
private var store = [Int:Int]()
private var order = [Int]()
init(_ capacity: Int) {
self.capacity = capacity
}
func get(_ key: Int) -> Int {
let value = store[key]
if let value = value {
order.remove(at: order.lastIndex(of: key)!)
order.append(key)
}
return value ?? -1
}
func put(_ key: Int, _ value: Int) {
if store[key] != nil {
order.remove(at: order.lastIndex(of: key)!)
order.append(key)
} else if order.count == capacity {
store.removeValue(forKey: order.remove(at: 0))
order.append(key)
} else {
order.append(key)
}
store[key] = value
}
}
let cache = LRUCache(2);
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // 返回 1
cache.put(3, 3); // 该操作会使得密钥 2 作废
cache.get(2); // 返回 -1 (未找到)
cache.put(4, 4); // 该操作会使得密钥 1 作废
cache.get(1); // 返回 -1 (未找到)
cache.get(3); // 返回 3
cache.get(4); // 返回 4
| 21.191489 | 52 | 0.549197 |
878035057b0827b719546c9519db7f5e4c6a5634
| 10,161 |
//
// RemoteImage.swift
//
//
// Created by Dmytro Anokhin on 25/08/2020.
//
import SwiftUI
import Combine
#if canImport(DownloadManager)
import DownloadManager
#endif
#if canImport(ImageDecoder)
import ImageDecoder
#endif
#if canImport(RemoteContentView)
import RemoteContentView
#endif
#if canImport(Log)
import Log
#endif
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
public final class RemoteImage : RemoteContent {
/// Reference to URLImageService used to download and cache the image.
unowned let service: URLImageService
/// Download object describes how the image should be downloaded.
let download: Download
let options: URLImageOptions
public init(service: URLImageService, download: Download, options: URLImageOptions) {
self.service = service
self.download = download
self.options = options
}
public typealias LoadingState = RemoteContentLoadingState<TransientImageType, Float?>
/// External loading state used to update the view
@Published public private(set) var loadingState: LoadingState = .initial {
willSet {
log_debug(self, #function, "\(download.url) will transition from \(loadingState) to \(newValue)", detail: log_detailed)
}
}
public func load() {
guard !isLoading else {
return
}
log_debug(self, #function, "Start load for: \(download.url)", detail: log_normal)
isLoading = true
switch options.cachePolicy {
case .returnCacheElseLoad(let cacheDelay, let downloadDelay):
guard !isLoadedSuccessfully else {
// Already loaded
isLoading = false
return
}
guard !loadFromInMemory() else {
// Loaded from the in-memory cache
isLoading = false
return
}
// Disk cache lookup
scheduleReturnCached(afterDelay: cacheDelay) { [weak self] success in
guard let self = self else { return }
if !success {
self.scheduleDownload(afterDelay: downloadDelay, secondCacheLookup: true)
}
}
case .returnCacheDontLoad(let delay):
guard !isLoadedSuccessfully else {
// Already loaded
isLoading = false
return
}
guard !loadFromInMemory() else {
// Loaded from the in-memory cache
isLoading = false
return
}
// Disk cache lookup
scheduleReturnCached(afterDelay: delay) { [weak self] success in
guard let self = self else { return }
if !success {
self.loadingState = .initial
self.isLoading = false
}
}
case .ignoreCache(let delay):
// Always download
scheduleDownload(afterDelay: delay)
case .useProtocol:
scheduleDownload(secondCacheLookup: false)
}
}
public func cancel() {
guard isLoading else {
return
}
log_debug(self, #function, "Cancel load for: \(download.url)", detail: log_normal)
isLoading = false
// Cancel publishers
for cancellable in cancellables {
cancellable.cancel()
}
cancellables.removeAll()
delayedReturnCached?.cancel()
delayedReturnCached = nil
delayedDownload?.cancel()
delayedDownload = nil
}
/// Internal loading state
private var isLoading: Bool = false
private var cancellables = Set<AnyCancellable>()
private var delayedReturnCached: DispatchWorkItem?
private var delayedDownload: DispatchWorkItem?
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension RemoteImage {
private var isLoadedSuccessfully: Bool {
switch loadingState {
case .success:
return true
default:
return false
}
}
/// Rerturn an image from the in memory cache.
///
/// Sets `loadingState` to `.success` if an image is in the in-memory cache and returns `true`. Otherwise returns `false` without changing the state.
private func loadFromInMemory() -> Bool {
guard let transientImage = service.inMemoryCache.getImage(withIdentifier: options.identifier, orURL: download.url) else {
log_debug(self, #function, "Image for \(download.url) not in the in memory cache", detail: log_normal)
return false
}
// Set image retrieved from cache
self.loadingState = .success(transientImage)
log_debug(self, #function, "Image for \(download.url) is in the in memory cache", detail: log_normal)
return true
}
private func scheduleReturnCached(afterDelay delay: TimeInterval?, completion: @escaping (_ success: Bool) -> Void) {
guard let delay = delay else {
// Read from cache immediately if no delay needed
returnCached(completion)
return
}
delayedReturnCached?.cancel()
delayedReturnCached = DispatchWorkItem { [weak self] in
guard let self = self else { return }
self.returnCached(completion)
}
DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: delayedReturnCached!)
}
// Second cache lookup is necessary, for some caching policies, for a case if the same image was downloaded by another instance of RemoteImage.
private func scheduleDownload(afterDelay delay: TimeInterval? = nil, secondCacheLookup: Bool = false) {
guard let delay = delay else {
// Start download immediately if no delay needed
startDownload()
return
}
delayedDownload?.cancel()
delayedDownload = DispatchWorkItem { [weak self] in
guard let self = self else { return }
if secondCacheLookup {
self.returnCached { [weak self] success in
guard let self = self else { return }
if !success {
self.startDownload()
}
}
}
else {
self.startDownload()
}
}
DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: delayedDownload!)
}
private func startDownload() {
loadingState = .inProgress(nil)
service.downloadManager.publisher(for: download)
.sink { [weak self] result in
guard let self = self else {
return
}
switch result {
case .finished:
break
case .failure(let error):
// This route happens when download fails
self.updateLoadingState(.failure(error))
}
}
receiveValue: { [weak self] info in
guard let self = self else {
return
}
switch info {
case .progress(let progress):
self.updateLoadingState(.inProgress(progress))
case .completion(let result):
do {
let transientImage = try self.service.decode(result: result,
download: self.download,
options: self.options)
self.updateLoadingState(.success(transientImage))
}
catch {
// This route happens when download succeeds, but decoding fails
self.updateLoadingState(.failure(error))
}
}
}
.store(in: &cancellables)
}
private func returnCached(_ completion: @escaping (_ success: Bool) -> Void) {
loadingState = .inProgress(nil)
service.diskCache
.getImagePublisher(withIdentifier: options.identifier, orURL: download.url, maxPixelSize: options.maxPixelSize)
.receive(on: DispatchQueue.main)
.catch { _ in
Just(nil)
}
.sink { [weak self] in
guard let self = self else {
return
}
if let transientImage = $0 {
log_debug(self, #function, "Image for \(self.download.url) is in the disk cache", detail: log_normal)
// Move to in memory cache
self.service.inMemoryCache.cacheTransientImage(transientImage,
withURL: self.download.url,
identifier: self.options.identifier,
expireAfter: self.options.expiryInterval)
// Set image retrieved from cache
self.loadingState = .success(transientImage)
completion(true)
}
else {
log_debug(self, #function, "Image for \(self.download.url) not in the disk cache", detail: log_normal)
completion(false)
}
}
.store(in: &cancellables)
}
private func updateLoadingState(_ loadingState: LoadingState) {
DispatchQueue.main.async { [weak self] in
guard let self = self else {
return
}
self.loadingState = loadingState
}
}
}
| 32.99026 | 153 | 0.530952 |
dd5467076d821984b9125c7868fdfb42c5cdbbb8
| 6,469 |
import Foundation
import LLVM
@discardableResult
func generateIRValue(from node: Node, with context: BuildContext) -> IRValue {
switch node {
case let numberNode as NumberNode:
return Generator<NumberNode>(node: numberNode).generate(with: context)
case let binaryExpressionNode as BinaryExpressionNode:
return Generator<BinaryExpressionNode>(node: binaryExpressionNode).generate(with: context)
case let variableNode as VariableNode:
return Generator<VariableNode>(node: variableNode).generate(with: context)
case let functionNode as FunctionNode:
return Generator<FunctionNode>(node: functionNode).generate(with: context)
case let callExpressionNode as CallExpressionNode:
return Generator<CallExpressionNode>(node: callExpressionNode).generate(with: context)
case let ifElseNode as IfElseNode:
return Generator<IfElseNode>(node: ifElseNode).generate(with: context)
case let returnNode as ReturnNode:
return Generator<ReturnNode>(node: returnNode).generate(with: context)
default:
fatalError("Unknown node type \(type(of: node))")
}
}
private protocol GeneratorProtocol {
associatedtype NodeType: Node
var node: NodeType { get }
func generate(with: BuildContext) -> IRValue
init(node: NodeType)
}
private struct Generator<NodeType: Node>: GeneratorProtocol {
func generate(with context: BuildContext) -> IRValue {
fatalError("Not implemented")
}
let node: NodeType
init(node: NodeType) {
self.node = node
}
}
// MARK: Practice 6
extension Generator where NodeType == NumberNode {
func generate(with context: BuildContext) -> IRValue {
FloatType.double.constant(node.value)
}
}
extension Generator where NodeType == VariableNode {
func generate(with context: BuildContext) -> IRValue {
guard let variable = context.namedValues[node.identifier] else {
fatalError("Undefined variable named \(node.identifier)")
}
return variable
}
}
extension Generator where NodeType == BinaryExpressionNode {
func generate(with context: BuildContext) -> IRValue {
let lhs = generateIRValue(from: node.lhs, with: context)
let rhs = generateIRValue(from: node.rhs, with: context)
switch node.operator {
case .addition: return context.builder.buildAdd(lhs, rhs, name: "AdditionNode")
case .subtraction: return context.builder.buildSub(lhs, rhs, name: "SubtractionNode")
case .multication: return context.builder.buildMul(lhs, rhs, name: "multmp")
case .division: return context.builder.buildDiv(lhs, rhs, name: "DivisionNode")
case .equal:
let bool = context.builder.buildFCmp(lhs, rhs, .orderedEqual, name: "cmptmp")
return context.builder.buildIntToFP(bool, type: FloatType.double, signed: true)
case .lessThan:
let bool = context.builder.buildFCmp(lhs, rhs, .orderedLessThan, name: "cmptmp")
return context.builder.buildIntToFP(bool, type: FloatType.double, signed: true)
case .greaterThan:
let bool = context.builder.buildFCmp(lhs, rhs, .orderedGreaterThan, name: "cmptmp")
return context.builder.buildIntToFP(bool, type: FloatType.double, signed: true)
}
}
}
extension Generator where NodeType == FunctionNode {
func generate(with context: BuildContext) -> IRValue {
let argTypes: [IRType] = [FloatType.double]
let returnType: IRType = FloatType.double
let funcType = FunctionType(argTypes: argTypes, returnType: returnType)
let function = context.builder.addFunction(node.name, type: funcType)
let entryBasicBlock = function.appendBasicBlock(named: "entry")
context.builder.positionAtEnd(of: entryBasicBlock)
context.namedValues.removeAll()
for i in node.arguments.indices {
let name = node.arguments[i].variableName
context.namedValues[name] = function.parameters[i]
}
let functionBody: IRValue = generateIRValue(from: node.body, with: context)
context.builder.buildRet(functionBody)
return functionBody
}
}
extension Generator where NodeType == CallExpressionNode {
func generate(with context: BuildContext) -> IRValue {
let function = context.module.function(named: node.callee)!
let args: [IRValue] = node.arguments.map { generateIRValue(from: $0.value, with: context) }
return context.builder.buildCall(function, args: args, name: "calltmp")
}
}
extension Generator where NodeType == IfElseNode {
func generate(with context: BuildContext) -> IRValue {
let condition = generateIRValue(from: node.condition, with: context)
let bool = context.builder.buildFCmp(
condition, FloatType.double.constant(0), .orderedNotEqual, name: "ifcond")
let function = context.builder.insertBlock!.parent!
let local = context.builder.buildAlloca(type: FloatType.double, name: "local")
let thenBasicBlock = function.appendBasicBlock(named: "then")
let elseBasicBlock = function.appendBasicBlock(named: "else")
let mergeBasicBlock = function.appendBasicBlock(named: "merge")
context.builder.buildCondBr(condition: bool, then: thenBasicBlock, else: elseBasicBlock)
context.builder.positionAtEnd(of: thenBasicBlock)
let thenVal = generateIRValue(from: node.then, with: context)
context.builder.buildBr(mergeBasicBlock)
context.builder.positionAtEnd(of: elseBasicBlock)
let elseVal = generateIRValue(from: node.else!, with: context)
context.builder.buildBr(mergeBasicBlock)
context.builder.positionAtEnd(of: mergeBasicBlock)
let phi = context.builder.buildPhi(FloatType.double, name: "phi")
phi.addIncoming([(thenVal, thenBasicBlock), (elseVal, elseBasicBlock)])
context.builder.buildStore(phi, to: local)
return phi
}
}
extension Generator where NodeType == ReturnNode {
func generate(with context: BuildContext) -> IRValue {
if let body = node.body {
let returnValue = MinSwiftKit.generateIRValue(from: body, with: context)
return returnValue
} else {
return VoidType().null()
}
}
}
| 40.943038 | 99 | 0.678312 |
e4338a9c0484972386a344b38a0b29b2bc2d14c4
| 1,425 |
//
// AppDelegate.swift
// DeleteRowFromList
//
// Created by Edgar Nzokwe on 3/20/20.
// Copyright © 2020 Edgar Nzokwe. 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.5 | 179 | 0.748772 |
79f550c7b7fbb8564454022f4eb6df57313fe52b
| 203 |
//
// URLConstants.swift
// ivy-sdk
//
// Created by Praphin SP on 24/11/21.
//
import Foundation
struct URLConstants {
static let authURL = "/auth"
static let registerURL = "/register"
}
| 12.6875 | 40 | 0.64532 |
75dc3f6d7d1ccfce16f84ca1ea1005de1e521309
| 834 |
//
// ContinueImageView.swift
// Storytelling
//
// Created by VTStudio on 3/16/19.
// Copyright © 2019 VTStudio. All rights reserved.
//
import UIKit
class ContinueImageView: UIImageView {
let jumpingHeight: CGFloat = 20.0
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func startJumping() {
self.isHidden = false
UIView.animate(withDuration: 0.5, animations: {
self.frame.origin.y -= self.jumpingHeight
}) { _ in
UIView.animateKeyframes(withDuration: 1.0, delay: 0.25, options: [.autoreverse, .repeat], animations: {
self.frame.origin.y += self.jumpingHeight
})
}
}
func stopJumping() {
self.isHidden = true
self.layer.removeAllAnimations()
}
}
| 23.828571 | 115 | 0.594724 |
e04410d1d1e4a016bf4c93efb61064ba13ddc58f
| 841 |
//
// CLLocationCoordinate2D.swift
// Shared
//
// Created by Moi Gutierrez on 6/29/21.
//
import MapKit
extension CLLocationCoordinate2D: Equatable {
public static func == (lhs: CLLocationCoordinate2D, rhs: CLLocationCoordinate2D) -> Bool {
lhs.latitude == rhs.latitude &&
lhs.longitude == rhs.longitude
}
}
extension CLLocationCoordinate2D {
/// Returns distance from coordianate in meters.
/// - Parameter from: coordinate which will be used as end point.
/// - Returns: Returns distance in meters.
public func distance(from: CLLocationCoordinate2D) -> CLLocationDistance {
let from = CLLocation(latitude: from.latitude, longitude: from.longitude)
let to = CLLocation(latitude: self.latitude, longitude: self.longitude)
return from.distance(from: to)
}
}
| 30.035714 | 94 | 0.687277 |
1d131c45bae66edcb164c9ab0b01416394f71435
| 8,887 |
//
// PageTitle.swift
// PageMenu
//
// Created by Chen,Yalun on 2019/3/18.
// Copyright © 2019 Chen,Yalun. All rights reserved.
//
import UIKit
// 代理
protocol PageTitleDelegate : class {
func pageTitleDidSelected(pageTitle: PageTitle, pageTitleView: PageTitleView)
}
// 标题视图组件
class PageTitleView: UIView {
// 索引
var index: Int = 0
// 标题
var title: String?
// 渐变颜色
var color: UIColor? {
didSet {
label.textColor = color
}
}
// 样式
fileprivate var style: MenuStyle
// 选中状态
fileprivate var isSelected: Bool = false {
didSet { reloadState() }// 刷新数据
}
// 自身宽度
fileprivate var width: CGFloat {
return title?.size(withAttributes: [NSAttributedString.Key.font: font]).width ?? 0
}
// 字体大小
fileprivate var font: UIFont { return isSelected ? style.selectedFont : style.defaultFont }
// 字体颜色
fileprivate var fontColor: UIColor { return isSelected ? style.selectedColor : style.defaultColor }
// 点击回调
fileprivate var tapCallBack: ((_ view: PageTitleView) -> Void)?
private lazy var label: UILabel = {
let label = UILabel()
let gesture = UITapGestureRecognizer(target: self, action: #selector(action(_:)))
label.addGestureRecognizer(gesture)
label.isUserInteractionEnabled = true
return label
}()
init(title: String?, isSelected: Bool, style: MenuStyle) {
self.title = title
self.isSelected = isSelected
self.style = style
super.init(frame: CGRect.zero)
reloadState()
self.addSubview(label)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// 动态链接
@objc fileprivate func action(_ tap: UITapGestureRecognizer) {
if tapCallBack != nil {
tapCallBack!(self)
}
}
// 刷新数据
private func reloadState() {
label.text = title
label.textColor = fontColor
label.font = font
label.sizeToFit()
}
}
// 标题视图
class PageTitle: UIView {
// 代理
weak var delegate: PageTitleDelegate?
private var titleList: [String]
private lazy var scrollView: UIScrollView = {
var scrollView = UIScrollView(frame: bounds)
scrollView.showsHorizontalScrollIndicator = false
addSubview(scrollView)
return scrollView
}()
// 指示器
private lazy var lineView: UIView = {
var lineView = UIView()
lineView.backgroundColor = menuStyle.lineColor ?? menuStyle.selectedColor
lineView.layer.cornerRadius = menuStyle.lineCornerRadius
lineView.layer.masksToBounds = true
scrollView.addSubview(lineView)
return lineView
}()
// 样式
private var menuStyle: MenuStyle
// 当前选中标题
private var currentSelectedView: PageTitleView?
// 标题列表
private var titleViewList = [PageTitleView]()
init(frame: CGRect, menuStyle: MenuStyle, titleList: [String]) {
self.menuStyle = menuStyle
self.titleList = titleList
super.init(frame: frame)
setupSubViews()
}
private func setupSubViews() {
var totalWidth: CGFloat = 0
// 设置子控件
for (idx, title) in titleList.enumerated() {
let view = PageTitleView(title: title as String, isSelected: false, style: menuStyle)
view.index = idx
titleViewList.append(view)
let x = CGFloat(idx + 1) * menuStyle.margin + totalWidth
view.frame = CGRect(x: x, y: 0, width: view.width, height: frame.height - menuStyle.lineHeight)
totalWidth += view.width
scrollView.addSubview(view)
view.tapCallBack = { [weak self] view in
guard let self = self else { return }
self.changeToSelectedIndex(idx: view.index)
}
}
scrollView.contentSize = CGSize(width: totalWidth + CGFloat(titleList.count + 1) * menuStyle.margin, height: 0)
// 默认选中的索引 0
changeToSelectedIndex()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: 切换过程中需要调用的函数
extension PageTitle {
private func changeToSelectedIndex(idx: Int = 0, progress: CGFloat = 1) {
// 索引值越界
if idx > titleViewList.count - 1 || idx < 0 || titleViewList.count <= 0 { return }
var fromView, toView: PageTitleView
if currentSelectedView == nil {
fromView = titleViewList.first!
toView = fromView
} else {
fromView = currentSelectedView!
toView = titleViewList[idx]
// 同一个标题
if fromView == toView { return }
}
if menuStyle.lineHeight != 0 {
refreshBottomLineFrame(fromView.frame, toView.frame, progress)
}
if menuStyle.lineColorGradual {
refreshTitleViewColor(fromView, toView, progress)
}
if progress == 1 {
refreshTitleViewState(fromView, toView)
}
}
// 设置指示条frame
private func refreshBottomLineFrame(_ from: CGRect, _ to: CGRect, _ progress: CGFloat) {
var from = from
var to = to
let lineHeight = menuStyle.lineHeight
let lineWidth = menuStyle.lineWidth
let y = frame.height - lineHeight
let isFixedLineWidth = lineWidth != 0
let fromWidth = isFixedLineWidth ? lineWidth : from.width
let toWidth = isFixedLineWidth ? lineWidth : to.width
let fromMinX = isFixedLineWidth ? from.midX - lineWidth * 0.5 : from.minX
let fromMaxX = isFixedLineWidth ? fromMinX + lineWidth : from.maxX
let toMinX = isFixedLineWidth ? to.midX - lineWidth * 0.5 : to.minX
let toMaxX = isFixedLineWidth ? toMinX + lineWidth : to.maxX
from = CGRect(x: fromMinX, y: y, width: fromWidth, height: lineHeight)
to = CGRect(x: toMinX, y: y, width: toWidth, height: lineHeight)
let isToLeft = toMinX < fromMinX // 向左
if progress < 0.5 {
if isToLeft { // 向左移动
let offsetWidth = (fromMinX - toMinX) * 2 * progress
lineView.frame = CGRect(x: fromMinX - offsetWidth, y: y, width: fromMaxX - fromMinX + offsetWidth, height: lineHeight)
} else {
let offsetWidth = (toMaxX - fromMaxX) * 2 * progress
lineView.frame = CGRect(x: fromMinX, y: y, width:from.width + offsetWidth, height: lineHeight)
}
} else {
if isToLeft { // 向左移动
let offsetWidth = (fromMaxX - to.maxX) * (1 - (progress - 0.5) * 2)
lineView.frame = CGRect(x: toMinX, y: y, width:to.width + offsetWidth, height: lineHeight)
} else {
let offsetWidth = (toMinX - fromMinX) * (1 - (progress - 0.5) * 2)
lineView.frame = CGRect(x: toMinX - offsetWidth, y: y, width:toMaxX - toMinX + offsetWidth, height: lineHeight)
}
}
}
// 刷新标题状态
private func refreshTitleViewState(_ fromView: PageTitleView, _ toView: PageTitleView) {
// 更新currentSelectedView
currentSelectedView?.isSelected = false
toView.isSelected = true
currentSelectedView = toView
// 设置标题居中
let width = scrollView.bounds.width
let contentWidth = scrollView.contentSize.width
var offsetX = toView.center.x - width * 0.5
offsetX = max(offsetX, 0)
offsetX = min(contentWidth - width, offsetX)
if contentWidth <= width { // 保持居中
let viewWidth = CGFloat(titleViewList.last?.frame.maxX ?? 0) - CGFloat(titleViewList.first?.frame.minX ?? 0)
offsetX = -(width - viewWidth) * 0.5 + menuStyle.margin
}
scrollView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: true)
if delegate != nil {
delegate?.pageTitleDidSelected(pageTitle: self, pageTitleView: toView)
}
}
// 标题颜色渐变
private func refreshTitleViewColor(_ fromView: PageTitleView, _ toView: PageTitleView, _ progress: CGFloat) {
let toRGB = UIColor.rgbValue(menuStyle.selectedColor)
let fromRGB = UIColor.rgbValue(menuStyle.defaultColor)
let deltaRGB = (toRGB.0 - fromRGB.0, toRGB.1 - fromRGB.1, toRGB.2 - fromRGB.2)
fromView.color = UIColor(r: toRGB.0 - deltaRGB.0 * progress, g: toRGB.1 - deltaRGB.1 * progress, b: toRGB.2 - deltaRGB.2 * progress)
toView.color = UIColor(r: fromRGB.0 + deltaRGB.0 * progress, g: fromRGB.1 + deltaRGB.1 * progress, b: fromRGB.2 + deltaRGB.2 * progress)
}
}
// MARK: PageContentDelegate
extension PageTitle : PageContentDelegate {
func pageContentDidChange(pageContent: PageContent, targetIndex: Int, progress: CGFloat) {
changeToSelectedIndex(idx: targetIndex, progress: progress)
}
}
| 37.029167 | 144 | 0.616181 |
6accce7c2db2fc8c134e64b72f90425a5b8e44ee
| 2,282 |
//
// Dateformatter+UPenn.swift
// Change Request
//
// Created by Rashad Abdul-Salam on 10/26/18.
// Copyright © 2018 University of Pennsylvania Health System. All rights reserved.
//
import Foundation
private var cachedFormatters = [String : DateFormatter]()
extension DateFormatter {
enum DateFormat : String {
case ISO8601 = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"
case RFC3339 = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
case UNIX_EPOCH = "1970-01-01T00:00:00Z"
}
static func formatString(_ dateString: String, format: DateFormat = .ISO8601) -> String {
/*
* 1. Create date object from cached formatter,
* 2. Update to desired dateFormat
* 3. Set dateString from formatter
* 4. Reset cached formatter dateFormat
*/
let formatter = DateFormatter.cached(withFormat: format)
guard let date = formatter.date(from: dateString) else { return dateString }
formatter.dateFormat = "MMM d, yyyy h:mm a"
let dateString = formatter.string(from: date)
formatter.dateFormat = format.rawValue
return dateString
}
static func cached(withFormat format: DateFormat) -> DateFormatter {
if let cachedFormatter = cachedFormatters[format.rawValue] { return cachedFormatter }
let formatter = DateFormatter()
formatter.dateFormat = format.rawValue
formatter.locale = Locale(identifier: "en_US_POSIX")
cachedFormatters[format.rawValue] = formatter
return formatter
}
static func formatDate(_ date: Date) -> String {
let formatter = DateFormatter.cached(withFormat: .RFC3339)
formatter.timeStyle = DateFormatter.Style.medium //Set time style
formatter.dateStyle = DateFormatter.Style.medium //Set date style
formatter.timeZone = .current
let dateString = formatter.string(from: date)
return dateString
}
static func dateNowFormatted() -> String {
let date = self.getDateFromTimeInterval(Date().timeIntervalSince1970)
return self.formatDate(date)
}
}
private extension DateFormatter {
static func getDateFromTimeInterval(_ interval: TimeInterval) -> Date {
return Date(timeIntervalSince1970: interval)
}
}
| 36.222222 | 93 | 0.670026 |
e648ec2ca3b7a10846a7131b570d93bb17d52537
| 6,071 |
//
// MensaView.swift
// UStudy
//
// Created by Jann Schafranek on 06.02.20.
// Copyright © 2020 Jann Thomas. All rights reserved.
//
import SwiftUI
import SwiftUIRefresh
import SchafKit
struct MensaView: View {
@State private var isRefreshing = false
@State private var isInfoShown = false
@State private var isFilterShown = false
@ObservedObject var helper: MensaHelper
let startDate: Date
let endDate: Date
@State var date: Date
@State var hiddenMensas: [String] = []
init(account: Account) {
self.startDate = Date(timeIntervalSinceNow: 86400).startOfWeek
self.endDate = Date(timeIntervalSinceNow: 86400 * 8).endOfWeek
self._date = State(initialValue: startDate.timeIntervalSinceNow > 0 ? startDate : Date())
self.helper = MensaHelper(account: account)
self.helper.dateRequested = date
refreshMeals()
}
func refreshMeals() {
self.isRefreshing = true
helper.refreshMeals(completion: {
self.isRefreshing = false
})
}
var pullToRefresh : some View {
PullToRefresh(action: {
self.refreshMeals()
}, isShowing: $isRefreshing)
}
@ViewBuilder var overlay : some View {
if helper.mealGroups?.isEmpty == true {
HStack {
Spacer()
VStack {
Spacer()
Text("Kein Angebot gefunden.")
Spacer()
}
Spacer()
}
.background(Color.background)
} else {
EmptyView()
}
}
func sectionHeader(for group: MealGroup) -> some View {
return (group.name == nil) ? AnyView(EmptyView()) : AnyView(Text(group.name!))
}
func test(meal: Meal) -> some View {
MealView(meal: meal, mensa: helper.indexedMensas[meal.mensa]!, userGroup: helper.account.selectedUserGroup)
}
var list: some View {
List {
ForEach(helper.mealGroups ?? [], id: \.name) { group in
Section(header: self.sectionHeader(for: group)) {
ForEach(group.meals, id: \.name) { meal in
MealView(meal: meal, mensa: self.helper.indexedMensas[meal.mensa]!, userGroup: helper.account.selectedUserGroup)
}
}
}
.id(UUID())
}
}
func set(date: Date) {
if helper.dateRequested != date {
helper.mealGroups = nil
helper.dateRequested = date
self.date = date
refreshMeals()
}
}
var filterList: some View {
List {
ForEach(helper.mensas ?? [], id: \.id) { mensa in
HStack(spacing: 12) {
Image(systemName: mensa.icon ?? "house")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 24)
Text(mensa.name)
Spacer()
if !hiddenMensas.contains(mensa.id) {
Image(systemName: "checkmark")
.foregroundColor(.accentColor)
}
}
}
}
.navigationBarTitle("Filter", displayMode: .inline)
.navigationBarItems(leading:
HStack {
Button(action: {
self.set(date: Date())
}) {
Text("Fertig")
.fontWeight(.bold)
.font(.system(size: 18))
}
})
}
var body: some View {
NavigationView {
VStack(spacing: 0) {
ScrollView([.horizontal], showsIndicators: false) {
// TODO: Get values from JavaScript/JSON somehow
DateChooserView(startDate: startDate, endDate: endDate, selectedDate: self.$date, dateSelectionChanged: { date in
self.set(date: date)
})
}
.background(VisualEffectView(effect: UIBlurEffect(style: .regular)))
Color.nearGrayColor.frame(height: 0.25)
list
.background(pullToRefresh)
.overlay(overlay)
}
.navigationBarTitle("Mensa", displayMode: .inline)
.navigationBarItems(leading:
HStack {
Button(action: {
self.set(date: Date())
}) {
Text("Today")
.font(.system(size: 18))
}
.disabled((startDate.timeIntervalSinceNow > 0 && !Calendar.current.isDateInToday(startDate)) || Calendar.current.isDateInToday(date))
}, trailing:
HStack {
Button(action: {
isFilterShown = true
}) {
Image(systemName: "line.horizontal.3.decrease.circle")
.font(.system(size: 22))
}
.padding()
Button(action: {
self.isInfoShown = true
}) {
Image(systemName: "info.circle")
.font(.system(size: 22))
}
.sheet(isPresented: $isInfoShown) {
MensasInfo(mensas: self.helper.mensas!)
}
.disabled(self.helper.mensas == nil)
})
}
.sheet(isPresented: $isFilterShown) {
NavigationView {
filterList
.font(.system(size: 14))
}
}
}
}
/*struct MensaView_Previews: PreviewProvider {
static var previews: some View {
MensaView()
}
}*/
| 32.465241 | 153 | 0.470598 |
8755fc9772191c75a1c36f31e3801af5a2a2f00a
| 13,996 |
//
// ViewController.swift
// Slide for Reddit
//
// Created by Carlos Crane on 01/04/17.
// Copyright © 2016 Haptic Apps. All rights reserved.
//
import reddift
import SDWebImage
import Starscream
import UIKit
import YYText
class LiveThreadViewController: MediaViewController, UICollectionViewDelegate, WrappingFlowLayoutDelegate, UICollectionViewDataSource {
func headerOffset() -> Int {
return 0
}
var tableView: UICollectionView!
var id: String
init(id: String) {
self.id = id
super.init(nibName: nil, bundle: nil)
setBarColors(color: GMColor.red500Color())
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setToolbarHidden(true, animated: false)
socket?.connect()
UIApplication.shared.isIdleTimerDisabled = true
}
var flowLayout: WrappingFlowLayout = WrappingFlowLayout.init()
override func viewDidLoad() {
super.viewDidLoad()
flowLayout.delegate = self
let frame = self.view.bounds
self.tableView = UICollectionView(frame: frame, collectionViewLayout: flowLayout)
tableView.contentInset = UIEdgeInsets.init(top: 4, left: 0, bottom: 56, right: 0)
self.view = UIView.init(frame: CGRect.zero)
self.view.addSubview(tableView)
self.tableView.delegate = self
self.tableView.dataSource = self
self.tableView.register(LiveThreadUpdate.classForCoder(), forCellWithReuseIdentifier: "live")
tableView.backgroundColor = ColorUtil.theme.backgroundColor
session = (UIApplication.shared.delegate as! AppDelegate).session
refresh()
}
var session: Session?
var content = [JSONDictionary]()
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return content.count
}
func collectionView(_ tableView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let c = tableView.dequeueReusableCell(withReuseIdentifier: "live", for: indexPath) as! LiveThreadUpdate
c.setUpdate(rawJson: content[indexPath.row], parent: self, nav: self.navigationController, width: self.view.frame.size.width)
return c
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
socket?.disconnect()
UIApplication.shared.isIdleTimerDisabled = false
}
deinit {
UIApplication.shared.isIdleTimerDisabled = false
}
var doneOnce = false
func startPulse(_ complete: Bool) {
if !doneOnce {
doneOnce = true
var progressDot = UIView()
progressDot.alpha = 0.7
progressDot.backgroundColor = .clear
let startAngle = -CGFloat.pi / 2
let center = CGPoint (x: 20 / 2, y: 20 / 2)
let radius = CGFloat(20 / 2)
let arc = CGFloat.pi * CGFloat(2) * 1
let cPath = UIBezierPath()
cPath.move(to: center)
cPath.addLine(to: CGPoint(x: center.x + radius * cos(startAngle), y: center.y + radius * sin(startAngle)))
cPath.addArc(withCenter: center, radius: radius, startAngle: startAngle, endAngle: arc + startAngle, clockwise: true)
cPath.addLine(to: CGPoint(x: center.x, y: center.y))
let circleShape = CAShapeLayer()
circleShape.path = cPath.cgPath
circleShape.strokeColor = GMColor.red500Color().cgColor
circleShape.fillColor = GMColor.red500Color().cgColor
circleShape.lineWidth = 1.5
// add sublayer
for layer in progressDot.layer.sublayers ?? [CALayer]() {
layer.removeFromSuperlayer()
}
progressDot.layer.removeAllAnimations()
progressDot.layer.addSublayer(circleShape)
let pulseAnimation = CABasicAnimation(keyPath: "transform.scale")
pulseAnimation.duration = 0.5
pulseAnimation.toValue = 1.2
pulseAnimation.fromValue = 0.2
pulseAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
pulseAnimation.autoreverses = false
pulseAnimation.repeatCount = Float.greatestFiniteMagnitude
let fadeAnimation = CABasicAnimation(keyPath: "opacity")
fadeAnimation.duration = 0.5
fadeAnimation.toValue = 0
fadeAnimation.fromValue = 2.5
fadeAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
fadeAnimation.autoreverses = false
fadeAnimation.repeatCount = Float.greatestFiniteMagnitude
progressDot.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
let liveB = UIBarButtonItem.init(customView: progressDot)
let more = UIButton.init(type: .custom)
more.setImage(UIImage.init(named: "info")?.navIcon(), for: UIControl.State.normal)
more.addTarget(self, action: #selector(self.showMenu(_:)), for: UIControl.Event.touchUpInside)
more.frame = CGRect.init(x: 0, y: 0, width: 30, height: 30)
let moreB = UIBarButtonItem.init(customView: more)
if complete {
navigationItem.rightBarButtonItem = moreB
} else {
self.navigationItem.rightBarButtonItems = [moreB, liveB]
}
progressDot.layer.add(pulseAnimation, forKey: "scale")
progressDot.layer.add(fadeAnimation, forKey: "fade")
}
}
func collectionView(_ collectionView: UICollectionView, width: CGFloat, indexPath: IndexPath) -> CGSize {
let data = content[indexPath.row]
let itemWidth = width - 10
let id = data["id"] as! String
if estimatedHeights[id] == nil {
var content = NSMutableAttributedString(string: "u/\(data["author"] as! String) \(DateFormatter().timeSince(from: NSDate(timeIntervalSince1970: TimeInterval(data["created_utc"] as! Int)), numericDates: true))", attributes: [NSAttributedString.Key.foregroundColor: ColorUtil.theme.fontColor, NSAttributedString.Key.font: FontGenerator.boldFontOfSize(size: 14, submission: false)])
if let body = data["body_html"] as? String {
if !body.isEmpty() {
let html = body.unescapeHTML
content.append(NSAttributedString(string: "\n"))
//todo maybe link parsing here?
content.append(TextDisplayStackView.createAttributedChunk(baseHTML: html, fontSize: 16, submission: false, accentColor: ColorUtil.baseAccent, fontColor: ColorUtil.theme.fontColor, linksCallback: nil, indexCallback: nil))
}
}
var imageHeight = 0
if data["mobile_embeds"] != nil && !(data["mobile_embeds"] as? JSONArray)!.isEmpty {
if let embedsB = data["mobile_embeds"] as? JSONArray, let embeds = embedsB[0] as? JSONDictionary, let height = embeds["height"] as? Int, let width = embeds["width"] as? Int {
print(embedsB)
let ratio = Double(height) / Double(width)
let width = Double(itemWidth)
imageHeight = Int(width * ratio)
}
}
let size = CGSize(width: width - 18, height: CGFloat.greatestFiniteMagnitude)
let layout = YYTextLayout(containerSize: size, text: content)!
let infoHeight = layout.textBoundingSize.height
estimatedHeights[id] = CGFloat(24 + infoHeight + CGFloat(imageHeight))
}
return CGSize(width: itemWidth, height: estimatedHeights[id]!)
}
var estimatedHeights: [String: CGFloat] = [:]
func refresh() {
do {
try session?.getLiveThreadDetails(id, completion: { (result) in
switch result {
case .failure(let error):
print(error)
case .success(let rawdetails):
self.getOldThreads()
self.doInfo(((rawdetails as! JSONDictionary)["data"] as! JSONDictionary))
if !(((rawdetails as! JSONDictionary)["data"] as! JSONDictionary)["websocket_url"] is NSNull) {
self.setupWatcher(websocketUrl: ((rawdetails as! JSONDictionary)["data"] as! JSONDictionary)["websocket_url"] as! String)
}
}
})
} catch {
print(error)
}
}
func doInfo(_ json: JSONDictionary) {
self.baseData = json
self.title = (json["title"] as? String) ?? ""
self.startPulse((json["state"] as? String ?? "complete") == "complete")
}
var baseData: JSONDictionary?
@objc func showMenu(_ sender: AnyObject) {
let alert = UIAlertController.init(title: (baseData!["title"] as? String) ?? "", message: "\n\n\(baseData!["viewer_count"] as! Int) watching\n\n\n\(baseData!["description"] as! String)", preferredStyle: .alert)
alert.addAction(UIAlertAction.init(title: "Close", style: .cancel, handler: nil))
present(alert, animated: true)
}
func getOldThreads() {
do {
try session?.getCurrentThreads(id, completion: { (result) in
switch result {
case .failure(let error):
print(error)
case .success(let rawupdates):
for item in rawupdates {
self.content.append((item as! JSONDictionary)["data"] as! JSONDictionary)
}
self.doneLoading()
}
})
} catch {
}
}
var socket: WebSocket?
func setupWatcher(websocketUrl: String) {
socket = WebSocket(url: URL(string: websocketUrl)!)
//websocketDidConnect
socket!.onConnect = {
print("websocket is connected")
}
//websocketDidDisconnect
socket!.onDisconnect = { (error: Error?) in
print("websocket is disconnected: \(error?.localizedDescription ?? "")")
}
//websocketDidReceiveMessage
socket!.onText = { (text: String) in
print("got some text: \(text)")
do {
let text = try JSONSerialization.jsonObject(with: text.data(using: .utf8)!, options: [])
if (text as! JSONDictionary)["type"] as! String == "update" {
if let payload = (text as! JSONDictionary)["payload"] as? JSONDictionary, let data = payload["data"] as? JSONDictionary {
DispatchQueue.main.async {
self.content.insert(data, at: 0)
self.flowLayout.reset(modal: self.presentingViewController != nil)
let contentHeight = self.tableView.contentSize.height
let offsetY = self.tableView.contentOffset.y
let bottomOffset = contentHeight - offsetY
if #available(iOS 11.0, *) {
CATransaction.begin()
CATransaction.setDisableActions(true)
self.tableView.performBatchUpdates({
self.tableView.insertItems(at: [IndexPath(row: 0, section: 0)])
}, completion: { (done) in
self.tableView.contentOffset = CGPoint(x: 0, y: self.tableView.contentSize.height - bottomOffset)
CATransaction.commit()
})
} else {
self.tableView.insertItems(at: [IndexPath(row: 0, section: 0)])
}
}
}
}
} catch {
}
}
//websocketDidReceiveData
socket!.onData = { (data: Data) in
print("got some data: \(data.count)")
}
//you could do onPong as well.
socket!.connect()
}
func doneLoading() {
DispatchQueue.main.async {
self.flowLayout.reset(modal: self.presentingViewController != nil)
self.tableView.reloadData()
}
}
}
// Helper function inserted by Swift 4.2 migrator.
private func convertToOptionalNSAttributedStringKeyDictionary(_ input: [String: Any]?) -> [NSAttributedString.Key: Any]? {
guard let input = input else { return nil }
return Dictionary(uniqueKeysWithValues: input.map { key, value in (NSAttributedString.Key(rawValue: key), value) })
}
// Helper function inserted by Swift 4.2 migrator.
private func convertFromNSAttributedStringKey(_ input: NSAttributedString.Key) -> String {
return input.rawValue
}
// Helper function inserted by Swift 4.2 migrator.
private func convertToNSAttributedStringDocumentReadingOptionKeyDictionary(_ input: [String: Any]) -> [NSAttributedString.DocumentReadingOptionKey: Any] {
return Dictionary(uniqueKeysWithValues: input.map { key, value in (NSAttributedString.DocumentReadingOptionKey(rawValue: key), value) })
}
// Helper function inserted by Swift 4.2 migrator.
private func convertFromNSAttributedStringDocumentAttributeKey(_ input: NSAttributedString.DocumentAttributeKey) -> String {
return input.rawValue
}
// Helper function inserted by Swift 4.2 migrator.
private func convertFromNSAttributedStringDocumentType(_ input: NSAttributedString.DocumentType) -> String {
return input.rawValue
}
| 43.331269 | 391 | 0.600672 |
4821dff1f7ebc6f462ed5c3ed08e32c3a31a2871
| 888 |
//
// VisionProcessor.swift
// Anime-fy Yourself
//
// Created by Yonatan Mittlefehldt on 2021-12-07.
//
import CoreImage
import Vision
/// Helpful protocol to conform Vision-based processors/detectors
protocol VisionProcessor {
func perform(_ request: VNRequest, on image: CVPixelBuffer) throws -> VNRequest
}
extension VisionProcessor {
/// Performs a request on an input `CVPixelBuffer`
/// - Parameters:
/// - request: Vision request to perform
/// - image: input image
/// - Throws: rethrows the error from the Vision framework
/// - Returns: the Vision request with the results field populated
func perform(_ request: VNRequest, on image: CVPixelBuffer) throws -> VNRequest {
let requestHandler = VNImageRequestHandler(cvPixelBuffer: image, options: [:])
try requestHandler.perform([request])
return request
}
}
| 30.62069 | 86 | 0.699324 |
1af867edf279b7ac4075fc8edf8655ef3e6c09b0
| 6,094 |
//
// RegularExpressionSyntaxType.swift
//
// CotEditor
// https://coteditor.com
//
// Created by 1024jp on 2018-04-02.
//
// ---------------------------------------------------------------------------
//
// © 2018-2020 1024jp
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation.NSRegularExpression
enum RegularExpressionParseMode {
case search
case replacement(unescapes: Bool)
}
enum RegularExpressionSyntaxType {
case character
case backReference
case symbol
case quantifier
case anchor
static let priority: [RegularExpressionSyntaxType] = [
.character,
.backReference,
.symbol,
.quantifier,
.anchor,
]
// MARK: Public Methods
func ranges(in string: String, mode: RegularExpressionParseMode) -> [NSRange] {
var ranges = self.patterns(for: mode)
.map { try! NSRegularExpression(pattern: $0) }
.flatMap { $0.matches(in: string, range: string.nsRange) }
.map(\.range)
if self == .character, case .search = mode {
ranges += string.ranges(bracePair: BracePair("[", "]"))
.map { (string[$0.lowerBound] == "^") ? string.index(after: $0.lowerBound)..<$0.upperBound : $0 }
.map { NSRange($0, in: string) }
}
return ranges
}
// MARK: Private Methods
private func patterns(for mode: RegularExpressionParseMode) -> [String] {
// regex pattern to avoid matching escaped character
let escapeIgnorer = "(?<!\\\\)(?:\\\\\\\\)*"
switch mode {
case .search:
switch self {
case .character:
// -> [abc] will be extracted in ranges(in:) since regex cannot parse nested []
return [
escapeIgnorer + "\\.", // .
escapeIgnorer + "\\\\" + "[^AbGZzQE1-9]", // all escaped characters
escapeIgnorer + "\\\\" + "[sdDefnrsStwWX]", // \s, \d, ...
escapeIgnorer + "\\\\" + "v", // \v
escapeIgnorer + "\\\\" + "\\\\", // \\
escapeIgnorer + "\\\\" + "c[a-z]", // \cX (control)
escapeIgnorer + "\\\\" + "N\\{[a-zA-Z0-9 ]+\\}", // \N{UNICODE CHARACTER NAME}
escapeIgnorer + "\\\\" + "[pP]\\{[a-zA-Z0-9 ]+\\}", // \p{UNICODE PROPERTY NAME}
escapeIgnorer + "\\\\" + "u[0-9a-fA-F]{4}", // \uhhhh (h: hex)
escapeIgnorer + "\\\\" + "U[0-9a-fA-F]{8}", // \Uhhhhhhhh (h: hex)
escapeIgnorer + "\\\\" + "x\\{[0-9a-fA-F]{1,6}\\}", // \x{hhhh} (h: hex)
escapeIgnorer + "\\\\" + "x[0-9a-fA-F]{2}", // \xhh (h: hex)
escapeIgnorer + "\\\\" + "0[0-7]{1,3}", // \0ooo (o: octal)
]
case .backReference:
return [
escapeIgnorer + "\\$[0-9]", // $0
escapeIgnorer + "\\\\[1-9]", // \1
]
case .symbol:
return [
escapeIgnorer + "\\(\\?(:|>|#|=|!|<=|<!|-?[ismwx]+:?)", // (?...
escapeIgnorer + "[()|]", // () |
escapeIgnorer + "(\\[\\^?|\\])", // [^ ]
escapeIgnorer + "\\\\[QE]", // \Q ... \E
]
case .quantifier:
// -> `?` is also used for .symbol.
return [
escapeIgnorer + "[*+?]", // * + ?
escapeIgnorer + "\\{[0-9]+(,[0-9]*)?\\}", // {n,m}
]
case .anchor:
// -> `^` is also used for [^abc].
// -> `$` is also used for .backReference.
return [
escapeIgnorer + "[$^]", // ^ $
escapeIgnorer + "\\\\[AbGZz]", // \A, \b, ...
]
}
case .replacement(let unescapes):
switch self {
case .character where unescapes:
return [escapeIgnorer + "\\\\[$0tnr\"'\\\\]"]
case .backReference:
return [escapeIgnorer + "\\$[0-9]"]
default:
return []
}
}
}
}
private extension StringProtocol {
/// ranges of inside of the most outer pairs of brace
func ranges(bracePair: BracePair) -> [Range<Index>] {
var index = self.startIndex
var braceRanges: [Range<Index>] = []
while index != self.endIndex {
guard self[index] == bracePair.begin, !self.isCharacterEscaped(at: index) else {
index = self.index(after: index)
continue
}
guard let endIndex = self.indexOfBracePair(beginIndex: index, pair: bracePair) else { break }
braceRanges.append(self.index(after: index)..<endIndex)
index = self.index(after: endIndex)
}
return braceRanges
}
}
| 36.27381 | 113 | 0.428782 |
d52f8d0556728ccff9ae9c187b65325a5135f9a3
| 2,293 |
//
// SocketLogger.swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 4/11/15.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public protocol SocketLogger: class {
/// Whether to log or not
var log: Bool {get set}
/// Normal log messages
func log(message: String, type: String, args: AnyObject...)
/// Error Messages
func error(message: String, type: String, args: AnyObject...)
}
public extension SocketLogger {
func log(message: String, type: String, args: AnyObject...) {
abstractLog("Log", message: message, type: type, args: args)
}
func error(message: String, type: String, args: AnyObject...) {
abstractLog("ERROR", message: message, type: type, args: args)
}
private func abstractLog(logType: String, message: String, type: String, args: [AnyObject]) {
guard log else { return }
let newArgs = args.map {arg -> CVarArgType in String(arg)}
let replaced = String(format: message, arguments: newArgs)
NSLog("%@ %@: %@", logType, type, replaced)
}
}
class DefaultSocketLogger: SocketLogger {
static var Logger: SocketLogger = DefaultSocketLogger()
var log = false
}
| 36.983871 | 97 | 0.691234 |
dd79df931d6ecaa9e9147a22c7aa6917d865a93e
| 252 |
//
// UIView+Extension.swift
// Yelp
//
// Created by Nana on 4/8/17.
// Copyright © 2017 Timothy Lee. All rights reserved.
//
import UIKit
extension UIView {
var firstLabel: UILabel? {
return self.viewWithTag(1) as? UILabel
}
}
| 14.823529 | 54 | 0.634921 |
5d76c77db91b5db47122694a1e57bb204ebfc244
| 4,026 |
//
// DecodingStrategy.swift
//
//
// Created by Max Obermeier on 28.06.21.
//
import Foundation
import Apodini
import ApodiniUtils
// MARK: DecodingStrategy
/// A strategy describing how a certain Apodini `Parameter` can be decoded from
/// a fixed ``Input`` type.
///
/// A ``DecodingStrategy`` can be used to transform a certain ``Input`` to an
/// Apodini `Request`. While the ``DecodingStrategy`` only helps implementing
/// the Apodini `Request/retrieveParameter(_:)`, a ``RequestBasis`` can
/// be used to provide the missing information. This proccess is implemented in
/// ``DecodingStrategy/decodeRequest(from:with:with:)``.
public protocol DecodingStrategy {
/// The type which the ``ParameterDecodingStrategy``s returned by ``strategy(for:)``
/// take as an input for ``ParameterDecodingStrategy/decode(from:)``.
associatedtype Input = Data
/// The actual strategy for determining a suitable ``ParameterDecodingStrategy`` for the
/// given `parameter`.
func strategy<Element: Decodable>(for parameter: Parameter<Element>) -> AnyParameterDecodingStrategy<Element, Input>
}
// MARK: AnyDecodingStrategy
public extension DecodingStrategy {
/// Erases the type from this ``DecodingStrategy``.
var typeErased: AnyDecodingStrategy<Input> {
AnyDecodingStrategy(self)
}
}
/// A type-erased wrapper around any ``DecodingStrategy``.
public struct AnyDecodingStrategy<I>: DecodingStrategy {
private let caller: DecodingStrategyCaller
init<S: DecodingStrategy>(_ strategy: S) where S.Input == I {
self.caller = SomeDecodingStrategyCaller(strategy: strategy)
}
public func strategy<Element>(for parameter: Parameter<Element>)
-> AnyParameterDecodingStrategy<Element, I> where Element: Decodable, Element: Encodable {
caller.call(with: parameter)
}
}
private protocol DecodingStrategyCaller {
func call<E: Decodable, I>(with parameter: Parameter<E>) -> AnyParameterDecodingStrategy<E, I>
}
private struct SomeDecodingStrategyCaller<S: DecodingStrategy>: DecodingStrategyCaller {
let strategy: S
func call<E: Decodable, I>(with parameter: Parameter<E>) -> AnyParameterDecodingStrategy<E, I> {
guard let parameterStrategy = strategy.strategy(for: parameter) as? AnyParameterDecodingStrategy<E, I> else {
fatalError("'SomeDecodingStrategyCaller' was used with wrong input type (\(I.self) instead of \(S.Input.self))")
}
return parameterStrategy
}
}
// MARK: TransformingStrategy
/// A ``DecodingStrategy`` that forms a transition between a wrapped ``DecodingStrategy`` `S`
/// and a parent ``DecodingStrategy`` with ``DecodingStrategy/Input`` type `I`.
///
/// This strategy allows for reuse of ``DecodingStrategy`` with a more basic ``DecodingStrategy/Input`` than
/// the one you are acutally using. E.g. many of the predefined strategies have input type `Data`.
/// If your input type is a complete request, you can probably reuse those predefined strategies by extracting the body
/// from the request.
public struct TransformingStrategy<S: DecodingStrategy, I>: DecodingStrategy {
private let transformer: (I) throws -> S.Input
private let strategy: S
init(_ strategy: S, using transformer: @escaping (I) throws -> S.Input) {
self.strategy = strategy
self.transformer = transformer
}
public func strategy<Element>(for parameter: Parameter<Element>)
-> AnyParameterDecodingStrategy<Element, I> where Element: Decodable, Element: Encodable {
TransformingParameterStrategy(strategy.strategy(for: parameter), using: transformer).typeErased
}
}
public extension DecodingStrategy {
/// Create a ``TransformingStrategy`` that mediates between this ``DecodingStrategy``
/// and a parent with input type `I`.
func transformed<I>(_ transformer: @escaping (I) throws -> Self.Input) -> TransformingStrategy<Self, I> {
TransformingStrategy(self, using: transformer)
}
}
| 38.711538 | 124 | 0.715102 |
ffa7c0228a4f78683b94cff20cb17b166168ab3b
| 4,765 |
//
// URLRouterTestCase.swift
// DispatchCenter
//
// Created by steven on 2021/2/19.
//
import XCTest
@testable import DispatchCenter
class URLRouterTestCase: BaseTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testWithoutparameter() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
let url = "http://animate"
container.register(url: url) { (resolve, parameter) -> Dog in
guard let param = parameter else { return Dog.create() }
let name = param["name"]!
let age = Int(param["age"]!)!
let dog = Dog.create(["name": name, "age": age])
return dog
}
let resolveURL = "http://animate"
let dog: Dog? = container.openURL(url: resolveURL)
XCTAssertNotNil(dog)
XCTAssertNotEqual(dog?.name, "li")
}
func testWithQueryParameter() throws {
let url = "http://animate"
container.register(url: url) { (resolve, parameter) -> Dog in
guard let param = parameter else { return Dog.create() }
let name = param["name"]!
let age = Int(param["age"]!)!
let dog = Dog.create(["name": name, "age": age])
return dog
}
let resolveURL = "http://animate?name=li&age=1"
let dog = container.openURL(url: resolveURL, serviceType: Dog.self)
XCTAssertNotNil(dog)
XCTAssertEqual(dog?.name, "li")
XCTAssertEqual(dog?.age, 1)
}
func testWithURLComponents() throws {
let urlStr = "http://animate?name=lv&age=1"
let url = URL(string: urlStr)
XCTAssertNotNil(url)
XCTAssertEqual(url?.baseURL, nil)
let urlStr2 = "http://nengxuehui.cn/animate?name=lv&age=1"
let url2 = URL(string: urlStr2)
XCTAssertEqual(url2?.host, "nengxuehui.cn")
let baseURL = URL(string: "http://server/foo/")!
let url3 = URL(string: "bar/file.html", relativeTo: baseURL)!
XCTAssertEqual(url3.absoluteString, "http://server/foo/bar/file.html")
let comp1 = URLComponents(url: url3, resolvingAgainstBaseURL: false)!
XCTAssertEqual(comp1.string!, "bar/file.html")
let comp2 = URLComponents(url: url3, resolvingAgainstBaseURL: true)!
XCTAssertEqual(comp2.string!, "http://server/foo/bar/file.html")
}
// func testPerformanceExample() throws {
// // This is an example of a performance test case.
// self.measure {
// // Put the code you want to measure the time of here.
// }
// }
func testWithUnregister() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
let url = "http://animate"
let router = URLRouter.init()
_ = router.register(url: url) { (resolver, parameter) -> Dog in
guard let param = parameter else { return Dog([:]) }
let name = param["name"]!
let age = Int(param["age"]!)!
let dog = Dog.init(["name": name, "age": age])
return dog
}
_ = router.unregister(url: url)
let dog: Dog? = router.resolve(url: url)
XCTAssertNil(dog)
}
func testWithCanOpenURL() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
let url = "http://animate"
let router = URLRouter.init()
_ = router.register(url: url) { (resolver, parameter) -> Dog in
guard let param = parameter else { return Dog([:]) }
let name = param["name"]!
let age = Int(param["age"]!)!
let dog = Dog.init(["name": name, "age": age])
return dog
}
let isCan = router.canOpenURL(url: url)
XCTAssertTrue(isCan)
let url2 = "http://animate?name=elephant&age=2"
let isCan2 = router.canOpenURL(url: url2)
XCTAssertFalse(isCan2)
let resolveURL = "http://animate?name=elephant&age=2"
let isCan3 = router.canOpenURL(url: resolveURL)
XCTAssertFalse(isCan3)
}
}
| 35.036765 | 111 | 0.576705 |
72653a4ddc40ae134568f0fca00a8a761b70880e
| 1,981 |
/// Copyright (c) 2020 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 Foundation
import ReSwift
struct GettingUsersLocationActions {
struct FailedGettingUsersLocation: Action {
// MARK: - Properties
let errorMessage: ErrorMessage
}
struct FinishedPresentingError: FinishedPresentingErrorAction {
// MARK: - Properties
let errorMessage: ErrorMessage
}
}
| 43.065217 | 83 | 0.757193 |
e643eee326460363f359835cb066952cfa41a08e
| 1,414 |
//
// ConstructorRouter.swift
// ARQuest
//
// Created by Anton Poltoratskyi on 15.04.2018.
// Copyright © 2018 Anton Poltoratskyi. All rights reserved.
//
import UIKit
final class ConstructorRouter: Router, ConstructorRouterInput {
weak var viewController: UIViewController!
weak var output: ConstructorRouterOutput?
func showTaskCreator() {
let module = TaskBuilderAssembly().build()
module.input.output = self
viewController.navigationController?.pushViewController(module.view, animated: true)
}
func showConstructorFinish(for quest: Quest, code: String) {
let module = ConstructorFinishAssembly(quest: quest, code: code).build()
viewController.navigationController?.pushViewController(module.view, animated: true)
}
func showQuestInfoPopup(delegate: QuestInfoPopupModuleOutput) {
let module = QuestInfoPopupAssembly().build()
module.input.output = delegate
module.view.modalTransitionStyle = .crossDissolve
module.view.modalPresentationStyle = .overCurrentContext
viewController.present(module.view, animated: true, completion: nil)
}
}
extension ConstructorRouter: TaskBuilderModuleOutput {
func taskBuilderModule(_ moduleInput: TaskBuilderModuleInput, didCreateTask task: Task) {
output?.didCreateTask(task)
moduleInput.dismiss()
}
}
| 32.136364 | 93 | 0.713579 |
c114cd63d43667c5701c04ad4dc962b602b915da
| 5,060 |
//
// WYMenu.swift
// HostsManager
//
// Created by wenyou on 2016/12/26.
// Copyright © 2016年 wenyou. All rights reserved.
//
import AppKit
class StatusMenu: NSMenu {
weak var statusItem: NSStatusItem?
var popover: NSPopover = {
let popover = NSPopover.init()
popover.contentViewController = {
let controller = PopoverViewController()
controller.popover = popover
return controller
}()
return popover
}()
init(statusItem: NSStatusItem?) {
super.init(title: "")
self.statusItem = statusItem
delegate = self
}
required init(coder decoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - private
func addDefaultItem() {
addItem(NSMenuItem.separator())
addItem({
let menuItem = NSMenuItem(title: "Edit Hosts", action: #selector(StatusMenu.editClicked(_:)), keyEquivalent: "")
menuItem.target = self
return menuItem
}())
addItem({
let menuItem = NSMenuItem(title: "Preferences...", action: #selector(StatusMenu.settingClicked(_:)), keyEquivalent: "")
menuItem.target = self
return menuItem
}())
addItem(NSMenuItem.separator())
addItem(withTitle: "About \(ProcessInfo.processInfo.processName)", action: #selector(NSApp.orderFrontStandardAboutPanel(_:)), keyEquivalent: "")
addItem(withTitle: "Quit \(ProcessInfo.processInfo.processName)", action: #selector(NSApp.terminate(_:)), keyEquivalent: "")
}
func editClicked(_ sender: NSMenuItem) {
NSRunningApplication.current().activate(options: [.activateIgnoringOtherApps])
NSApp.windows.forEach { (window) in
if let win = window as? SettingWindow {
win.toolbarItemSelected(identifier: .edit)
win.center()
win.makeKeyAndOrderFront(self)
return
}
}
}
func settingClicked(_ sender: NSMenuItem) { // 唤起 window 切换至 setting controller
NSRunningApplication.current().activate(options: [.activateIgnoringOtherApps])
NSApp.windows.forEach { (window) in
if let win = window as? SettingWindow {
win.toolbarItemSelected(identifier: .setting)
win.center()
win.makeKeyAndOrderFront(self)
return
}
}
}
func groupClicked(_ sender: NSMenuItem) {
let filePermissions = FilePermissions.sharedInstance
if !filePermissions.hostFileWritePermissionsCheck() || !filePermissions.bookmarkCheck() {
return
}
let dataManager = HostDataManager.sharedInstance
let group = dataManager.groups[sender.tag - 100]
group.selected = !group.selected
dataManager.updateGroupData()
HostsFileManager.sharedInstance.writeContentToFile(content: dataManager.groups)
NotificationCenter.default.post(name: .WYStatusMenuUpdateHosts, object: nil)
AlertPanel.show("hosts 文件已同步")
}
}
extension StatusMenu: NSMenuDelegate {
func menuWillOpen(_ menu: NSMenu) { // 开启时初始化 menu
removeAllItems()
let dataManager = HostDataManager.sharedInstance
for index in 0 ..< dataManager.groups.count {
let group = dataManager.groups[index]
addItem({
let menuItem = NSMenuItem.init(title: group.name!, action: #selector(StatusMenu.groupClicked(_:)), keyEquivalent: "")
menuItem.tag = index + 100
menuItem.target = self
if group.selected {
menuItem.state = NSOnState
}
return menuItem
}())
}
addDefaultItem()
}
func menuDidClose(_ menu: NSMenu) { // 关闭时关闭浮层
if popover.isShown {
popover.performClose(nil)
}
}
func menu(_ menu: NSMenu, willHighlight item: NSMenuItem?) { // 鼠标浮动变更时改变浮层显示内容
if let menuItem = item, menuItem.tag >= 100, let button = statusItem?.button {
let group = HostDataManager.sharedInstance.groups[(menuItem.tag - 100)]
var string = ""
group.hosts.forEach({ (host) in
string.append((string.characters.count == 0 ? "" : "\n") + "\(host.ip) \(host.domain)")
})
if !popover.isShown {
popover.show(relativeTo: button.bounds, of: button, preferredEdge: .minX)
}
// 此行代码放在下边是因为第一次时, controller viewWillApper 之前调用 fittingSize 返回结果不对
if let controller = popover.contentViewController as? PopoverViewController {
controller.setText(string: string)
}
} else {
if popover.isShown {
popover.performClose(nil)
}
}
}
}
extension Notification.Name {
static let WYStatusMenuUpdateHosts = Notification.Name("StatusMenuUpdateHosts")
}
| 35.138889 | 152 | 0.598221 |
1a25fa063315b5410e68c887169c06613c63874a
| 572 |
//
// ShortcutsBarVM.swift
// OnlySwitch
//
// Created by Jacklandrin on 2022/1/2.
//
import Foundation
class ShortcutsBarVM:ObservableObject {
@Published var name:String
@Published var processing:Bool = false
init(name:String) {
self.name = name
}
func runShortCut() {
processing = true
Task{
let _ = await operateCMD()
DispatchQueue.main.async {
self.processing = false
}
}
}
func operateCMD() async -> Bool {
return true
}
}
| 17.875 | 42 | 0.547203 |
095f5ce7d8ab753c4a537204d8f633e897336093
| 519 |
import UIKit
public struct Utils {
public static func pathForCircleThatContains(rect: CGRect) -> CGPath {
let size = rect.smallestContainingSquare
.size
.rescale(sqrt(2))
return UIBezierPath(ovalIn: CGRect(centre: rect.centre, size: size)).cgPath
}
public static func pathForCircleInRect(rect: CGRect, scaled: CGFloat) -> CGPath {
let size = rect.size.rescale(scaled)
return UIBezierPath(ovalIn: CGRect(centre: rect.centre, size: size)).cgPath
}
}
| 30.529412 | 83 | 0.67052 |
692864511c119f2235b64485734ce77ab5c2c857
| 1,411 |
//
// AppDelegate.swift
// collector
//
// Created by Gabriel Coelho on 1/23/20.
// Copyright © 2020 Gabe. 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.131579 | 179 | 0.746988 |
89cd278deec6a17d5331d5496f00195629172f59
| 407 |
// swift-tools-version:5.3
import PackageDescription
let package = Package(
name: "ISHPullUp",
platforms: [
.iOS(.v8)
],
products: [
.library(
name: "ISHPullUp",
targets: ["ISHPullUp"]
),
],
targets: [
.target(
name: "ISHPullUp",
path: "ISHPullUp",
publicHeadersPath: "."
)
]
)
| 17.695652 | 34 | 0.459459 |
dbcccbf3740a9fe16dd14fbae33d4d572cb189d1
| 2,674 |
//
// CGPathConvertable.swift
// LMAnimatedTransition
//
// Created by 刘明 on 2019/3/15.
// Copyright © 2019 com.ming. All rights reserved.
//
import UIKit
public typealias Shape = CGPath
public typealias MutableShape = CGMutablePath
public protocol ShapeConvertable {
func asShape() -> Shape
}
extension ShapeConvertable {
public func asMutableShape() -> MutableShape {
return asShape().asMutableShape()
}
}
extension Shape: ShapeConvertable {
public func asShape() -> Shape {
return self
}
}
extension UIBezierPath: ShapeConvertable {
public func asShape() -> Shape {
return cgPath
}
}
// MARK
/// a ShapeProducer can conbine to a MutableShape
public protocol ShapeComposable {
func asMutableShape() -> MutableShape
func compose(other: ShapeConvertable) -> MutableShape
}
extension ShapeComposable where Self: Shape {
public func asMutableShape() -> MutableShape {
let mutl = MutableShape()
mutl.addPath(self)
return mutl
}
public func compose(other: ShapeConvertable) -> MutableShape {
let mult = asMutableShape()
mult.addPath(asShape().asShape())
return mult
}
}
extension ShapeComposable where Self: MutableShape {
public func asMutableShape() -> MutableShape {
return self
}
public func compose(other: ShapeConvertable) -> MutableShape {
addPath(other.asShape())
return self
}
public func compose(shapeMaker execute: () -> ShapeConvertable) -> MutableShape {
return compose(other: execute())
}
}
extension Shape: ShapeComposable {
public func compose(anyOtherShapes shapes: [ShapeConvertable]) -> MutableShape {
return shapes.reduce(asMutableShape()) { $0.compose(other: $1) }
}
}
//MARK: -
/// draw one shape or amount of shape into a CAShapeLayer instance
extension CAShapeLayer {
public func draw(anyShape: ShapeConvertable) -> Void {
self.path = anyShape.asShape()
}
public func draw(anyShapes: [ShapeConvertable],
into aMutableShape: MutableShape? = nil) -> Void {
draw(anyShape: (aMutableShape ?? MutableShape()).compose(anyOtherShapes: anyShapes))
}
public func draw(shapeMaker execute: () -> ShapeConvertable) -> Void {
draw(anyShape: execute())
}
public func drawInherit(shapeMaker execute: () -> ShapeConvertable) -> Void {
if let old = path?.copy() {
draw(anyShape: old.asMutableShape().compose(shapeMaker: execute))
}else {
draw(shapeMaker: execute)
}
}
}
| 24.53211 | 92 | 0.641735 |
f53313e4bedcbe38a4f6c5767021c71331c6e19b
| 4,650 |
//
// ContactView.swift
// ApplozicSwift
//
// Created by Shivam Pokhriyal on 16/04/19.
//
import Contacts
struct ContactModel {
let identifier: String
let contact: CNContact
init(identifier: String, contact: CNContact) {
self.identifier = identifier
self.contact = contact
}
}
class ContactView: UIView {
struct Padding {
struct ContactImage {
static let left: CGFloat = 10
static let width: CGFloat = 30
static let height: CGFloat = 30
}
struct ContactName {
static let left: CGFloat = 10
static let right: CGFloat = 10
}
struct ContactSaveIcon {
static let right: CGFloat = 10
static let width: CGFloat = 10
static let height: CGFloat = 15
}
static let height: CGFloat = 50
}
let contactImage: UIImageView = {
let imageView = UIImageView()
imageView.layer.cornerRadius = 15
imageView.clipsToBounds = true
imageView.contentMode = .scaleToFill
return imageView
}()
let contactName: UILabel = {
let label = UILabel()
label.numberOfLines = 1
label.lineBreakMode = .byTruncatingTail
label.font = UIFont(name: "HelveticaNeue", size: 17)
return label
}()
let contactSaveIcon: UIButton = {
let button = UIButton()
let image = UIImage(
named: "icon_arrow",
in: Bundle.applozic,
compatibleWith: nil)?
.withRenderingMode(.alwaysTemplate)
button.setImage(image, for: .normal)
return button
}()
var contactSelected: ((ContactModel) -> Void)?
var contactModel: ContactModel!
override init(frame: CGRect) {
super.init(frame: frame)
setupConstraints()
setTarget()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setColorIn(text: UIColor, background: UIColor) {
contactName.textColor = text
contactSaveIcon.tintColor = text
backgroundColor = background
}
func update(contactModel: ContactModel) {
self.contactModel = contactModel
let contact = contactModel.contact
contactName.text = "\(contact.givenName) \(contact.familyName)"
guard
let data = contact.imageData,
let image = UIImage(data: data)
else {
self.contactImage.image = UIImage(named: "placeholder", in: Bundle.applozic, compatibleWith: nil)
return
}
contactImage.image = image
}
class func height() -> CGFloat {
return Padding.height
}
@objc func tapped() {
guard let contactSelected = contactSelected else {
return
}
contactSelected(contactModel)
}
private func setupConstraints() {
layer.cornerRadius = 10
clipsToBounds = true
heightAnchor.constraint(equalToConstant: Padding.height).isActive = true
addViewsForAutolayout(views: [contactImage, contactName, contactSaveIcon])
contactImage.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: Padding.ContactImage.left).isActive = true
contactImage.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
contactImage.widthAnchor.constraint(equalToConstant: Padding.ContactImage.width).isActive = true
contactImage.heightAnchor.constraint(equalToConstant: Padding.ContactImage.height).isActive = true
contactSaveIcon.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -Padding.ContactSaveIcon.right).isActive = true
contactSaveIcon.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
contactSaveIcon.widthAnchor.constraint(equalToConstant: Padding.ContactSaveIcon.width).isActive = true
contactSaveIcon.heightAnchor.constraint(equalToConstant: Padding.ContactSaveIcon.height).isActive = true
contactName.leadingAnchor.constraint(equalTo: contactImage.trailingAnchor, constant: Padding.ContactName.left).isActive = true
contactName.trailingAnchor.constraint(equalTo: contactSaveIcon.leadingAnchor, constant: -Padding.ContactName.right).isActive = true
contactName.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
}
private func setTarget() {
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tapped))
tapGesture.numberOfTapsRequired = 1
self.addGestureRecognizer(tapGesture)
}
}
| 33.695652 | 139 | 0.65828 |
6ab9d5b704779fac81c80f46430bcba9730e2ede
| 420 |
//
// UserSession.swift
// Musication
//
// Created by Tiago Oliveira on 12/10/21.
//
import Foundation
class UserSession {
static var shared: UserSession = {
let instance = UserSession()
return instance
}()
private var userId: String = ""
private init() {
userId = UUID().uuidString
}
public func getUserId() -> String {
return userId
}
}
| 16.153846 | 42 | 0.571429 |
75b3a04863c1c391556476f82c666659a89d1b87
| 2,283 |
//
// SceneDelegate.swift
//
//
// Created by ji-no on R 4/02/05
//
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 42.277778 | 147 | 0.708717 |
6966ec69e0bbdbd1df11cfbfd2c58dbc2732347c
| 12,909 |
//
// BBPDropdown.swift
// BBPDropDown
//
// Created by Don Clore on 3/6/16.
// Copyright © 2016 Beer Barrel Poker Studios. All rights reserved.
//
import UIKit
protocol BBPDropDownDelegate {
func requestNewHeight(_ dropDown:BBPDropdown, newHeight: CGFloat)
func dropDownView(_ dropDown: BBPDropdown, didSelectedItem item:String)
func dropDownView(_ dropDown: BBPDropdown, dataList: [String])
func dropDownWillAppear(_ dropDown: BBPDropdown)
}
@IBDesignable class BBPDropdown: UIView, UICollectionViewDelegate, UICollectionViewDataSource,
LozengeCellDelegate, BBPDropDownPopupDelegate {
// MARK: - private constants
fileprivate let cellId = "LozengeCell"
fileprivate let vertMargin : CGFloat = 8.0
// MARK: - private properties
fileprivate var lozengeData: [String] = [String]()
fileprivate var popTable: BBPDropDownPopup?
fileprivate var view: UIView! // Our custom view from the Xib file.
fileprivate var rightGutterTapRecognizer : UITapGestureRecognizer?
fileprivate var collectionViewTapRecognizer: UITapGestureRecognizer?
fileprivate var backgroundViewTapRecognizer: UITapGestureRecognizer?
fileprivate var labelTapRecognizer: UITapGestureRecognizer?
fileprivate var dropDownVisible : Bool = false
fileprivate var ready : Bool = false
fileprivate func showPlaceholder(_ show: Bool) {
placeHolderLabel.alpha = show ? 1.0 : 0.0
placeHolderLabel.isHidden = !show
showSingleItemLabel(!isMultiple && !show)
showLozengeCollection(isMultiple && !show)
}
fileprivate func showSingleItemLabel(_ show: Bool) {
singleItemLabel.alpha = show ? 1.0 : 0.0
singleItemLabel.isHidden = !show
}
fileprivate func showLozengeCollection(_ show: Bool) {
lozengeCollection.alpha = show ? 1.0 : 0.0
lozengeCollection.isHidden = !show
}
// MARK: - IBOutlets
@IBOutlet var lozengeCollection: UICollectionView!
@IBOutlet var rightGutter: UIView!
@IBOutlet var singleItemLabel: UILabel!
@IBOutlet var placeHolderLabel: UILabel!
// MARK: - public non-inspectable properties
var data : [String] = [] {
willSet (newValue) {
ready = true
}
}
var selections : [String] {
get {
return lozengeData
}
set (newValue){
lozengeData = newValue
lozengeCollection.reloadData()
// Hide the placeholder if there's data, show it if not.
showPlaceholder(newValue.count == 0)
readjustHeight()
}
}
var singleItemText : String? {
get {
return singleItemLabel.text
}
set (newValue) {
var placeHolder : Bool = false
singleItemLabel.text = newValue
if let text = newValue {
placeHolder = text != "" ? false : true
} else {
placeHolder = true
}
showPlaceholder(placeHolder)
}
}
// MARK: - Inspectable properties
@IBInspectable var placeHolderText : String? {
get {
return placeHolderLabel.text
}
set (newValue) {
placeHolderLabel.text = newValue
}
}
@IBInspectable var lozengeBackgroundColor : UIColor?
@IBInspectable var lozengeTextColor : UIColor?
@IBInspectable var borderColor : UIColor = UIColor.lightGray
@IBInspectable var borderWidth : CGFloat = 1.0
var delegate: BBPDropDownDelegate?
@IBInspectable var isMultiple : Bool = false {
didSet(newValue){
setUIStateForSelectionMode(newValue)
}
}
// MARK: - Inspectable properties forwarded to contained popup
// Ugh: -- Apple encourages long, descriptive identifier names, but if I do that, these
// get clipped in InterfaceBuilder. These are not great names, and they get clipped, but
// it's the best compromise I could find.
@IBInspectable var popTitle: String = ""
@IBInspectable var popBGColor: UIColor = UIColor(red: 204.0 / 255.0,
green: 208.0 / 255.0, blue: 218.0 / 225.0, alpha: 0.70)
@IBInspectable var popTextColor : UIColor = UIColor.black
@IBInspectable var shadOffCX: CGFloat = 2.5
@IBInspectable var shadOffCY: CGFloat = 2.5
@IBInspectable var shadRadius: CGFloat = 2.5
@IBInspectable var shadAlpha: Float = 0.5
@IBInspectable var sepColor : UIColor = UIColor(white: 1.0, alpha: 0.2)
@IBInspectable var selectImage : UIImage?
@IBInspectable var showsHeader : Bool = false
@IBInspectable var headerTextColor : UIColor?
override init(frame: CGRect) {
super.init(frame: frame)
xibSetup()
commonInitStuff()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
xibSetup()
commonInitStuff()
}
func xibSetup() {
view = loadViewFromXib()
// use bounds not frame or it'll be offset
view.frame = bounds
// Make the view stretch with containing view
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
// Adding custom subview on top of our view
addSubview(view)
}
func loadViewFromXib() -> UIView {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName:"BBPDropDown", bundle: bundle)
let view = nib.instantiate(withOwner: self, options:nil)[0] as! UIView
return view
}
func commonInitStuff() {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: cellId, bundle:bundle)
lozengeCollection.register(nib, forCellWithReuseIdentifier: cellId)
lozengeCollection.dataSource = self
lozengeCollection.delegate = self
lozengeCollection.reloadData()
layer.borderColor = borderColor.cgColor
layer.borderWidth = borderWidth
rightGutterTapRecognizer = setupTapRecog()
rightGutter.addGestureRecognizer(rightGutterTapRecognizer!)
collectionViewTapRecognizer = setupTapRecog()
lozengeCollection.addGestureRecognizer(collectionViewTapRecognizer!)
backgroundViewTapRecognizer = setupTapRecog()
addGestureRecognizer(backgroundViewTapRecognizer!)
labelTapRecognizer = setupTapRecog()
singleItemLabel.addGestureRecognizer(labelTapRecognizer!)
singleItemLabel.translatesAutoresizingMaskIntoConstraints = false
setUIStateForSelectionMode(isMultiple)
}
func setUIStateForSelectionMode(_ multiSelect: Bool) {
lozengeCollection.alpha = multiSelect ? 1.0 : 0.0
singleItemLabel.alpha = multiSelect ? 0.0 : 1.0
}
fileprivate func setupTapRecog() -> UITapGestureRecognizer {
let recog = UITapGestureRecognizer()
recog.numberOfTouchesRequired = 1
recog.numberOfTapsRequired = 1
recog.isEnabled = true
recog.addTarget(self, action: #selector(BBPDropdown.tappedForPopup(_:)))
return recog;
}
func fadeOut() {
if let popTable = popTable {
popTable.fadeOut()
}
}
func initializePopup(_ options: [String]) {
resignFirstResponder()
fadeOut()
if let delegate = delegate {
delegate.dropDownWillAppear(self)
}
var xy = CGPoint(x: 0, y: frame.size.height)
xy = convert(xy, to: superview)
let indexes = getIndexesForSelectedItems()
// TODO: This initializer is kind of...not ideal. Just set the properties.
popTable = BBPDropDownPopup(title: popTitle, options:options,
xy: xy,
size:CGSize(width: frame.size.width, height: 280), isMultiple: isMultiple,
showsHeader: showsHeader)
// If they specified an image in the storyboard/xib, honor it.
if let selectImage = selectImage {
popTable!.cellSelectionImage = selectImage
}
if let headerTextColor = headerTextColor {
popTable!.headerTextColor = headerTextColor
}
popTable!.popupTextColor = popTextColor
popTable!.selectedItems = indexes
popTable!.shadowOffsetWidth = shadOffCX
popTable!.shadowOffsetHeight = shadOffCY
popTable!.shadowRadius = shadRadius
popTable!.shadowOpacity = shadAlpha
popTable!.separatorColor = sepColor
popTable!.popupBackgroundColor = popBGColor
popTable!.delegate = self
popTable!.showInView(superview!, animated:true)
dropDownVisible = true
}
func getIndexesForSelectedItems() -> [IndexPath] {
var indexes = [IndexPath]()
if isMultiple {
// If it's the mult-select case, grovel through the lozengeData
for selection in lozengeData {
if let idx = data.firstIndex(of: selection) {
let indexPath = IndexPath(item: idx, section: 0)
indexes.append(indexPath)
}
}
} else {
// if it's the single-selectet, the singleItemLabel has the data.
if let text = singleItemText, let idx = data.firstIndex(of: text) {
let indexPath = IndexPath(item: idx, section: 0)
indexes.append(indexPath)
}
}
return indexes
}
// MARK: - tap handlers
// Ugh! - why can't these be private? Evidently targets for tap handlers cannot be.
@objc func tappedForPopup(_ sender: AnyObject) {
if !ready {
return
}
if dropDownVisible {
if let popTable = popTable {
popTable.fadeOut()
}
dropDownVisible = false
} else {
initializePopup(data)
dropDownVisible = true
}
}
// MARK: - UICollectionViewDelegate
func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return lozengeData.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt
indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId,
for: indexPath) as? LozengeCell
cell!.lozengeText.text = lozengeData[indexPath.row]
if let lozengeBackgroundColor = lozengeBackgroundColor,
let lozengeTextColor = lozengeTextColor {
cell!.backgroundColor = lozengeBackgroundColor
cell!.lozengeText.textColor = lozengeTextColor
}
cell!.delegate = self
cell!.setupDeleteTap()
return cell!
}
func collectionView(_ collectionView: UICollectionView, didEndDisplaying
cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
readjustHeight()
}
// MARK: - IBActions
@IBAction func dropDownButtonTouched(_ sender: AnyObject) {
tappedForPopup(sender)
}
func readjustHeight() {
if isMultiple == false {
// Don't grow the height for the single-selection case.
return
}
let size = lozengeCollection.collectionViewLayout.collectionViewContentSize
let height = size.height + (vertMargin * 2)
if let flowLayout = lozengeCollection.collectionViewLayout as? UICollectionViewFlowLayout {
let minHeight = flowLayout.itemSize.height + (vertMargin * 2)
if let delegate = delegate {
delegate.requestNewHeight(self, newHeight: max(minHeight, height))
}
}
}
// MARK: - LozengeCellDelegate
func deleteTapped(_ cell: LozengeCell) {
if let path = lozengeCollection.indexPath(for: cell) {
lozengeData.remove(at: path.row)
lozengeCollection.deleteItems(at: [path])
if lozengeData.count == 0 {
showPlaceholder(true)
}
}
}
// MARK: - BBPDropDownPopupDelegate
func dropDownView(_ dropDownView: BBPDropDownPopup, didSelectedIndex idx: Int) {
let itemData = data[idx]
lozengeData.append(itemData)
lozengeCollection.reloadData()
singleItemText = itemData
showPlaceholder(itemData == "")
if let delegate = delegate {
delegate.dropDownView(self, didSelectedItem: itemData)
}
}
func dropDownView(_ dropDownView: BBPDropDownPopup, dataList: [String]) {
print("dropDownView:dataList: called")
lozengeData = dataList
lozengeCollection.reloadData()
readjustHeight()
let placeHolder = dataList.count == 0
showPlaceholder(placeHolder)
if let delegate = delegate {
delegate.dropDownView(self, dataList:dataList)
}
}
}
| 34.889189 | 99 | 0.633899 |
1eb05055a8ee6d204e8c0f253dc335e6d587a350
| 493 |
//
// Base64Crytion.swift
// ThunderFire
//
// Created by laurenceSecuNet on 4/13/20.
// Copyright © 2020 laurenceSecuNet. All rights reserved.
//
import Foundation
import UIKit
extension String {
func base64Encoded() -> String? {
return data(using: .utf8)?.base64EncodedString()
}
func base64Decoded() -> String? {
guard let data = Data(base64Encoded: self) else {
return nil
}
return String(data: data, encoding: .utf8)
}
}
| 20.541667 | 58 | 0.626775 |
f9bf8dad4afdbd7aef7a0ad6d2ceb7a3bb0eca8d
| 2,896 |
@testable import Graphviz
import SwiftGraph
import XCTest
class GraphvizTests: XCTestCase {
func testEmptyGraph() {
let graph = Graphviz()
XCTAssertEqual(graph.description, "graph { }")
}
func testEmptyDirectedGraph() {
let graph = Graphviz(type: .directed)
XCTAssertEqual(graph.description, "digraph { }")
}
func testEmptyGraphWithName() {
let graph = Graphviz(name: "foo")
XCTAssertEqual(graph.description, "graph foo { }")
}
func testGraphWithOneNode() {
let graph = Graphviz(statements: [Node("A")])
XCTAssertEqual(graph.description, "graph { \"A\" }")
}
func testGraphWithTwoNodes() {
let graph = Graphviz(statements: [Node("A"), Node("B")])
XCTAssertEqual(graph.description, "graph { \"A\"; \"B\" }")
}
func testUndirectedGraphWithOneEdge() {
let graph = Graphviz(statements: ["A" >> "B"])
XCTAssertEqual(graph.description, "graph { \"A\" -- \"B\" }")
}
func testDirectedGraphWithOneEdge() {
let graph = Graphviz(type: .directed,
statements: ["A" >> "B"])
XCTAssertEqual(graph.description, "digraph { \"A\" -> \"B\" }")
}
func testUndirectedGraphWithTwoEdges() {
let graph = Graphviz(statements: ["A" >> "B", "B" >> "C"])
XCTAssertEqual(graph.description, "graph { \"A\" -- \"B\"; \"B\" -- \"C\" }")
}
func testDirectedGraphWithTwoEdges() {
let graph = Graphviz(type: .directed,
statements: ["A" >> "B", "B" >> "C"])
XCTAssertEqual(graph.description, "digraph { \"A\" -> \"B\"; \"B\" -> \"C\" }")
}
func testUndirectedGraphWithSubgraph() {
let graph = Graphviz(statements: [Subgraph("foo")])
XCTAssertEqual(graph.description, "graph { subgraph foo { } }")
}
func testComplexUndirectedGraphWithSubgraph() {
let graph = Graphviz(statements: ["A" >> "B",
Subgraph(statements: ["C" >> "D"])])
XCTAssertEqual(graph.description, "graph { \"A\" -- \"B\"; subgraph { \"C\" -- \"D\" } }")
}
func testGraphWithClusteredSubgraph() {
let graph = Graphviz(statements: [Subgraph("blah", isCluster: true)])
XCTAssertEqual(graph.description, "graph { subgraph cluster_blah { } }")
}
func testSerializingBasicGraph() {
let graph = UnweightedGraph<String>()
_ = graph.addVertex("A")
_ = graph.addVertex("B")
_ = graph.addVertex("C")
graph.addEdge(from: "A", to: "B", directed: true)
graph.addEdge(from: "B", to: "C", directed: true)
graph.addEdge(from: "C", to: "A", directed: true)
let gv = graph.graphviz(name: "Foo")
XCTAssertEqual(gv.description, "digraph Foo { \"A\" -> \"B\"; \"B\" -> \"C\"; \"C\" -> \"A\" }")
}
}
| 30.166667 | 104 | 0.555594 |
5bd2abcae896999adf43a8dd6ca44e05a2e1b306
| 2,803 |
//
// This source file is part of the Apodini open source project
//
// SPDX-FileCopyrightText: 2019-2021 Paul Schmiedmayer and the Apodini project authors (see CONTRIBUTORS.md) <[email protected]>
//
// SPDX-License-Identifier: MIT
//
import MetadataSystem
extension HandlerMetadataNamespace {
/// Name definition for the `EmptyHandlerMetadata`
public typealias Empty = EmptyHandlerMetadata
}
extension ComponentOnlyMetadataNamespace {
/// Name definition for the `EmptyComponentOnlyMetadata`
public typealias Empty = EmptyComponentOnlyMetadata
}
extension WebServiceMetadataNamespace {
/// Name definition for the `EmptyWebServiceMetadata`
public typealias Empty = EmptyWebServiceMetadata
}
extension ComponentMetadataBlockNamespace {
/// Name definition for the `EmptyComponentMetadata`
public typealias Empty = EmptyComponentMetadata
}
/// `EmptyHandlerMetadata` is a `AnyHandlerMetadata` which in fact doesn't hold any Metadata.
/// The Metadata is available under the `HandlerMetadataNamespace.Empty` name and can be used like the following:
/// ```swift
/// struct ExampleHandler: Handler {
/// // ...
/// var metadata: Metadata {
/// Empty()
/// }
/// }
/// ```
public struct EmptyHandlerMetadata: EmptyMetadata, HandlerMetadataDefinition {
public init() {}
}
/// `EmptyComponentOnlyMetadata` is a `ComponentOnlyMetadataDefinition` which in fact doesn't hold any Metadata.
/// The Metadata is available under the `ComponentOnlyMetadataNamespace.Empty` name and can be used like the following:
/// ```swift
/// struct ExampleComponent: Component {
/// // ...
/// var metadata: Metadata {
/// Empty()
/// }
/// }
/// ```
public struct EmptyComponentOnlyMetadata: EmptyMetadata, ComponentOnlyMetadataDefinition {
public init() {}
}
/// `EmptyWebServiceMetadata` is a `AnyWebServiceMetadata` which in fact doesn't hold any Metadata.
/// The Metadata is available under the `WebServiceMetadataNamespace.Empty` name and can be used like the following:
/// ```swift
/// struct ExampleWebService: WebService {
/// // ...
/// var metadata: Metadata {
/// Empty()
/// }
/// }
/// ```
public struct EmptyWebServiceMetadata: EmptyMetadata, WebServiceMetadataDefinition {
public init() {}
}
/// `EmptyComponentMetadata` is a `AnyComponentMetadata` which in fact doesn't hold any Metadata.
/// The Metadata is available under the `ComponentMetadataBlockNamespace.Empty` name and can be used like the following:
/// ```swift
/// struct ExampleComponentMetadata: ComponentMetadataBlock {
/// var metadata: Metadata {
/// Empty()
/// }
/// }
/// ```
public struct EmptyComponentMetadata: EmptyMetadata, ComponentMetadataDefinition {
public init() {}
}
| 32.593023 | 135 | 0.711737 |
abdc8ab03142aed70c33b7491893ac92d0666772
| 7,090 |
//
// BrowsePageNavigationBar.swift
// DoorDash
//
// Created by Marvin Zhan on 2018-10-31.
// Copyright © 2018 Monster. All rights reserved.
//
import UIKit
final class AddressHeadlineView: UIView {
private let deliveryLabel: UILabel
private let addressLabel: UILabel
private let dropDownIndicator: UIImageView
static let height: CGFloat = 45
static let addressLabelFont: UIFont = ApplicationDependency.manager.theme.fonts.bold18
override init(frame: CGRect) {
deliveryLabel = UILabel()
addressLabel = UILabel()
dropDownIndicator = UIImageView()
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupView(address: String) {
self.addressLabel.text = address
}
static func calcHeight(text: String) -> CGFloat {
let addressWidth = HelperManager.textWidth(text, font: addressLabelFont) + 22
return addressWidth
}
}
extension AddressHeadlineView {
private func setupUI() {
setupLabels()
setupDropDownIndicator()
setupConstraints()
}
private func setupLabels() {
setupAddressLabel()
setupDeliveryLabel()
}
private func setupAddressLabel() {
addSubview(addressLabel)
addressLabel.textColor = ApplicationDependency.manager.theme.colors.black
addressLabel.font = AddressHeadlineView.addressLabelFont
addressLabel.textAlignment = .right
addressLabel.adjustsFontSizeToFitWidth = true
addressLabel.minimumScaleFactor = 0.5
addressLabel.numberOfLines = 1
}
private func setupDeliveryLabel() {
addSubview(deliveryLabel)
deliveryLabel.textColor = ApplicationDependency.manager.theme.colors.doorDashRed
deliveryLabel.font = ApplicationDependency.manager.theme.fonts.extraBold10
deliveryLabel.textAlignment = .center
deliveryLabel.adjustsFontSizeToFitWidth = true
deliveryLabel.minimumScaleFactor = 0.5
deliveryLabel.numberOfLines = 1
deliveryLabel.text = "DELIVERING TO"
}
private func setupDropDownIndicator() {
addSubview(dropDownIndicator)
dropDownIndicator.contentMode = .scaleAspectFit
dropDownIndicator.image = ApplicationDependency.manager.theme.imageAssets.dropDownIndicator
}
private func setupConstraints() {
deliveryLabel.snp.makeConstraints { (make) in
make.centerX.equalToSuperview()
make.bottom.equalTo(self.snp.centerY)
}
addressLabel.snp.makeConstraints { (make) in
make.leading.equalToSuperview()
make.trailing.equalTo(dropDownIndicator.snp.leading).offset(-6)
make.top.equalTo(self.snp.centerY)
}
dropDownIndicator.snp.makeConstraints { (make) in
make.trailing.equalToSuperview().offset(-6)
make.width.equalTo(10)
make.height.equalTo(8)
make.centerY.equalTo(addressLabel).offset(1)
}
}
}
final class BrowsePageNavigationBar: UIView {
let addressView: AddressHeadlineView
let numShopLabel: UILabel
private let separator: Separator
var userTappedChangeAddress: (() -> Void)?
override init(frame: CGRect) {
addressView = AddressHeadlineView()
numShopLabel = UILabel()
separator = Separator.create()
super.init(frame: frame)
setupUI()
setupAction()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupAction() {
let tap = UITapGestureRecognizer(target: self, action: #selector(addressHeadlineViewTapped))
addressView.addGestureRecognizer(tap)
}
private func updateBy(offset: CGFloat, navigattionBarMinHeight: CGFloat) {
self.transform = CGAffineTransform(
translationX: 0,
y: -offset
)
self.addressView.layer.opacity = Float(1 - offset / (navigattionBarMinHeight))
self.numShopLabel.layer.opacity = Float(offset / (navigattionBarMinHeight + 2))
}
func adjustBySrollView(offsetY: CGFloat,
previousOffset: CGFloat,
navigattionBarMinHeight: CGFloat) {
if offsetY <= navigattionBarMinHeight && offsetY > 0 {
self.updateBy(offset: offsetY, navigattionBarMinHeight: navigattionBarMinHeight)
}
if previousOffset < navigattionBarMinHeight && offsetY >= navigattionBarMinHeight {
self.updateBy(offset: navigattionBarMinHeight,
navigattionBarMinHeight: navigattionBarMinHeight)
}
if previousOffset > 0 && offsetY < 0 {
self.updateBy(offset: 0, navigattionBarMinHeight: navigattionBarMinHeight)
}
if offsetY <= 0 {
self.addressView.layer.opacity = 1
self.numShopLabel.layer.opacity = 0
}
if offsetY == 0 {
self.transform = CGAffineTransform.identity
}
}
func updateTexts(address: String, numShops: String) {
numShopLabel.text = numShops
addressView.setupView(address: address)
addressView.snp.updateConstraints { (make) in
make.width.equalTo(AddressHeadlineView.calcHeight(text: address))
}
}
}
extension BrowsePageNavigationBar {
private func setupUI() {
self.backgroundColor = ApplicationDependency.manager.theme.colors.white
addSubview(separator)
separator.alpha = 0.6
setupTitleLabel()
setupAddressView()
setupConstraints()
}
private func setupTitleLabel() {
addSubview(numShopLabel)
numShopLabel.textColor = ApplicationDependency.manager.theme.colors.black
numShopLabel.font = ApplicationDependency.manager.theme.fonts.extraBold10
numShopLabel.adjustsFontSizeToFitWidth = true
numShopLabel.minimumScaleFactor = 0.5
numShopLabel.numberOfLines = 1
numShopLabel.textAlignment = .center
numShopLabel.layer.opacity = 0
}
private func setupAddressView() {
addSubview(addressView)
addressView.backgroundColor = .clear
}
private func setupConstraints() {
addressView.snp.makeConstraints { (make) in
make.centerX.equalToSuperview()
make.bottom.equalToSuperview().offset(-10)
make.height.equalTo(AddressHeadlineView.height)
make.width.equalTo(100)
}
numShopLabel.snp.makeConstraints { (make) in
make.bottom.equalToSuperview().offset(-8)
make.centerX.equalToSuperview()
}
separator.snp.makeConstraints { (make) in
make.leading.trailing.bottom.equalToSuperview()
make.height.equalTo(0.6)
}
}
}
extension BrowsePageNavigationBar {
@objc
private func addressHeadlineViewTapped() {
userTappedChangeAddress?()
}
}
| 31.371681 | 100 | 0.6567 |
fe391cd928bcfa2e5220bcd62cb6a8c35edc8ade
| 186 |
// swift-tools-version:5.3
import PackageDescription
let package = Package(
name: "file-icon",
platforms: [
.macOS(.v10_10)
],
targets: [
.target(
name: "file-icon"
)
]
)
| 12.4 | 26 | 0.629032 |
225795866c69d8b9ab6ecf6031940cd1e6fccab1
| 8,220 |
// RUN: %target-run-simple-swift
// REQUIRES: executable_test
//
// REQUIRES: OS=macosx
// REQUIRES: OS=ios
// REQUIRES: OS=tvos
// REQUIRES: OS=watchos
// REQUIRES: OS=linux-androideabi
// REQUIRES: OS=linux-gnu
import Swift
import StdlibUnittest
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
import Darwin
#elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) || os(Cygwin) || os(Haiku)
import Glibc
#else
#error("Unsupported platform")
#endif
var POSIXErrorCodeTestSuite = TestSuite("POSIXErrorCode")
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
POSIXErrorCodeTestSuite.test("Darwin POSIX error codes constants") {
expectEqual(EPERM, POSIXErrorCode.EPERM.rawValue)
}
#elseif os(Linux) || os(Android)
POSIXErrorCodeTestSuite.test("Linux POSIX error codes constants") {
expectEqual(EPERM, POSIXErrorCode.EPERM.rawValue)
expectEqual(ENOENT, POSIXErrorCode.ENOENT.rawValue)
expectEqual(ESRCH, POSIXErrorCode.ESRCH.rawValue)
expectEqual(EINTR, POSIXErrorCode.EINTR.rawValue)
expectEqual(EIO, POSIXErrorCode.EIO.rawValue)
expectEqual(ENXIO, POSIXErrorCode.ENXIO.rawValue)
expectEqual(E2BIG, POSIXErrorCode.E2BIG.rawValue)
expectEqual(ENOEXEC, POSIXErrorCode.ENOEXEC.rawValue)
expectEqual(EBADF, POSIXErrorCode.EBADF.rawValue)
expectEqual(ECHILD, POSIXErrorCode.ECHILD.rawValue)
expectEqual(EAGAIN, POSIXErrorCode.EAGAIN.rawValue)
expectEqual(ENOMEM, POSIXErrorCode.ENOMEM.rawValue)
expectEqual(EACCES, POSIXErrorCode.EACCES.rawValue)
expectEqual(EFAULT, POSIXErrorCode.EFAULT.rawValue)
expectEqual(ENOTBLK, POSIXErrorCode.ENOTBLK.rawValue)
expectEqual(EBUSY, POSIXErrorCode.EBUSY.rawValue)
expectEqual(EXDEV, POSIXErrorCode.EXDEV.rawValue)
expectEqual(ENODEV, POSIXErrorCode.ENODEV.rawValue)
expectEqual(ENOTDIR, POSIXErrorCode.ENOTDIR.rawValue)
expectEqual(EISDIR, POSIXErrorCode.EISDIR.rawValue)
expectEqual(EINVAL, POSIXErrorCode.EINVAL.rawValue)
expectEqual(ENFILE, POSIXErrorCode.ENFILE.rawValue)
expectEqual(EMFILE, POSIXErrorCode.EMFILE.rawValue)
expectEqual(ENOTTY, POSIXErrorCode.ENOTTY.rawValue)
expectEqual(ETXTBSY, POSIXErrorCode.ETXTBSY.rawValue)
expectEqual(EFBIG, POSIXErrorCode.EFBIG.rawValue)
expectEqual(ENOSPC, POSIXErrorCode.ENOSPC.rawValue)
expectEqual(ESPIPE, POSIXErrorCode.ESPIPE.rawValue)
expectEqual(EROFS, POSIXErrorCode.EROFS.rawValue)
expectEqual(EMLINK, POSIXErrorCode.EMLINK.rawValue)
expectEqual(EPIPE, POSIXErrorCode.EPIPE.rawValue)
expectEqual(EDOM, POSIXErrorCode.EDOM.rawValue)
expectEqual(ERANGE, POSIXErrorCode.ERANGE.rawValue)
expectEqual(EDEADLK, POSIXErrorCode.EDEADLK.rawValue)
expectEqual(ENAMETOOLONG, POSIXErrorCode.ENAMETOOLONG.rawValue)
expectEqual(ENOLCK, POSIXErrorCode.ENOLCK.rawValue)
expectEqual(ENOSYS, POSIXErrorCode.ENOSYS.rawValue)
expectEqual(ENOTEMPTY, POSIXErrorCode.ENOTEMPTY.rawValue)
expectEqual(ELOOP, POSIXErrorCode.ELOOP.rawValue)
expectEqual(EWOULDBLOCK, POSIXErrorCode.EWOULDBLOCK.rawValue)
expectEqual(ENOMSG, POSIXErrorCode.ENOMSG.rawValue)
expectEqual(EIDRM, POSIXErrorCode.EIDRM.rawValue)
expectEqual(ECHRNG, POSIXErrorCode.ECHRNG.rawValue)
expectEqual(EL2NSYNC, POSIXErrorCode.EL2NSYNC.rawValue)
expectEqual(EL3HLT, POSIXErrorCode.EL3HLT.rawValue)
expectEqual(EL3RST, POSIXErrorCode.EL3RST.rawValue)
expectEqual(ELNRNG, POSIXErrorCode.ELNRNG.rawValue)
expectEqual(EUNATCH, POSIXErrorCode.EUNATCH.rawValue)
expectEqual(ENOCSI, POSIXErrorCode.ENOCSI.rawValue)
expectEqual(EL2HLT, POSIXErrorCode.EL2HLT.rawValue)
expectEqual(EBADE, POSIXErrorCode.EBADE.rawValue)
expectEqual(EBADR, POSIXErrorCode.EBADR.rawValue)
expectEqual(EXFULL, POSIXErrorCode.EXFULL.rawValue)
expectEqual(ENOANO, POSIXErrorCode.ENOANO.rawValue)
expectEqual(EBADRQC, POSIXErrorCode.EBADRQC.rawValue)
expectEqual(EBADSLT, POSIXErrorCode.EBADSLT.rawValue)
expectEqual(EDEADLOCK, POSIXErrorCode.EDEADLOCK.rawValue)
expectEqual(EBFONT, POSIXErrorCode.EBFONT.rawValue)
expectEqual(ENOSTR, POSIXErrorCode.ENOSTR.rawValue)
expectEqual(ENODATA, POSIXErrorCode.ENODATA.rawValue)
expectEqual(ETIME, POSIXErrorCode.ETIME.rawValue)
expectEqual(ENOSR, POSIXErrorCode.ENOSR.rawValue)
expectEqual(ENONET, POSIXErrorCode.ENONET.rawValue)
expectEqual(ENOPKG, POSIXErrorCode.ENOPKG.rawValue)
expectEqual(EREMOTE, POSIXErrorCode.EREMOTE.rawValue)
expectEqual(ENOLINK, POSIXErrorCode.ENOLINK.rawValue)
expectEqual(EADV, POSIXErrorCode.EADV.rawValue)
expectEqual(ESRMNT, POSIXErrorCode.ESRMNT.rawValue)
expectEqual(ECOMM, POSIXErrorCode.ECOMM.rawValue)
expectEqual(EPROTO, POSIXErrorCode.EPROTO.rawValue)
expectEqual(EMULTIHOP, POSIXErrorCode.EMULTIHOP.rawValue)
expectEqual(EDOTDOT, POSIXErrorCode.EDOTDOT.rawValue)
expectEqual(EBADMSG, POSIXErrorCode.EBADMSG.rawValue)
expectEqual(EOVERFLOW, POSIXErrorCode.EOVERFLOW.rawValue)
expectEqual(ENOTUNIQ, POSIXErrorCode.ENOTUNIQ.rawValue)
expectEqual(EBADFD, POSIXErrorCode.EBADFD.rawValue)
expectEqual(EREMCHG, POSIXErrorCode.EREMCHG.rawValue)
expectEqual(ELIBACC, POSIXErrorCode.ELIBACC.rawValue)
expectEqual(ELIBBAD, POSIXErrorCode.ELIBBAD.rawValue)
expectEqual(ELIBSCN, POSIXErrorCode.ELIBSCN.rawValue)
expectEqual(ELIBMAX, POSIXErrorCode.ELIBMAX.rawValue)
expectEqual(ELIBEXEC, POSIXErrorCode.ELIBEXEC.rawValue)
expectEqual(EILSEQ, POSIXErrorCode.EILSEQ.rawValue)
expectEqual(ERESTART, POSIXErrorCode.ERESTART.rawValue)
expectEqual(ESTRPIPE, POSIXErrorCode.ESTRPIPE.rawValue)
expectEqual(EUSERS, POSIXErrorCode.EUSERS.rawValue)
expectEqual(ENOTSOCK, POSIXErrorCode.ENOTSOCK.rawValue)
expectEqual(EDESTADDRREQ, POSIXErrorCode.EDESTADDRREQ.rawValue)
expectEqual(EMSGSIZE, POSIXErrorCode.EMSGSIZE.rawValue)
expectEqual(EPROTOTYPE, POSIXErrorCode.EPROTOTYPE.rawValue)
expectEqual(ENOPROTOOPT, POSIXErrorCode.ENOPROTOOPT.rawValue)
expectEqual(EPROTONOSUPPORT, POSIXErrorCode.EPROTONOSUPPORT.rawValue)
expectEqual(ESOCKTNOSUPPORT, POSIXErrorCode.ESOCKTNOSUPPORT.rawValue)
expectEqual(EOPNOTSUPP, POSIXErrorCode.EOPNOTSUPP.rawValue)
expectEqual(EPFNOSUPPORT, POSIXErrorCode.EPFNOSUPPORT.rawValue)
expectEqual(EAFNOSUPPORT, POSIXErrorCode.EAFNOSUPPORT.rawValue)
expectEqual(EADDRINUSE, POSIXErrorCode.EADDRINUSE.rawValue)
expectEqual(EADDRNOTAVAIL, POSIXErrorCode.EADDRNOTAVAIL.rawValue)
expectEqual(ENETDOWN, POSIXErrorCode.ENETDOWN.rawValue)
expectEqual(ENETUNREACH, POSIXErrorCode.ENETUNREACH.rawValue)
expectEqual(ENETRESET, POSIXErrorCode.ENETRESET.rawValue)
expectEqual(ECONNABORTED, POSIXErrorCode.ECONNABORTED.rawValue)
expectEqual(ECONNRESET, POSIXErrorCode.ECONNRESET.rawValue)
expectEqual(ENOBUFS, POSIXErrorCode.ENOBUFS.rawValue)
expectEqual(EISCONN, POSIXErrorCode.EISCONN.rawValue)
expectEqual(ENOTCONN, POSIXErrorCode.ENOTCONN.rawValue)
expectEqual(ESHUTDOWN, POSIXErrorCode.ESHUTDOWN.rawValue)
expectEqual(ETOOMANYREFS, POSIXErrorCode.ETOOMANYREFS.rawValue)
expectEqual(ETIMEDOUT, POSIXErrorCode.ETIMEDOUT.rawValue)
expectEqual(ECONNREFUSED, POSIXErrorCode.ECONNREFUSED.rawValue)
expectEqual(EHOSTDOWN, POSIXErrorCode.EHOSTDOWN.rawValue)
expectEqual(EHOSTUNREACH, POSIXErrorCode.EHOSTUNREACH.rawValue)
expectEqual(EALREADY, POSIXErrorCode.EALREADY.rawValue)
expectEqual(EINPROGRESS, POSIXErrorCode.EINPROGRESS.rawValue)
expectEqual(ESTALE, POSIXErrorCode.ESTALE.rawValue)
expectEqual(EUCLEAN, POSIXErrorCode.EUCLEAN.rawValue)
expectEqual(ENOTNAM, POSIXErrorCode.ENOTNAM.rawValue)
expectEqual(ENAVAIL, POSIXErrorCode.ENAVAIL.rawValue)
expectEqual(EISNAM, POSIXErrorCode.EISNAM.rawValue)
expectEqual(EREMOTEIO, POSIXErrorCode.EREMOTEIO.rawValue)
expectEqual(EDQUOT, POSIXErrorCode.EDQUOT.rawValue)
expectEqual(ENOMEDIUM, POSIXErrorCode.ENOMEDIUM.rawValue)
expectEqual(EMEDIUMTYPE, POSIXErrorCode.EMEDIUMTYPE.rawValue)
expectEqual(ECANCELED, POSIXErrorCode.ECANCELED.rawValue)
expectEqual(ENOKEY, POSIXErrorCode.ENOKEY.rawValue)
expectEqual(EKEYEXPIRED, POSIXErrorCode.EKEYEXPIRED.rawValue)
expectEqual(EKEYREVOKED, POSIXErrorCode.EKEYREVOKED.rawValue)
expectEqual(EKEYREJECTED, POSIXErrorCode.EKEYREJECTED.rawValue)
expectEqual(EOWNERDEAD, POSIXErrorCode.EOWNERDEAD.rawValue)
expectEqual(ENOTRECOVERABLE, POSIXErrorCode.ENOTRECOVERABLE.rawValue)
}
#endif
| 49.518072 | 85 | 0.829197 |
d9c228ddd955126090334cda45ea5e62b9465f20
| 2,843 |
class LRUCache_TLE {
var keys: [Int]
var values: [Int]
var count: Int
init(_ capacity: Int) {
self.count = capacity
self.keys = []
self.values = []
}
func get(_ key: Int) -> Int {
if keys.contains(key) {
let idx = keys.firstIndex(of: key)!
let val = values[idx]
keys.remove(at: idx)
values.remove(at: idx)
keys.append(key)
values.append(val)
print(keys)
print(values)
return val
} else {
return -1
}
}
func put(_ key: Int, _ value: Int) {
if keys.contains(key) {
let idx = keys.firstIndex(of: key)!
keys.remove(at: idx)
values.remove(at: idx)
keys.append(key)
values.append(value)
} else {
if keys.count == count {
keys.removeFirst()
values.removeFirst()
}
keys.append(key)
values.append(value)
}
print(keys)
print(values)
}
}
//
//Your LRUCache object will be instantiated and called as such:
//let obj = LRUCache(2)
//obj.put(1, 1)
//obj.put(2, 2)
//obj.put(3, 3)
//let ret_1: Int = obj.get(2)
//obj.put(4, 4)
//
class ListNode {
var key: Int
var val: Int
var prev: ListNode?
var next: ListNode?
init(_ key: Int, _ val: Int) {
self.key = key
self.val = val
}
}
class LRUCache {
var head: ListNode?
var tail: ListNode?
var map: [Int: ListNode] = [:]
var capacity: Int
init(_ capacity: Int) {
self.capacity = capacity
}
func get(_ key: Int) -> Int {
if let node = map[key] {
if node !== head {
remove(node)
addToHead(node)
}
return node.val
} else {
return -1
}
}
func put(_ key: Int, _ value: Int) {
if let node = map[key] {
node.val = value
if node !== head {
remove(node)
addToHead(node)
}
} else {
let node = ListNode(key, value)
if map.count == capacity {
map[tail!.key] = nil
remove(tail!)
}
addToHead(node)
map[key] = node
if tail == nil {
tail = node
}
}
}
private func remove(_ node: ListNode) {
node.prev?.next = node.next
node.next?.prev = node.prev
if node === tail {
tail = node.prev
}
}
private func addToHead(_ node: ListNode) {
node.next = head
head?.prev = node
head = node
}
}
| 21.70229 | 63 | 0.445304 |
b954a5b905e4f4149db472988e9829db46cdff53
| 930 |
//
// VeluzityKitTests.swift
// VeluzityKitTests
//
// Created by Jean Frederic Plante on 3/29/15.
// Copyright (c) 2015 Fantastic Whale Labs. All rights reserved.
//
import UIKit
import XCTest
class VeluzityKitTests: 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.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| 25.135135 | 111 | 0.623656 |
7501e3b929e5f6b0800a6bca0973b75a07370cbe
| 6,367 |
import Foundation
import CoreData
public class CoreDataiCloudStorage: Storage {
// MARK: - Attributes
internal let store: CoreDataStore
internal var objectModel: NSManagedObjectModel! = nil
internal var persistentStore: NSPersistentStore! = nil
internal var persistentStoreCoordinator: NSPersistentStoreCoordinator! = nil
internal var rootSavingContext: NSManagedObjectContext! = nil
// MARK: - Storage
public var description: String {
get {
return "CoreDataiCloudStorage"
}
}
public var type: StorageType = .coreData
public var mainContext: Context!
public var saveContext: Context! {
get {
let context = cdContext(withParent: .context(self.rootSavingContext), concurrencyType: .privateQueueConcurrencyType, inMemory: false)
context.observe(inMainThread: true) { [weak self] (notification) -> Void in
(self?.mainContext as? NSManagedObjectContext)?.mergeChanges(fromContextDidSave: notification as Notification)
}
return context
}
}
public var memoryContext: Context! {
get {
let context = cdContext(withParent: .context(self.rootSavingContext), concurrencyType: .privateQueueConcurrencyType, inMemory: true)
return context
}
}
public func operation<T>(_ operation: @escaping (_ context: Context, _ save: @escaping () -> Void) throws -> T) throws -> T {
let context: NSManagedObjectContext = (self.saveContext as? NSManagedObjectContext)!
var _error: Error!
var returnedObject: T!
context.performAndWait {
do {
returnedObject = try operation(context, { () -> Void in
do {
try context.save()
}
catch {
_error = error
}
if self.rootSavingContext.hasChanges {
self.rootSavingContext.performAndWait {
do {
try self.rootSavingContext.save()
}
catch {
_error = error
}
}
}
})
}
catch {
_error = error
}
}
if let error = _error {
throw error
}
return returnedObject
}
public func backgroundOperation(_ operation: @escaping (_ context: Context, _ save: @escaping () -> Void) -> (), completion: @escaping (Error?) -> ()) {
let context: NSManagedObjectContext = self.saveContext as! NSManagedObjectContext
var _error: Error!
context.perform {
operation(context, { () -> Void in
do {
try context.save()
}
catch {
_error = error
}
self.rootSavingContext.perform {
if self.rootSavingContext.hasChanges {
do {
try self.rootSavingContext.save()
}
catch {
_error = error
}
}
completion(_error)
}
})
}
}
public func removeStore() throws {
try FileManager.default.removeItem(at: store.path() as URL)
}
// MARK: - Init
public convenience init(model: CoreDataObjectModel, iCloud: CoreDataiCloudConfig) throws {
try self.init(model: model, iCloud: iCloud, versionController: VersionController())
}
internal init(model: CoreDataObjectModel, iCloud: CoreDataiCloudConfig, versionController: VersionController) throws {
self.objectModel = model.model()!
self.persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: objectModel)
let result = try! cdiCloudInitializeStore(storeCoordinator: persistentStoreCoordinator, iCloud: iCloud)
self.store = result.0
self.persistentStore = result.1
self.rootSavingContext = cdContext(withParent: .coordinator(self.persistentStoreCoordinator), concurrencyType: .privateQueueConcurrencyType, inMemory: false)
self.mainContext = cdContext(withParent: .context(self.rootSavingContext), concurrencyType: .mainQueueConcurrencyType, inMemory: false)
self.observeiCloudChangesInCoordinator()
#if DEBUG
versionController.check()
#endif
}
// MARK: - Public
#if os(iOS) || os(tvOS) || os(watchOS)
public func observable<T: NSManagedObject>(request: FetchRequest<T>) -> RequestObservable<T> where T:Equatable {
return CoreDataObservable(request: request, context: self.mainContext as! NSManagedObjectContext)
}
#endif
// MARK: - Private
private func observeiCloudChangesInCoordinator() {
NotificationCenter
.default
.addObserver(forName: NSNotification.Name.NSPersistentStoreDidImportUbiquitousContentChanges, object: self.persistentStoreCoordinator, queue: nil) { [weak self] (notification) -> Void in
self?.rootSavingContext.perform {
self?.rootSavingContext.mergeChanges(fromContextDidSave: notification)
}
}
}
}
internal func cdiCloudInitializeStore(storeCoordinator: NSPersistentStoreCoordinator, iCloud: CoreDataiCloudConfig) throws -> (CoreDataStore, NSPersistentStore?) {
let storeURL = FileManager.default
.url(forUbiquityContainerIdentifier: iCloud.ubiquitousContainerIdentifier)!
.appendingPathComponent(iCloud.ubiquitousContentURL)
var options = CoreDataOptions.migration.dict()
options[NSPersistentStoreUbiquitousContentURLKey] = storeURL as AnyObject?
options[NSPersistentStoreUbiquitousContentNameKey] = iCloud.ubiquitousContentName as AnyObject?
let store = CoreDataStore.url(storeURL)
return try (store, cdAddPersistentStore(store: store, storeCoordinator: storeCoordinator, options: options))
}
| 38.125749 | 198 | 0.592744 |
ebffbfe45ae57a9d18fb4df12feacdf28c04cd08
| 1,489 |
//
// ASN1Parser.swift
// CardExplorer
//
// Created by Thomas Engelmeier on 13.07.19.
// Copyright © 2019 Thomas Engelmeier. All rights reserved.
//
import Foundation
class ASN1Parser {
private var tlv : ASN1.DER.TLV
init?( _ data: Data ) {
var localData = data
do {
tlv = try ASN1.DER.Decoder.parse(&localData)
value = localData
} catch let error {
return nil
}
}
init( tlv: ASN1.DER.TLV ) {
self.tlv = tlv
switch tlv {
case .integer( let data ):
value = data
case .unknown( let data ):
value = data
case .objectIdentifier( let string ):
preconditionFailure( "Can not handle objectIdentifier \(string)" )
case .sequence( let tlvs ):
preconditionFailure( "Can not handle nested TLVs \(tlvs)" )
default:
break
}
}
var tag : UInt8 {
get { return tlv.tagIdentifier }
}
var value: Data?
func find( tagIdentifier: Int ) -> ASN1Parser? {
var result: ASN1Parser? // ASN1.DER.TLV? = nil
switch tlv {
case .sequence( let tlvs ):
if let matchingTlv = tlvs.first(where:{ $0.tagIdentifier == tagIdentifier }) {
result = ASN1Parser( tlv: matchingTlv )
}
default:
break
}
return result
}
}
| 25.237288 | 94 | 0.511753 |
d55889521aa6b952247776789b4e0418045394e8
| 215 |
@testable import Vapor
@testable import AppLogic
func makeTestDroplet() throws -> Droplet {
let drop = Droplet(arguments: ["dummy/path/", "prepare"])
load(drop)
try drop.runCommands()
return drop
}
| 21.5 | 61 | 0.688372 |
79669bdf9e76fa857d40aed79ad2fb3e543057c2
| 1,163 |
// https://github.com/Quick/Quick
import Quick
import Nimble
import PYToolBarScrollView
class TableOfContentsSpec: QuickSpec {
override func spec() {
describe("these will fail") {
it("can do maths") {
expect(1) == 2
}
it("can read") {
expect("number") == "string"
}
it("will eventually fail") {
expect("time").toEventually( equal("done") )
}
context("these will pass") {
it("can do maths") {
expect(23) == 23
}
it("can read") {
expect("🐮") == "🐮"
}
it("will eventually pass") {
var time = "passing"
DispatchQueue.main.async {
time = "done"
}
waitUntil { done in
Thread.sleep(forTimeInterval: 0.5)
expect(time) == "done"
done()
}
}
}
}
}
}
| 22.803922 | 60 | 0.362855 |
62638ea6ae37958aa604deefc0510397d0cdbdc8
| 1,709 |
//
// NavigationController.swift
// Flashback_Example
//
// Created by yupao_ios_macmini05 on 2021/12/15.
// Copyright © 2021 CocoaPods. All rights reserved.
//
import Foundation
import UIKit
class NavigationController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
interactivePopGestureRecognizer?.isEnabled = false
// 从中间滑动返回
// let target = self.interactivePopGestureRecognizer?.delegate
// let handler = NSSelectorFromString("handleNavigationTransition:")
// let pan = UIPanGestureRecognizer(target: target, action: handler)
// pan.delegate = self
// self.interactivePopGestureRecognizer?.view?.addGestureRecognizer(pan)
// self.interactivePopGestureRecognizer?.isEnabled = false
// weak var weakSelf = self
// if self.responds(to: #selector(getter: interactivePopGestureRecognizer)) {
// self.interactivePopGestureRecognizer?.delegate = weakSelf
// }
}
}
extension NavigationController: UIGestureRecognizerDelegate {
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
// 控制器栈里只有一个,不响应
if self.viewControllers.count <= 1 {
return false
}
// 当控制器正在返回的时候,不响应
if let isTransitioning = self.value(forKey: "_isTransitioning") as? Bool, isTransitioning {
return false
}
// 只能响应 从左到右的滑动
if let translation = (gestureRecognizer as? UIPanGestureRecognizer)?.translation(in: gestureRecognizer.view) {
if translation.x <= 0 {
return false
}
}
return true
}
}
| 32.245283 | 118 | 0.653013 |
030463c5674adecf39d0a42e0b8b93e1e547c5cb
| 35,163 |
//
// DPAGChatStreamSendOptionsView.swift
// ginlo
//
// Created by RBU on 02/06/16.
// Copyright © 2020 ginlo.net GmbH. All rights reserved.
//
import SIMSmeCore
import UIKit
class DPAGTransparentIfClearView: UIView {
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
if let view = super.hitTest(point, with: event) {
if view == self {
if self.isHidden || self.backgroundColor == .clear {
return nil
}
}
return view
}
return nil
}
}
public enum DPAGChatStreamSendOptionsViewSendOption: Int {
case hidden,
closed,
opened,
highPriority,
selfDestruct,
sendTimed,
deactivated
}
public protocol DPAGChatStreamSendOptionsViewDelegate: AnyObject {
func sendOptionSelected(sendOption: DPAGChatStreamSendOptionsViewSendOption)
}
public protocol DPAGChatStreamSendOptionsViewProtocol: AnyObject {
var delegate: DPAGChatStreamSendOptionsViewDelegate? { get set }
func updateButtonTextsWithSendOptions()
func show()
func close()
func reset()
func deactivate()
}
class DPAGChatStreamSendOptionsView: DPAGTransparentIfClearView, DPAGChatStreamSendOptionsViewProtocol {
private var showState: DPAGChatStreamSendOptionsViewSendOption = .hidden
weak var delegate: DPAGChatStreamSendOptionsViewDelegate?
@IBOutlet private var viewActionLabel: UIView! {
didSet {
self.viewActionLabel.backgroundColor = DPAGColorProvider.shared[.messageSendOptionsAction]
self.viewActionLabel.isHidden = true
}
}
@IBOutlet private var labelAction: UILabel! {
didSet {
self.labelAction.textAlignment = .center
self.labelAction.font = UIFont.kFontSubheadline
self.labelAction.textColor = DPAGColorProvider.shared[.messageSendOptionsActionContrast]
}
}
@IBOutlet private var viewActions: DPAGTransparentIfClearView! {
didSet {
self.viewActions.isHidden = true
self.viewActions.backgroundColor = .clear
}
}
@IBOutlet private var viewActionsFrame: UIView!
@IBOutlet private var constraintActionHighPriorityTrailing: NSLayoutConstraint!
@IBOutlet private var viewActionHighPriority: UIView! {
didSet {
self.viewActionHighPriority.alpha = 0
}
}
@IBOutlet private var constraintActionSelfDestructTrailing: NSLayoutConstraint!
@IBOutlet private var viewActionSelfDestruct: UIView! {
didSet {
self.viewActionSelfDestruct.alpha = 0
}
}
@IBOutlet private var constraintActionSendTimedTrailing: NSLayoutConstraint!
@IBOutlet private var viewActionSendTimed: UIView! {
didSet {
self.viewActionSendTimed.alpha = 0
}
}
@IBOutlet private var viewActionShowHide: UIView! {
didSet {
self.viewActionShowHide.alpha = 1
}
}
private var backgroundColorButtonUnselected: UIColor {
DPAGColorProvider.shared[.messageSendOptionsActionUnselected]
}
private var tintColorButtonUnselected: UIColor {
DPAGColorProvider.shared[.messageSendOptionsActionUnselectedContrast]
}
@IBOutlet private var buttonHighPriority: UIButton! {
didSet {
self.buttonHighPriority.accessibilityIdentifier = "chat.button.enable_highPriority"
self.configureButtonAction(self.buttonHighPriority)
self.buttonHighPriority.setImage(DPAGImageProvider.shared[.kImagePriority], for: .normal)
self.buttonHighPriority.addTargetClosure { [weak self] _ in
guard let strongSelf = self else { return }
strongSelf.viewActionLabel.isHidden = false
if strongSelf.showState != .highPriority, DPAGSendMessageViewOptions.sharedInstance.messagePriorityHigh {
strongSelf.buttonHighPriority.backgroundColor = strongSelf.backgroundColorButtonUnselected
strongSelf.buttonHighPriority.tintColor = strongSelf.tintColorButtonUnselected
strongSelf.imageViewHighPriorityCancel.isHidden = true
strongSelf.imageViewHighPriorityCheck.isHidden = true
strongSelf.delegate?.sendOptionSelected(sendOption: .highPriority)
strongSelf.labelAction.text = DPAGLocalizedString("chat.sendOptions.highPriority.unselected")
strongSelf.updateButtonTextsWithSendOptions()
} else {
strongSelf.delegate?.sendOptionSelected(sendOption: .highPriority)
strongSelf.labelAction.text = DPAGSendMessageViewOptions.sharedInstance.messagePriorityHigh ? DPAGLocalizedString("chat.sendOptions.highPriority.selected") : DPAGLocalizedString("chat.sendOptions.highPriority.unselected")
strongSelf.updateButtonTextsWithSendOptions()
switch strongSelf.showState {
case .highPriority:
strongSelf.showState = .opened
strongSelf.buttonHighPriority.backgroundColor = strongSelf.backgroundColorButtonUnselected
strongSelf.buttonHighPriority.tintColor = strongSelf.tintColorButtonUnselected
strongSelf.imageViewHighPriorityCancel.isHidden = true
strongSelf.imageViewHighPriorityCheck.isHidden = true
case .opened:
strongSelf.showState = .highPriority
strongSelf.buttonHighPriority.backgroundColor = DPAGColorProvider.shared[.messageSendOptionsActionHighPriority]
strongSelf.buttonHighPriority.tintColor = DPAGColorProvider.shared[.messageSendOptionsActionHighPriorityContrast]
strongSelf.imageViewHighPriorityCancel.isHidden = true
strongSelf.imageViewHighPriorityCheck.isHidden = false
case .selfDestruct, .sendTimed:
strongSelf.buttonHighPriority.backgroundColor = strongSelf.backgroundColorButtonUnselected
strongSelf.buttonHighPriority.tintColor = strongSelf.tintColorButtonUnselected
strongSelf.imageViewHighPriorityCancel.isHidden = false
strongSelf.imageViewHighPriorityCheck.isHidden = true
case .closed, .hidden, .deactivated:
break
}
}
}
}
}
@IBOutlet private var imageViewHighPriorityCheck: UIImageView! {
didSet {
self.configureButtonActionCheck(self.imageViewHighPriorityCheck)
self.imageViewHighPriorityCheck.isHidden = (self.showState != .highPriority)
}
}
@IBOutlet private var imageViewHighPriorityCancel: UIImageView! {
didSet {
self.configureButtonActionCancel(self.imageViewHighPriorityCancel)
self.imageViewHighPriorityCancel.isHidden = (DPAGSendMessageViewOptions.sharedInstance.messagePriorityHigh == false)
}
}
@IBOutlet private var buttonSelfDestruct: UIButton! {
didSet {
self.buttonSelfDestruct.accessibilityIdentifier = "chat.button.enable_selfdestruction"
self.buttonSelfDestruct.accessibilityLabel = DPAGLocalizedString("chat.button.enable_selfdestruction.accessibility.label")
self.configureButtonAction(self.buttonSelfDestruct)
if DPAGSendMessageViewOptions.sharedInstance.selfDestructionEnabled ?? false {
self.buttonSelfDestruct.backgroundColor = DPAGColorProvider.shared[.messageSendOptionsActionSelfdestruct]
self.buttonSelfDestruct.tintColor = DPAGColorProvider.shared[.messageSendOptionsActionSelfdestructContrast]
} else {
self.buttonSelfDestruct.backgroundColor = self.backgroundColorButtonUnselected
self.buttonSelfDestruct.tintColor = self.tintColorButtonUnselected
}
self.buttonSelfDestruct.setImage(DPAGImageProvider.shared[.kImageChatSelfdestruct], for: .normal)
self.buttonSelfDestruct.addTargetClosure { [weak self] _ in
guard let strongSelf = self else { return }
strongSelf.viewActionLabel.isHidden = false
if strongSelf.showState != .selfDestruct, DPAGSendMessageViewOptions.sharedInstance.selfDestructionEnabled ?? false {
strongSelf.buttonSelfDestruct.backgroundColor = strongSelf.backgroundColorButtonUnselected
strongSelf.buttonSelfDestruct.tintColor = strongSelf.tintColorButtonUnselected
strongSelf.imageViewSelfDestructCancel.isHidden = true
strongSelf.imageViewSelfDestructCheck.isHidden = true
DPAGSendMessageViewOptions.sharedInstance.switchSelfDestruction()
strongSelf.labelAction.text = DPAGLocalizedString("chat.sendOptions.selfDestruct.unselected")
strongSelf.updateButtonTextsWithSendOptions()
} else {
strongSelf.delegate?.sendOptionSelected(sendOption: .selfDestruct)
strongSelf.labelAction.text = (DPAGSendMessageViewOptions.sharedInstance.selfDestructionEnabled ?? false) ? DPAGLocalizedString("chat.sendOptions.selfDestruct.selected") : DPAGLocalizedString("chat.sendOptions.selfDestruct.unselected")
strongSelf.updateButtonTextsWithSendOptions()
switch strongSelf.showState {
case .selfDestruct:
let sendTimeEnabled = (DPAGSendMessageViewOptions.sharedInstance.sendTimeEnabled ?? false)
if sendTimeEnabled {
strongSelf.showState = .sendTimed
strongSelf.buttonSendTimed.backgroundColor = DPAGColorProvider.shared[.messageSendOptionsActionSendDelayed]
strongSelf.buttonSendTimed.tintColor = DPAGColorProvider.shared[.messageSendOptionsActionSendDelayedContrast]
strongSelf.imageViewSendTimedCancel.isHidden = true
strongSelf.imageViewSendTimedCheck.isHidden = false
} else {
strongSelf.showState = .opened
}
strongSelf.buttonSelfDestruct.backgroundColor = strongSelf.backgroundColorButtonUnselected
strongSelf.buttonSelfDestruct.tintColor = strongSelf.tintColorButtonUnselected
strongSelf.imageViewSelfDestructCancel.isHidden = true
strongSelf.imageViewSelfDestructCheck.isHidden = true
case .opened:
strongSelf.showState = .selfDestruct
strongSelf.buttonSelfDestruct.backgroundColor = DPAGColorProvider.shared[.messageSendOptionsActionSelfdestruct]
strongSelf.buttonSelfDestruct.tintColor = DPAGColorProvider.shared[.messageSendOptionsActionSelfdestructContrast]
strongSelf.imageViewSelfDestructCancel.isHidden = true
strongSelf.imageViewSelfDestructCheck.isHidden = false
case .highPriority:
strongSelf.showState = .selfDestruct
strongSelf.buttonSelfDestruct.backgroundColor = DPAGColorProvider.shared[.messageSendOptionsActionSelfdestruct]
strongSelf.buttonSelfDestruct.tintColor = DPAGColorProvider.shared[.messageSendOptionsActionSelfdestructContrast]
strongSelf.imageViewSelfDestructCancel.isHidden = true
strongSelf.imageViewSelfDestructCheck.isHidden = false
strongSelf.imageViewHighPriorityCancel.isHidden = false
strongSelf.imageViewHighPriorityCheck.isHidden = true
strongSelf.buttonHighPriority.backgroundColor = strongSelf.backgroundColorButtonUnselected
strongSelf.buttonHighPriority.tintColor = strongSelf.tintColorButtonUnselected
case .sendTimed:
strongSelf.showState = .selfDestruct
strongSelf.buttonSelfDestruct.backgroundColor = DPAGColorProvider.shared[.messageSendOptionsActionSelfdestruct]
strongSelf.buttonSelfDestruct.tintColor = DPAGColorProvider.shared[.messageSendOptionsActionSelfdestructContrast]
strongSelf.imageViewSelfDestructCancel.isHidden = true
strongSelf.imageViewSelfDestructCheck.isHidden = false
strongSelf.imageViewSendTimedCancel.isHidden = false
strongSelf.imageViewSendTimedCheck.isHidden = true
strongSelf.buttonSendTimed.backgroundColor = strongSelf.backgroundColorButtonUnselected
strongSelf.buttonSendTimed.tintColor = strongSelf.tintColorButtonUnselected
case .closed, .hidden, .deactivated:
break
}
}
}
}
}
@IBOutlet private var imageViewSelfDestructCheck: UIImageView! {
didSet {
self.configureButtonActionCheck(self.imageViewSelfDestructCheck)
self.imageViewSelfDestructCheck.isHidden = (self.showState != .selfDestruct)
}
}
@IBOutlet private var imageViewSelfDestructCancel: UIImageView! {
didSet {
self.configureButtonActionCancel(self.imageViewSelfDestructCancel)
self.imageViewSelfDestructCancel.isHidden = ((DPAGSendMessageViewOptions.sharedInstance.selfDestructionEnabled ?? false) == false)
}
}
@IBOutlet private var buttonSendTimed: UIButton! {
didSet {
self.buttonSendTimed.accessibilityIdentifier = "chat.button.enable_sendTimed"
self.buttonSendTimed.accessibilityLabel = DPAGLocalizedString("chat.button.enable_sendTimed.accessibility.label")
self.configureButtonAction(self.buttonSendTimed)
self.buttonSendTimed.setImage(DPAGImageProvider.shared[.kImageChatSendTimed], for: .normal)
self.buttonSendTimed.addTargetClosure { [weak self] _ in
guard let strongSelf = self else { return }
strongSelf.viewActionLabel.isHidden = false
if strongSelf.showState != .sendTimed, DPAGSendMessageViewOptions.sharedInstance.sendTimeEnabled ?? false {
strongSelf.buttonSendTimed.backgroundColor = strongSelf.backgroundColorButtonUnselected
strongSelf.buttonSendTimed.tintColor = strongSelf.tintColorButtonUnselected
strongSelf.imageViewSendTimedCancel.isHidden = true
strongSelf.imageViewSendTimedCheck.isHidden = true
DPAGSendMessageViewOptions.sharedInstance.switchSendTimed()
strongSelf.labelAction.text = DPAGLocalizedString("chat.sendOptions.sendTimed.selected")
strongSelf.updateButtonTextsWithSendOptions()
} else {
strongSelf.delegate?.sendOptionSelected(sendOption: .sendTimed)
strongSelf.labelAction.text = (DPAGSendMessageViewOptions.sharedInstance.sendTimeEnabled ?? false) ? DPAGLocalizedString("chat.sendOptions.sendTimed.selected") : DPAGLocalizedString("chat.sendOptions.sendTimed.unselected")
strongSelf.updateButtonTextsWithSendOptions()
switch strongSelf.showState {
case .sendTimed:
let selfDestructionEnabled = (DPAGSendMessageViewOptions.sharedInstance.selfDestructionEnabled ?? false)
if selfDestructionEnabled {
strongSelf.showState = .selfDestruct
strongSelf.buttonSelfDestruct.backgroundColor = DPAGColorProvider.shared[.messageSendOptionsActionSelfdestruct]
strongSelf.buttonSelfDestruct.tintColor = DPAGColorProvider.shared[.messageSendOptionsActionSelfdestructContrast]
strongSelf.imageViewSelfDestructCancel.isHidden = true
strongSelf.imageViewSelfDestructCheck.isHidden = false
} else {
strongSelf.showState = .opened
}
strongSelf.buttonSendTimed.backgroundColor = strongSelf.backgroundColorButtonUnselected
strongSelf.buttonSendTimed.tintColor = strongSelf.tintColorButtonUnselected
strongSelf.imageViewSendTimedCancel.isHidden = true
strongSelf.imageViewSendTimedCheck.isHidden = true
case .opened:
strongSelf.showState = .sendTimed
strongSelf.buttonSendTimed.backgroundColor = DPAGColorProvider.shared[.messageSendOptionsActionSendDelayed]
strongSelf.buttonSendTimed.tintColor = DPAGColorProvider.shared[.messageSendOptionsActionSendDelayedContrast]
strongSelf.imageViewSendTimedCancel.isHidden = true
strongSelf.imageViewSendTimedCheck.isHidden = false
case .highPriority:
strongSelf.showState = .sendTimed
strongSelf.buttonSendTimed.backgroundColor = DPAGColorProvider.shared[.messageSendOptionsActionSendDelayed]
strongSelf.buttonSendTimed.tintColor = DPAGColorProvider.shared[.messageSendOptionsActionSendDelayedContrast]
strongSelf.imageViewSendTimedCancel.isHidden = true
strongSelf.imageViewSendTimedCheck.isHidden = false
strongSelf.imageViewHighPriorityCancel.isHidden = false
strongSelf.imageViewHighPriorityCheck.isHidden = true
strongSelf.buttonHighPriority.backgroundColor = strongSelf.backgroundColorButtonUnselected
strongSelf.buttonHighPriority.tintColor = strongSelf.tintColorButtonUnselected
case .selfDestruct:
strongSelf.showState = .sendTimed
strongSelf.buttonSendTimed.backgroundColor = DPAGColorProvider.shared[.messageSendOptionsActionSendDelayed]
strongSelf.buttonSendTimed.tintColor = DPAGColorProvider.shared[.messageSendOptionsActionSendDelayedContrast]
strongSelf.imageViewSendTimedCancel.isHidden = true
strongSelf.imageViewSendTimedCheck.isHidden = false
strongSelf.imageViewSelfDestructCancel.isHidden = false
strongSelf.imageViewSelfDestructCheck.isHidden = true
strongSelf.buttonSelfDestruct.backgroundColor = strongSelf.backgroundColorButtonUnselected
strongSelf.buttonSelfDestruct.tintColor = strongSelf.tintColorButtonUnselected
case .closed, .hidden, .deactivated:
break
}
}
}
}
}
@IBOutlet private var imageViewSendTimedCheck: UIImageView! {
didSet {
self.configureButtonActionCheck(self.imageViewSendTimedCheck)
self.imageViewSendTimedCheck.isHidden = (self.showState != .sendTimed)
}
}
@IBOutlet private var imageViewSendTimedCancel: UIImageView! {
didSet {
self.configureButtonActionCancel(self.imageViewSendTimedCancel)
self.imageViewSendTimedCancel.isHidden = ((DPAGSendMessageViewOptions.sharedInstance.sendTimeEnabled ?? false) == false)
}
}
@IBOutlet private var buttonShowHide: UIButton! {
didSet {
self.buttonShowHide.accessibilityIdentifier = "chat.button.showSendOptions"
self.configureButtonAction(self.buttonShowHide)
self.buttonShowHide.setImage(DPAGImageProvider.shared[.kImageChatSendOptions], for: .normal)
self.buttonShowHide.addTargetClosure { [weak self] _ in
guard let strongSelf = self else { return }
if strongSelf.showState == .closed {
strongSelf.delegate?.sendOptionSelected(sendOption: .opened)
strongSelf.open()
} else {
strongSelf.delegate?.sendOptionSelected(sendOption: .closed)
strongSelf.close()
}
}
}
}
@IBOutlet private var viewSendOptionValues: UIView! {
didSet {
self.viewSendOptionValues.isHidden = true
}
}
@IBOutlet private var imageViewSendOptionValuesBackground: UIImageView! {
didSet {
let size = self.imageViewSendOptionValuesBackground.frame.size
let rect = CGRect(origin: .zero, size: size)
let radius: CGFloat = 8
let image = UIGraphicsImageRenderer(size: size).image { context in
UIBezierPath(roundedRect: rect, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: radius, height: radius)).addClip()
DPAGColorProvider.shared[.messageSendOptionsSelectedBackground].setFill()
context.fill(rect)
}
let imageResizable = image.resizableImage(withCapInsets: UIEdgeInsets(top: radius, left: radius, bottom: 0, right: radius), resizingMode: .stretch)
self.imageViewSendOptionValuesBackground.image = imageResizable
}
}
@IBOutlet private var imageViewHighPriority: UIImageView! {
didSet {
self.imageViewHighPriority.image = DPAGImageProvider.shared[.kImagePriority]
self.imageViewHighPriority.tintColor = DPAGColorProvider.shared[.messageSendOptionsSelectedBackgroundContrast]
self.imageViewHighPriority.isHidden = true
}
}
@IBOutlet private var imageViewSelfDestruct: UIImageView! {
didSet {
self.imageViewSelfDestruct.image = DPAGImageProvider.shared[.kImageChatSelfdestruct]
self.imageViewSelfDestruct.tintColor = DPAGColorProvider.shared[.messageSendOptionsSelectedBackgroundContrast]
self.imageViewSelfDestruct.isHidden = true
}
}
@IBOutlet private var labelSelfDestruct: UILabel! {
didSet {
self.labelSelfDestruct.font = UIFont.kFontFootnote
self.labelSelfDestruct.textColor = DPAGColorProvider.shared[.messageSendOptionsSelectedBackgroundContrast]
self.labelSelfDestruct.text = nil
}
}
@IBOutlet private var imageViewSendTimed: UIImageView! {
didSet {
self.imageViewSendTimed.image = DPAGImageProvider.shared[.kImageChatSendTimed]
self.imageViewSendTimed.tintColor = DPAGColorProvider.shared[.messageSendOptionsSelectedBackgroundContrast]
self.imageViewSendTimed.isHidden = true
}
}
@IBOutlet private var labelSendTimed: UILabel! {
didSet {
self.labelSendTimed.font = UIFont.kFontFootnote
self.labelSendTimed.textColor = DPAGColorProvider.shared[.messageSendOptionsSelectedBackgroundContrast]
self.labelSendTimed.text = nil
}
}
private func configureButtonAction(_ btn: UIButton) {
btn.setTitle(nil, for: .normal)
btn.layer.cornerRadius = btn.frame.width / 2
btn.backgroundColor = self.backgroundColorButtonUnselected
btn.tintColor = self.tintColorButtonUnselected
}
private func configureButtonActionCancel(_ imageView: UIImageView) {
imageView.image = DPAGImageProvider.shared[.kImageClose]
imageView.layer.cornerRadius = imageView.frame.width / 2
imageView.backgroundColor = DPAGColorProvider.shared[.messageSendOptionsActionCancel]
imageView.tintColor = DPAGColorProvider.shared[.messageSendOptionsActionCancelContrast]
}
private func configureButtonActionCheck(_ imageView: UIImageView) {
imageView.image = DPAGImageProvider.shared[.kImageChatCellOverlayCheck]
imageView.layer.cornerRadius = imageView.frame.height / 2
imageView.backgroundColor = DPAGColorProvider.shared[.messageSendOptionsActionCheck]
imageView.tintColor = DPAGColorProvider.shared[.messageSendOptionsActionCheckContrast]
}
private func open() {
self.showState = .opened
self.constraintActionHighPriorityTrailing.constant = 8 + self.viewActionShowHide.frame.width
if DPAGSendMessageViewOptions.sharedInstance.messageGuidCitation == nil {
self.constraintActionSelfDestructTrailing.constant = 8 + self.viewActionShowHide.frame.width
self.constraintActionSendTimedTrailing.constant = 8 + self.viewActionShowHide.frame.width
}
UIView.animate(withDuration: TimeInterval(UINavigationController.hideShowBarDuration), animations: {
self.viewActionHighPriority.alpha = 1
if DPAGSendMessageViewOptions.sharedInstance.messageGuidCitation == nil {
self.viewActionSendTimed.alpha = 1
self.viewActionSelfDestruct.alpha = 1
}
self.backgroundColor = DPAGColorProvider.shared[.messageSendOptionsOverlayBackground]
self.buttonShowHide.backgroundColor = self.backgroundColorButtonUnselected
self.buttonShowHide.tintColor = self.tintColorButtonUnselected
self.buttonShowHide.setImage(DPAGImageProvider.shared[.kImageClose], for: .normal)
self.viewSendOptionValues.isHidden = false
self.viewActions.superview?.layoutIfNeeded()
}, completion: { _ in
})
}
func close() {
self.showState = .closed
self.constraintActionHighPriorityTrailing.constant = 0
self.constraintActionSelfDestructTrailing.constant = 0
self.constraintActionSendTimedTrailing.constant = 0
UIView.animate(withDuration: TimeInterval(UINavigationController.hideShowBarDuration), animations: {
self.viewActionLabel.isHidden = true
self.viewActionSendTimed.alpha = 0
self.viewActionHighPriority.alpha = 0
self.viewActionSelfDestruct.alpha = 0
self.backgroundColor = .clear
if DPAGSendMessageViewOptions.sharedInstance.messagePriorityHigh || (DPAGSendMessageViewOptions.sharedInstance.selfDestructionEnabled ?? false) || (DPAGSendMessageViewOptions.sharedInstance.sendTimeEnabled ?? false) {
self.buttonShowHide.backgroundColor = DPAGColorProvider.shared[.messageSendOptionsAction]
self.buttonShowHide.tintColor = DPAGColorProvider.shared[.messageSendOptionsActionContrast]
self.viewSendOptionValues.isHidden = false
if DPAGSendMessageViewOptions.sharedInstance.messagePriorityHigh {
self.imageViewHighPriorityCancel.isHidden = false
self.imageViewHighPriorityCheck.isHidden = true
self.buttonHighPriority.backgroundColor = self.backgroundColorButtonUnselected
self.buttonHighPriority.tintColor = self.tintColorButtonUnselected
}
if DPAGSendMessageViewOptions.sharedInstance.selfDestructionEnabled ?? false {
self.imageViewSelfDestructCancel.isHidden = false
self.imageViewSelfDestructCheck.isHidden = true
self.buttonSelfDestruct.backgroundColor = self.backgroundColorButtonUnselected
self.buttonSelfDestruct.tintColor = self.tintColorButtonUnselected
}
if DPAGSendMessageViewOptions.sharedInstance.sendTimeEnabled ?? false {
self.imageViewSendTimedCancel.isHidden = false
self.imageViewSendTimedCheck.isHidden = true
self.buttonSendTimed.backgroundColor = self.backgroundColorButtonUnselected
self.buttonSendTimed.tintColor = self.tintColorButtonUnselected
}
} else {
self.buttonShowHide.backgroundColor = self.backgroundColorButtonUnselected
self.buttonShowHide.tintColor = self.tintColorButtonUnselected
self.viewSendOptionValues.isHidden = true
}
self.buttonShowHide.setImage(DPAGImageProvider.shared[.kImageChatSendOptions], for: .normal)
self.viewActions.superview?.layoutIfNeeded()
}, completion: { _ in
})
}
func deactivate() {
switch self.showState {
case .closed, .deactivated, .hidden:
break
case .highPriority, .selfDestruct, .sendTimed, .opened:
if DPAGSendMessageViewOptions.sharedInstance.selfDestructionEnabled ?? false {
self.buttonSelfDestruct.backgroundColor = self.backgroundColorButtonUnselected
self.buttonSelfDestruct.tintColor = self.tintColorButtonUnselected
self.imageViewSelfDestructCancel.isHidden = false
self.imageViewSelfDestructCheck.isHidden = true
}
if DPAGSendMessageViewOptions.sharedInstance.sendTimeEnabled ?? false {
self.buttonSendTimed.backgroundColor = self.backgroundColorButtonUnselected
self.buttonSendTimed.tintColor = self.tintColorButtonUnselected
self.imageViewSendTimedCancel.isHidden = false
self.imageViewSendTimedCheck.isHidden = true
}
if DPAGSendMessageViewOptions.sharedInstance.messagePriorityHigh {
self.buttonHighPriority.backgroundColor = self.backgroundColorButtonUnselected
self.buttonHighPriority.tintColor = self.tintColorButtonUnselected
self.imageViewHighPriorityCancel.isHidden = false
self.imageViewHighPriorityCheck.isHidden = true
}
self.showState = .opened
}
}
func reset() {
self.close()
self.showState = .hidden
self.updateButtonTextsWithSendOptions()
self.viewActions.isHidden = true
self.viewActionLabel.isHidden = true
self.viewSendOptionValues.isHidden = true
self.imageViewHighPriorityCheck.isHidden = true
self.imageViewSelfDestructCheck.isHidden = true
self.imageViewSendTimedCheck.isHidden = true
self.imageViewHighPriorityCancel.isHidden = true
self.imageViewSelfDestructCancel.isHidden = true
self.imageViewSendTimedCancel.isHidden = true
self.buttonHighPriority.backgroundColor = self.backgroundColorButtonUnselected
self.buttonHighPriority.tintColor = self.tintColorButtonUnselected
self.buttonSelfDestruct.backgroundColor = self.backgroundColorButtonUnselected
self.buttonSelfDestruct.tintColor = self.tintColorButtonUnselected
self.buttonSendTimed.backgroundColor = self.backgroundColorButtonUnselected
self.buttonSendTimed.tintColor = self.tintColorButtonUnselected
}
func show() {
switch self.showState {
case .hidden:
self.viewActions.isHidden = false
self.viewActionLabel.isHidden = true
self.viewSendOptionValues.isHidden = true
self.showState = .closed
case .closed, .highPriority, .opened, .selfDestruct, .sendTimed, .deactivated:
break
}
}
func updateButtonTextsWithSendOptions() {
if DPAGSendMessageViewOptions.sharedInstance.selfDestructionEnabled ?? false {
self.imageViewSelfDestruct.isHidden = false
self.labelSelfDestruct.text = DPAGSendMessageViewOptions.sharedInstance.timerLabelDestructionCell
} else {
self.imageViewSelfDestruct.isHidden = true
self.labelSelfDestruct.text = nil
}
if DPAGSendMessageViewOptions.sharedInstance.sendTimeEnabled ?? false {
self.imageViewSendTimed.isHidden = false
self.labelSendTimed.text = DPAGSendMessageViewOptions.sharedInstance.timerLabelSendTimeCell
} else {
self.imageViewSendTimed.isHidden = true
self.labelSendTimed.text = nil
}
if DPAGSendMessageViewOptions.sharedInstance.messagePriorityHigh {
self.imageViewHighPriority.isHidden = false
} else {
self.imageViewHighPriority.isHidden = true
}
}
override
func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if #available(iOS 13.0, *) {
if self.traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) {
DPAGColorProvider.shared.darkMode = traitCollection.userInterfaceStyle == .dark
self.viewActionLabel.backgroundColor = DPAGColorProvider.shared[.messageSendOptionsAction]
self.labelAction.textColor = DPAGColorProvider.shared[.messageSendOptionsActionContrast]
self.imageViewHighPriority.tintColor = DPAGColorProvider.shared[.messageSendOptionsSelectedBackgroundContrast]
self.imageViewSelfDestruct.tintColor = DPAGColorProvider.shared[.messageSendOptionsSelectedBackgroundContrast]
self.labelSelfDestruct.textColor = DPAGColorProvider.shared[.messageSendOptionsSelectedBackgroundContrast]
self.imageViewSendTimed.tintColor = DPAGColorProvider.shared[.messageSendOptionsSelectedBackgroundContrast]
self.labelSendTimed.textColor = DPAGColorProvider.shared[.messageSendOptionsSelectedBackgroundContrast]
self.configureButtonActionCancel(self.imageViewHighPriorityCancel)
self.configureButtonActionCancel(self.imageViewSelfDestructCancel)
self.configureButtonActionCancel(self.imageViewSendTimedCancel)
self.configureButtonActionCheck(self.imageViewHighPriorityCheck)
self.configureButtonActionCheck(self.imageViewSelfDestructCheck)
self.configureButtonActionCheck(self.imageViewSendTimedCheck)
}
} else {
DPAGColorProvider.shared.darkMode = false
}
}
}
| 53.848392 | 255 | 0.661747 |
4bdef39e3c488eb248b6323f71e35914f27dbbfe
| 1,447 |
/*
MIT License
Copyright (c) 2017 MessageKit
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import Foundation
struct TestMessage: MessageType {
var messageId: String
var sender: Sender
var sentDate: Date
var data: MessageData
init(text: String, sender: Sender, messageId: String) {
data = .text(text)
self.sender = sender
self.messageId = messageId
self.sentDate = Date()
}
}
| 35.292683 | 79 | 0.744299 |
d6209794b17fa108c905ca0deed733d5334a1227
| 3,456 |
import AVFoundation
import GLKit
import ImageSource
final class CameraOutputGLKView: GLKView, CameraOutputRenderView, CameraCaptureOutputHandler {
// MARK: - State
private var hasWindow = false
private var bufferQueue = DispatchQueue.main
// MARK: - Init
init(captureSession: AVCaptureSession, outputOrientation: ExifOrientation, eaglContext: EAGLContext) {
ciContext = CIContext(eaglContext: eaglContext, options: [CIContextOption.workingColorSpace: NSNull()])
orientation = outputOrientation
super.init(frame: .zero, context: eaglContext)
clipsToBounds = true
enableSetNeedsDisplay = false
bufferQueue = CaptureSessionPreviewService.startStreamingPreview(
of: captureSession,
to: self,
isMirrored: outputOrientation.isMirrored)
}
override func didMoveToWindow() {
super.didMoveToWindow()
let hasWindow = (window != nil)
bufferQueue.async { [weak self] in
self?.hasWindow = hasWindow
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - CameraOutputView
var orientation: ExifOrientation
var onFrameDraw: (() -> ())?
var imageBuffer: CVImageBuffer? {
didSet {
if hasWindow {
display()
}
}
}
// MARK: - GLKView
override func draw(_ rect: CGRect) {
guard let imageBuffer = imageBuffer else { return }
let image = CIImage(cvPixelBuffer: imageBuffer)
ciContext.draw(
image,
in: drawableBounds(for: rect),
from: sourceRect(of: image, targeting: rect)
)
onFrameDraw?()
}
// MARK: - Private
private let ciContext: CIContext
private func drawableBounds(for rect: CGRect) -> CGRect {
let screenScale = UIScreen.main.nativeScale
var drawableBounds = rect
drawableBounds.size.width *= screenScale
drawableBounds.size.height *= screenScale
return drawableBounds
}
private func sourceRect(of image: CIImage, targeting rect: CGRect) -> CGRect {
guard image.extent.width > 0, image.extent.height > 0, rect.width > 0, rect.height > 0 else {
return .zero
}
let sourceExtent = image.extent
let sourceAspect = sourceExtent.size.width / sourceExtent.size.height
let previewAspect = rect.size.width / rect.size.height
// we want to maintain the aspect radio of the screen size, so we clip the video image
var drawRect = sourceExtent
if sourceAspect > previewAspect {
// use full height of the video image, and center crop the width
drawRect.origin.x += (drawRect.size.width - drawRect.size.height * previewAspect) / 2
drawRect.size.width = drawRect.size.height * previewAspect
} else {
// use full width of the video image, and center crop the height
drawRect.origin.y += (drawRect.size.height - drawRect.size.width / previewAspect) / 2
drawRect.size.height = drawRect.size.width / previewAspect
}
return drawRect
}
}
| 30.584071 | 111 | 0.596354 |
18a72de029261eb43bc247fb99c7f994a971db37
| 833 |
//
// Reusable.swift
// zyme
//
// Created by zyme on 2018/1/22.
// Copyright © 2018年 zyme. All rights reserved.
//
import Foundation
import UIKit
protocol ZymeReusable: ZymeNameOfClassable {
static var defaultIdentifier: String {get}
var defaultIdentifier: String {get}
}
protocol ZymeNibReusable: ZymeReusable {
static var nib: UINib { get }
}
extension ZymeReusable {
static var defaultIdentifier: String { return nameOfClass + ".zyme." + "identifier" }
var defaultIdentifier: String { return Self.defaultIdentifier }
}
extension ZymeNibReusable {
static var nib: UINib {
return UINib(nibName: nameOfClass, bundle: nil)
}
}
extension UITableViewCell: ZymeNibReusable {}
extension UICollectionReusableView: ZymeNibReusable {}
extension UITableViewHeaderFooterView: ZymeNibReusable {}
| 23.138889 | 89 | 0.735894 |
e594b050f17c23c91e2c578f9fdf56d1053cd84e
| 356 |
//
// UITextView+I18n.swift
// SwiftI18n
//
// Created by Vlaho Poluta on 17/08/16.
// Copyright © 2016 Infinum. All rights reserved.
//
import UIKit
extension UITextView: I18n {
func loc_localeDidChange() {
guard let text = loc_keysDictionary[UITextView.loc_titleKey]?.localised else {return}
self.text = text
}
}
| 17.8 | 93 | 0.654494 |
46122ad22ce57cd66ad069889a1ddd9e64e6be64
| 5,168 |
//
// TilesCollectionViewLayout.swift
// GiphyAPI-InfiniteScroll
//
// Created by Akshit Zaveri on 21/06/19.
// Copyright © 2019 Akshit Zaveri. All rights reserved.
//
import UIKit
protocol TilesCollectionViewLayoutDelegate: class {
func collectionView(_ collectionView: UICollectionView, aspectRatioForImageAtIndexPath indexPath: IndexPath) -> CGFloat
}
class TilesCollectionViewLayout: UICollectionViewFlowLayout {
weak var delegate: TilesCollectionViewLayoutDelegate!
private(set) var cache = [UICollectionViewLayoutAttributes]()
private var numberOfColumns: Int
private var contentWidth: CGFloat {
guard let collectionView = collectionView else { return 0 }
let insets = collectionView.contentInset
return collectionView.bounds.width - (insets.left + insets.right)
}
private var contentHeight = CGFloat(0)
override var collectionViewContentSize: CGSize { return CGSize(width: contentWidth, height: contentHeight) }
init(numberOfColumns: Int = 2,
delegate: TilesCollectionViewLayoutDelegate?,
sectionInset: UIEdgeInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8),
minimumInteritemSpacing: CGFloat = CGFloat(8),
minimumLineSpacing: CGFloat = CGFloat(8)) {
self.numberOfColumns = numberOfColumns
self.delegate = delegate
super.init()
self.sectionInset = sectionInset
self.minimumInteritemSpacing = minimumInteritemSpacing
self.minimumLineSpacing = minimumLineSpacing
}
required init?(coder aDecoder: NSCoder) { fatalError("Not implemented") }
func getColumnWidth() -> CGFloat {
let interItemSpacing = (minimumInteritemSpacing * CGFloat(numberOfColumns - 1))
let sectionInsets = sectionInset.left + sectionInset.right
let columnWidth = (contentWidth - sectionInsets - interItemSpacing) / CGFloat(numberOfColumns)
return columnWidth
}
override func prepare() {
guard cache.isEmpty, let collectionView = collectionView else { return }
let columnWidth = getColumnWidth()
var xOffset = [CGFloat]()
for column in 0..<numberOfColumns {
var x: CGFloat = 0
if let previous = xOffset.last { x = previous + columnWidth + minimumInteritemSpacing }
else { x = CGFloat(column) * columnWidth + sectionInset.left }
xOffset.append(x)
}
var column = 0
let firstRowOffset = collectionView.contentInset.top + sectionInset.top
var yOffset = [CGFloat](repeating: firstRowOffset, count: numberOfColumns)
for item in 0..<collectionView.numberOfItems(inSection: 0) {
guard let attributes = calculateFrames(for: item,
column: &column,
maximumWidth: columnWidth,
yOffset: &yOffset,
columnX: xOffset[column]) else { continue }
cache.append(attributes)
}
}
func calculateFrames(for itemIndex: Int,
column: inout Int,
maximumWidth: CGFloat,
yOffset: inout [CGFloat],
columnX: CGFloat) -> UICollectionViewLayoutAttributes? {
guard let collectionView = collectionView else { return nil }
let indexPath = IndexPath(item: itemIndex, section: 0)
// Requesting aspect ratio of the image from the delegate and calculating new frame
let aspectRatio = delegate.collectionView(collectionView, aspectRatioForImageAtIndexPath: indexPath)
let height = (maximumWidth / aspectRatio)
let frame = CGRect(x: columnX, y: yOffset[column], width: maximumWidth, height: height)
contentHeight = max(contentHeight, frame.maxY)
yOffset[column] += (height + minimumLineSpacing)
// Set column to 0 only if it has reached to the right most one else advance to the next column
column = (column < (numberOfColumns - 1)) ? (column + 1) : 0
// Adding calculated frame to cache
let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
attributes.frame = frame
return attributes
}
override func invalidateLayout() {
super.invalidateLayout()
cache = []
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var attributesForElementsInVisibleRect = [UICollectionViewLayoutAttributes]()
for attributesForElement in cache {
guard attributesForElement.frame.intersects(rect) else { continue }
attributesForElementsInVisibleRect.append(attributesForElement)
}
return attributesForElementsInVisibleRect
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
return cache[indexPath.item]
}
}
| 42.01626 | 123 | 0.64106 |
b9e56e7cdfb430cb7e231c0bc47c6b07812c1ff7
| 153 |
//
// TranslationNode.swift
// LanguageTranslationAR
//
import SceneKit.SCNNode
class TranslationNode: SCNNode {
var translation: Translation?
}
| 13.909091 | 33 | 0.745098 |
bb852c0b69e71128b1b625327821e99131823c3c
| 909 |
//
// NetworkTools.swift
// LL
//
// Created by l on 2018/5/24.
// Copyright © 2018年 l. All rights reserved.
//
import Foundation
import UIKit
import Alamofire
enum MethodType {
case get
case post
}
class NetworkTools {
class func requestData(_ type : MethodType, URLString : String, parameters : [String : Any]? = nil, finishedCallback : @escaping (_ result : Any) -> ()) {
// 1.获取类型
let method = type == .get ? HTTPMethod.get : HTTPMethod.post
// 2.发送网络请求
Alamofire.request(URLString, method: method, parameters: parameters).responseJSON { (response) in
// 3.获取结果
guard let result = response.result.value else {
print(response.result.error ?? NSError())
return
}
// 4.将结果回调出去
finishedCallback(result)
}
}
}
| 23.921053 | 159 | 0.557756 |
50eddd6b065953d6c71a13470f8c6edb495406ed
| 873 |
//
// ProfileViewController.swift
// PhotoSnap
//
// Created by Fernanda on 3/21/16.
// Copyright © 2016 Maria C. All rights reserved.
//
import UIKit
class ProfileViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 24.25 | 106 | 0.67583 |
9b71c9a079553a5b9b910bdabb52db512ed2a433
| 651 |
// =======================================================
// HMCore
// Nathaniel Kirby
// =======================================================
import Foundation
// =======================================================
public class ServiceContainer: Resolver<ServiceContext> {
internal(set) public var active = false
public let userID: String
public var loggedIn: Bool {
return self.userID != "anon"
}
internal override init(context: ServiceContext, container: ResolverContainer<ServiceContext>) {
self.userID = context.userIdentifier
super.init(context: context, container: container)
}
}
| 29.590909 | 99 | 0.508449 |
5b1fe9f70ae479538b0bb73843958c4b426d2dc5
| 1,493 |
//
// LocalizationApiSwift.swift
// mo-vol-ios
//
// Created by 许永霖 on 2020/11/24.
// Copyright © 2020 Gsafety. All rights reserved.
//
import Foundation
import UIKit
public class InternationalizeApiSwift: NSObject {
typealias JSCallback = (Any)->Void
// MARK: - 切换语言
// 必须使用"_"忽略第一个参数名
@objc func changeLanguage( _ arg: Any, handler: @escaping JSCallback){
// 获取当前设备语言
let lang: String = UserDefaults.standard.string(forKey: "localLanguage") ?? ""
// let lang: String = Locale.preferredLanguages.first!
print(lang)
if lang.contains("Hant"){
AppSettings.shared.language = .Chinese // .Chinese
UserDefaults.standard.setValue("zh-Hans-CN", forKey: "localLanguage")
} else {
AppSettings.shared.language = .Tradition // .Chinese
UserDefaults.standard.setValue("zh-Hant-CN", forKey: "localLanguage")
}
resetRootViewController()
handler(NSLocalizedString("inter_changeSuc", comment: "切换成功"))
}
func resetRootViewController() {
if let appdelegate = UIApplication.shared.delegate {
let storyBoard = UIStoryboard.init(name: "Main", bundle: nil)
if let mainController = storyBoard.instantiateViewController(withIdentifier: "rootViewController") as? UINavigationController {
appdelegate.window??.rootViewController = mainController
}
}
}
}
| 33.177778 | 143 | 0.629605 |
142a800018aeea4b2d5ffe79fba68b8cdd2941ba
| 7,670 |
//
// ConsolesTableViewController.swift
// MyGames
//
// Created by Douglas Frari on 16/05/20.
// Copyright © 2020 Douglas Frari. All rights reserved.
//
import UIKit
import CoreData
class ConsolesTableViewController: UITableViewController {
// esse tipo de classe oferece mais recursos para monitorar os dados
var fetchedResultController:NSFetchedResultsController<Console>!
var label = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
// mensagem default
label.text = "Você não tem plataformas cadastradas"
label.textAlignment = .center
loadConsoles()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// recarrega os dados da tabela quando a tela aparecer
tableView.reloadData()
}
func loadConsoles() {
let fetchRequest: NSFetchRequest<Console> = Console.fetchRequest()
// definindo criterio da ordenacao de como os dados serao entregues
let consoleNameSortDescriptor = NSSortDescriptor(key: "name", ascending: true)
fetchRequest.sortDescriptors = [consoleNameSortDescriptor]
fetchedResultController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
fetchedResultController.delegate = self
do {
try fetchedResultController.performFetch()
} catch {
print(error.localizedDescription)
}
//ConsolesManager.shared.loadConsoles(with: context)
//tableView.reloadData()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
let count = fetchedResultController?.fetchedObjects?.count ?? 0
tableView.backgroundView = count == 0 ? label : nil
return count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "consoleCell", for: indexPath) as! ConsoleTableViewCell
guard let console = fetchedResultController.fetchedObjects?[indexPath.row] else {
return cell
}
cell.prepare(with: console)
return cell
}
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
guard let console = fetchedResultController.fetchedObjects?[indexPath.row] else {
print("Nao foi possivel obter a Plataforma da linha selecionada para deletar")
return
}
context.delete(console) // foi escalado para ser deletado, mas precisamos confirmar com save
do {
try context.save()
// efeito visual deletar poderia ser feito aqui, porem, faremos somente se o banco de dados
//reagir informando que ocorreu uma mudanca (NSFetchedResultsControllerDelegate)
} catch {
print(error.localizedDescription)
}
}
//ConsolesManager.shared.deleteConsole(index: indexPath.row, context: context)
//tableView.deleteRows(at: [indexPath], with: .fade)
}
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
if segue.identifier! == "editConsoleSegue" {
print("editConsoleSegue")
let vc = segue.destination as! ConsoleAddEditViewController
if let consoles = fetchedResultController.fetchedObjects {
vc.console = consoles[tableView.indexPathForSelectedRow!.row]
}
} else if segue.identifier! == "consoleSegue" {
print("consoleSegue")
}
}
// override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//
// let console = ConsolesManager.shared.consoles[indexPath.row]
// //showAlert(with: console)
//
// // deselecionar atual cell
// tableView.deselectRow(at: indexPath, animated: false)
// }
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
// func showAlert(with console: Console?) {
// let title = console == nil ? "Adicionar" : "Editar"
// let alert = UIAlertController(title: title + " plataforma", message: nil, preferredStyle: .alert)
//
// alert.addTextField(configurationHandler: { (textField) in
// textField.placeholder = "Nome da plataforma"
//
// if let name = console?.name {
// textField.text = name
// }
// })
//
// alert.addAction(UIAlertAction(title: title, style: .default, handler: {(action) in
// let console = console ?? Console(context: self.context)
// console.name = alert.textFields?.first?.text
// do {
// try self.context.save()
// self.loadConsoles()
// } catch {
// print(error.localizedDescription)
// }
// }))
//
// alert.addAction(UIAlertAction(title: "Cancelar", style: .cancel, handler: nil))
// alert.view.tintColor = UIColor(named: "second")
//
// present(alert, animated: true, completion: nil)
// }
// @IBAction func addConsole(_ sender: UIBarButtonItem) {
// print("addConsole")
//
// // nil indica que sera criado uma plataforma nova
// showAlert(with: nil)
// }
} // fim da classe
extension ConsolesTableViewController: NSFetchedResultsControllerDelegate {
// sempre que algum objeto for modificado esse metodo sera notificado
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch type {
case .delete:
if let indexPath = indexPath {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
}
break
default:
tableView.reloadData()
}
}
}
| 35.509259 | 200 | 0.626206 |
b9b0a9521d1a49c149aec19ee7a8e542d17296cd
| 1,437 |
//
// PuzzleAppUITests.swift
// PuzzleAppUITests
//
// Created by Mariusz Sut on 23/10/2019.
// Copyright © 2019 Mariusz Sut. All rights reserved.
//
import XCTest
class PuzzleAppUITests: 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
// 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() {
// 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() {
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTOSSignpostMetric.applicationLaunch]) {
XCUIApplication().launch()
}
}
}
}
| 32.659091 | 182 | 0.654141 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.