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
|
---|---|---|---|---|---|
234a96c7e8a88cc757b578fcce0e73bf5f84492a | 855 | //
// AnyOf.swift
// GZHKitSwiftExample
//
// Created by 顾振华 on 2018/8/23.
// Copyright © 2018年 顾振华. All rights reserved.
//
/* Read from [https://gist.github.com/JohnSundell/1956ce36b9303eb4bf912da0de9e2844]
*
* -- Before:
* if string == "One" || string == "Two" || string == "Three" {
* ...
* }
*
* -- Now:
* if string == any(of: "One", "Two", "Three") {
* ...
* }
*/
import Foundation
struct EquatableValueSequence<T: Equatable> {
static func == (lhs: EquatableValueSequence<T>, rhs: T) -> Bool {
return lhs.values.contains(rhs)
}
static func == (lhs: T, rhs: EquatableValueSequence<T>) -> Bool {
return rhs == lhs
}
fileprivate let values: [T]
}
func any<T: Equatable>(of values: T...) -> EquatableValueSequence<T> {
return EquatableValueSequence(values: values)
}
| 21.375 | 83 | 0.591813 |
117084ba0ad3fdd22d0096bd02b36a2c8320c6db | 655 | //
// String+Extensions.swift
// MarvelHeroes
//
// Created by Lorrayne Paraiso on 27/10/18.
// Copyright © 2018 Lorrayne Paraiso. All rights reserved.
//
import Foundation
import CommonCrypto
extension String {
func toMD5(string: String) -> Data {
let messageData = string.data(using: .utf8)!
var digestData = Data(count: Int(CC_MD5_DIGEST_LENGTH))
_ = digestData.withUnsafeMutableBytes {digestBytes in
messageData.withUnsafeBytes {messageBytes in
CC_MD5(messageBytes, CC_LONG(messageData.count), digestBytes)
}
}
return digestData
}
}
| 24.259259 | 77 | 0.635115 |
2f42633e94cde47f63a1438518a33f4655f8b537 | 3,811 | //
// APIManager.swift
// apiCombine
//
// Created by Javier Calatrava on 20/2/21.
//
import Foundation
import UIKit
import Combine
class APIManager {
private static let baseUrl = URL(string: "https://developer.nps.gov/api/v1/")!
// To get a valid api key subscribe to https://www.nps.gov/subjects/developer/get-started.htm
private static let apiKey = ""
private let session = URLSession.shared
private let jsonDecoder = JSONDecoder()
static var injectedUrl: URL?
enum URLPark {
case park
func getURL() -> URL {
switch self {
case .park: return injectedUrl ?? baseUrl
.appending(path: "parks")
.appending(queryParams: [
"api_key": apiKey])
default:
return baseUrl
}
}
}
func fetchParksOriginal(completion: @escaping (Result<ParksResponseAPI, Error>) -> Void) {
let url = APIManager.injectedUrl ?? APIManager.baseUrl
.appending(path: "parks")
.appending(queryParams: [
"api_key": APIManager.apiKey
])
URLSession.shared.dataTask(with: url) { data, response, error in
if let error = error {
completion(.failure(error))
}
guard let data = data else {
assertionFailure("No error and no data. This should never happen.")
return
}
do {
let decodedResponse = try JSONDecoder().decode(ParksResponseAPI.self, from: data)
completion(.success(decodedResponse))
} catch {
completion(.failure(error))
}
}.resume()
}
func fetchParks() -> AnyPublisher<ParksResponseAPI, HTTPError> {
let url = APIManager.injectedUrl ?? APIManager.baseUrl
.appending(path: "parks")
.appending(queryParams: [
"api_key": APIManager.apiKey
])
return URLSession.shared.dataTaskPublisher(for: url)
.tryMap { (data: Data, response: URLResponse) -> (Data, HTTPURLResponse) in
guard let http = response as? HTTPURLResponse else {
throw HTTPError.nonHTTPResponse
}
return (data, http)
}
.mapError { error -> HTTPError in
guard let httpError = error as? HTTPError else {
return HTTPError.networkError(error)
}
return httpError
}
.tryMap { (data: Data, response: HTTPURLResponse) -> Data in
switch response.statusCode {
case 200...299: return data
case 400...499: throw HTTPError.requestFailed(response.statusCode)
case 500...599: throw HTTPError.serverError(response.statusCode)
default:
fatalError("Unhandled HTTP Response status code: \(response.statusCode)")
}
}
.decode(type: ParksResponseAPI.self, decoder: JSONDecoder())
.mapError { error in
guard let httpError = error as? HTTPError else {
return HTTPError.modelError(error)
}
return httpError
}
.eraseToAnyPublisher()
}
}
public extension URL {
func appending(path: String) -> URL {
appendingPathComponent(path, isDirectory: false)
}
func appending(queryParams: [String: String]) -> URL {
var components = URLComponents(url: self, resolvingAgainstBaseURL: false)!
components.queryItems = queryParams.map { key, value in
URLQueryItem(name: key, value: value)
}
return components.url!
}
}
| 33.725664 | 97 | 0.556284 |
e5e0c3613c90018e4ee2bba00d2a692e286c9afe | 1,391 | import Foundation
public struct RelativeDateFormatter {
private let calendar: Calendar
private let dateFormatter: DateFormatter
public init(calendar: Calendar = .current) {
self.calendar = calendar
self.dateFormatter = DateFormatter()
dateFormatter.doesRelativeDateFormatting = true
}
public func localizedStringFromDate(_ date: Date) -> String {
let timeString = timeStringFromDate(date)
if let dateString = dateStringFromDate(date) {
let format = TroposCoreLocalizedString("UpdatedAtDateAndTime")
return String.localizedStringWithFormat(format, dateString, timeString)
} else {
let format = TroposCoreLocalizedString("UpdatedAtTime")
return String.localizedStringWithFormat(format, timeString)
}
}
private func dateStringFromDate(_ date: Date) -> String? {
let components = calendar.dateComponents([.day, .hour, .minute, .second], from: date, to: Date())
guard components.day == 0 else { return nil }
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .none
return dateFormatter.string(from: date)
}
private func timeStringFromDate(_ date: Date) -> String {
dateFormatter.dateStyle = .none
dateFormatter.timeStyle = .short
return dateFormatter.string(from: date)
}
}
| 35.666667 | 105 | 0.674335 |
f8b05d284afa8de1b4e1b82797a46786703f147e | 1,272 | //
// Example.swift
// PDefaults_Tests
//
// Created by Pierre Mardon on 08/06/2021.
// Copyright © 2021 CocoaPods. All rights reserved.
//
import PDefaults
import Combine
struct SomeData: Codable {
var count: Int
var label: String
}
protocol ServiceProtocol {
var name: String { get }
var namePublisher: AnyPublisher<String, Never> { get }
var array: [String] { get }
var arrayPublisher: AnyPublisher<[String], Never> { get }
var data: SomeData { get }
var dataPublisher: AnyPublisher<SomeData, Never> { get }
var optionalData: SomeData? { get }
var optionalDataPublisher: AnyPublisher<SomeData?, Never> { get }
}
class SomeService {
@PDefaults("user.name")
var name = "Pitt"
@PDefaults("user.array")
var array: [String] = []
@PDefaults("user.data")
var data = SomeData(count: 0, label: "Nothing here")
@PDefaults("user.optionaldata")
var optionalData: SomeData? = nil
}
extension SomeService: ServiceProtocol {
var namePublisher: AnyPublisher<String, Never> { $name }
var arrayPublisher: AnyPublisher<[String], Never> { $array }
var dataPublisher: AnyPublisher<SomeData, Never> { $data }
var optionalDataPublisher: AnyPublisher<SomeData?, Never> { $optionalData }
}
| 24.461538 | 79 | 0.677673 |
e63c3f8571c08b443316b11aa7afb65f2cb0d284 | 3,333 | //
// StarViewController.swift
// KDTree
//
// Copyright (c) 2020 mathHeartCode UG(haftungsbeschränkt) <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(macOS)
import Cocoa
#else
import UIKit
#endif
import KDTree
import SwiftyHYGDB
class StarViewController: NSViewController {
var stars: KDTree<RadialStar>?
@IBOutlet weak var loadingIndicator: NSProgressIndicator!
@IBOutlet weak var starMapView: StarMapView!
override func viewDidLoad() {
super.viewDidLoad()
self.title = "StarMap"
loadingIndicator.controlTint = NSControlTint.blueControlTint
//do not load csv during tests
guard ProcessInfo.processInfo.environment["IN_TESTING"] == nil else {
return
}
let startLoading = Date()
DispatchQueue.global(qos: .background).async { [weak self] in
StarHelper.loadStarTree(named: "allStars", completion: { (stars) in
log.debug("Completed loading stars: \(Date().timeIntervalSince(startLoading))s")
self?.stars = stars
log.debug("Finished loading \(stars?.count ?? -1) stars, after \(Date().timeIntervalSince(startLoading))s")
DispatchQueue.main.async {
self?.loadingIndicator.stopAnimation(nil)
self?.reloadStars()
}
})
}
}
func reloadStars() {
if let stars = stars, let starMapView = self.starMapView {
StarHelper.loadForwardStars(starTree: stars,
currentCenter: starMapView.centerPoint,
radii: starMapView.currentRadii()) { (starsVisible) in
starMapView.stars = starsVisible
}
}
}
@IBAction func starMapClicked(_ recognizer: NSClickGestureRecognizer) {
if let stars = stars {
let point = recognizer.location(in: recognizer.view)
StarHelper.selectNearestStar(to: point, starMapView: self.starMapView, stars: stars)
}
}
deinit {
stars?.forEach({ (star: RadialStar) in
star.starData?.ref.release()
})
}
}
| 37.875 | 123 | 0.639064 |
20d49cf90053ab33ea7ef31371e3a13fc82dba1a | 10,990 | import SwiftUI
import XCTest
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public struct InspectableView<View> where View: KnownViewType {
internal let content: Content
internal let parentView: UnwrappedView?
internal let inspectionCall: String
internal let inspectionIndex: Int?
internal init(_ content: Content, parent: UnwrappedView?,
call: String = #function, index: Int? = nil) throws {
let parentView: UnwrappedView? = (parent is InspectableView<ViewType.ParentView>)
? parent?.parentView : parent
let inspectionCall = index
.flatMap({ call.replacingOccurrences(of: "_:", with: "\($0)") }) ?? call
try self.init(content: content, parent: parentView, call: inspectionCall, index: index)
}
private init(content: Content, parent: UnwrappedView?, call: String, index: Int?) throws {
if !View.typePrefix.isEmpty,
Inspector.isTupleView(content.view),
View.self != ViewType.TupleView.self {
throw InspectionError.notSupported(
"Unable to extract \(View.typePrefix): please specify its index inside parent view")
}
self.content = content
self.parentView = parent
self.inspectionCall = call
self.inspectionIndex = index
do {
try Inspector.guardType(value: content.view,
namespacedPrefixes: View.namespacedPrefixes,
inspectionCall: inspectionCall)
} catch {
if let err = error as? InspectionError, case .typeMismatch = err {
let factual = Inspector.typeName(value: content.view, namespaced: true, prefixOnly: true)
.sanitizeNamespace()
let expected = View.namespacedPrefixes
.map { $0.sanitizeNamespace() }
.joined(separator: " or ")
throw InspectionError.inspection(path: pathToRoot, factual: factual, expected: expected)
}
throw error
}
}
}
private extension String {
func sanitizeNamespace() -> String {
var str = self
if let range = str.range(of: ".(unknown context at ") {
let end = str.index(range.upperBound, offsetBy: .init(11))
str.replaceSubrange(range.lowerBound..<end, with: "")
}
return str.replacingOccurrences(of: "SwiftUI.", with: "")
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
internal protocol UnwrappedView {
var content: Content { get }
var parentView: UnwrappedView? { get }
var inspectionCall: String { get }
var inspectionIndex: Int? { get }
var pathToRoot: String { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
extension InspectableView: UnwrappedView { }
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
internal extension UnwrappedView {
func asInspectableView() throws -> InspectableView<ViewType.ClassifiedView> {
return try .init(content, parent: parentView, call: inspectionCall, index: inspectionIndex)
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
internal extension InspectableView {
func asInspectableView<T>(ofType type: T.Type) throws -> InspectableView<T> where T: KnownViewType {
return try .init(content, parent: parentView, call: inspectionCall, index: inspectionIndex)
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension InspectableView {
func parent() throws -> InspectableView<ViewType.ParentView> {
guard let parent = self.parentView else {
throw InspectionError.parentViewNotFound(view: Inspector.typeName(value: content.view))
}
if parent.parentView == nil,
parent is InspectableView<ViewType.ClassifiedView>,
Inspector.typeName(value: parent.content.view, namespaced: true)
== Inspector.typeName(value: content.view, namespaced: true) {
throw InspectionError.parentViewNotFound(view: Inspector.typeName(value: content.view))
}
return try .init(parent.content, parent: parent.parentView, call: parent.inspectionCall)
}
var pathToRoot: String {
let prefix = parentView.flatMap { $0.pathToRoot } ?? ""
return prefix.isEmpty ? inspectionCall : prefix + "." + inspectionCall
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
internal extension InspectableView where View: SingleViewContent {
func child() throws -> Content {
return try View.child(content)
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
internal extension InspectableView where View: MultipleViewContent {
func child(at index: Int, isTupleExtraction: Bool = false) throws -> Content {
let viewes = try View.children(content)
guard index >= 0 && index < viewes.count else {
throw InspectionError.viewIndexOutOfBounds(index: index, count: viewes.count)
}
let child = try viewes.element(at: index)
if !isTupleExtraction && Inspector.isTupleView(child.view) {
// swiftlint:disable line_length
throw InspectionError.notSupported(
"Please insert .tupleView(\(index)) after \(Inspector.typeName(type: View.self)) for inspecting its children at index \(index)")
// swiftlint:enable line_length
}
return child
}
}
// MARK: - Inspection of a Custom View
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension View {
func inspect(function: String = #function) throws -> InspectableView<ViewType.ClassifiedView> {
let medium = ViewHosting.medium(function: function)
let content = try Inspector.unwrap(view: self, medium: medium)
return try .init(content, parent: nil, call: "")
}
func inspect(function: String = #function, file: StaticString = #file, line: UInt = #line,
inspection: (InspectableView<ViewType.ClassifiedView>) throws -> Void) {
do {
try inspection(try inspect(function: function))
} catch {
XCTFail("\(error.localizedDescription)", file: file, line: line)
}
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension View where Self: Inspectable {
func inspect(function: String = #function) throws -> InspectableView<ViewType.View<Self>> {
let call = "view(\(ViewType.View<Self>.typePrefix).self)"
let medium = ViewHosting.medium(function: function)
let content = Content(self, medium: medium)
return try .init(content, parent: nil, call: call)
}
func inspect(function: String = #function, file: StaticString = #file, line: UInt = #line,
inspection: (InspectableView<ViewType.View<Self>>) throws -> Void) {
do {
try inspection(try inspect(function: function))
} catch {
XCTFail("\(error.localizedDescription)", file: file, line: line)
}
}
}
// MARK: - Modifiers
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
internal extension InspectableView {
func numberModifierAttributes(modifierName: String, path: String, call: String) -> Int {
return contentForModifierLookup.numberModifierAttributes(modifierName: modifierName, path: path, call: call)
}
func modifierAttribute<Type>(modifierName: String, path: String,
type: Type.Type, call: String, index: Int = 0) throws -> Type {
return try contentForModifierLookup.modifierAttribute(
modifierName: modifierName, path: path, type: type, call: call, index: index)
}
func modifierAttribute<Type>(modifierLookup: (ModifierNameProvider) -> Bool, path: String,
type: Type.Type, call: String) throws -> Type {
return try contentForModifierLookup.modifierAttribute(
modifierLookup: modifierLookup, path: path, type: type, call: call)
}
func modifier(_ modifierLookup: (ModifierNameProvider) -> Bool, call: String) throws -> Any {
return try contentForModifierLookup.modifier(modifierLookup, call: call)
}
var contentForModifierLookup: Content {
if self is InspectableView<ViewType.ParentView>, let parent = parentView {
return parent.content
}
return content
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
internal extension Content {
typealias ModifierLookupClosure = (ModifierNameProvider) -> Bool
func numberModifierAttributes(modifierName: String, path: String, call: String) -> Int {
let modifyNameProvider: ModifierLookupClosure = { modifier -> Bool in
guard modifier.modifierType.contains(modifierName) else {
return false
}
return true
}
let modifiers = medium.viewModifiers.lazy
.compactMap({ $0 as? ModifierNameProvider })
.filter(modifyNameProvider)
return modifiers.count
}
func modifierAttribute<Type>(modifierName: String, path: String,
type: Type.Type, call: String, index: Int = 0) throws -> Type {
let modifyNameProvider: ModifierLookupClosure = { modifier -> Bool in
guard modifier.modifierType.contains(modifierName) else { return false }
return (try? Inspector.attribute(path: path, value: modifier) as? Type) != nil
}
return try modifierAttribute(modifierLookup: modifyNameProvider, path: path,
type: type, call: call, index: index)
}
func modifierAttribute<Type>(modifierLookup: ModifierLookupClosure, path: String,
type: Type.Type, call: String, index: Int = 0) throws -> Type {
let modifier = try self.modifier(modifierLookup, call: call, index: index)
guard let attribute = try? Inspector.attribute(path: path, value: modifier) as? Type
else {
throw InspectionError.modifierNotFound(
parent: Inspector.typeName(value: self.view), modifier: call)
}
return attribute
}
func modifier(_ modifierLookup: ModifierLookupClosure, call: String, index: Int = 0) throws -> Any {
let modifiers = medium.viewModifiers.lazy
.compactMap({ $0 as? ModifierNameProvider })
.filter(modifierLookup)
if index < modifiers.count {
return modifiers[index]
}
throw InspectionError.modifierNotFound(
parent: Inspector.typeName(value: self.view), modifier: call)
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
internal protocol ModifierNameProvider {
var modifierType: String { get }
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
extension ModifiedContent: ModifierNameProvider {
var modifierType: String {
return Inspector.typeName(type: Modifier.self)
}
}
| 40.553506 | 144 | 0.637307 |
114ec5186a1fa6ba5b1d2e4944b2afbe982868a4 | 13,593 | //
// ALMessage+Extension.swift
// ApplozicSwift
//
// Created by Mukesh Thawani on 04/05/17.
// Copyright © 2017 Applozic. All rights reserved.
//
import ApplozicCore
import Foundation
import MapKit
#if canImport(RichMessageKit)
import RichMessageKit
#endif
let friendsMessage = "4"
let myMessage = "5"
let imageBaseUrl = ALUserDefaultsHandler.getFILEURL() + "/rest/ws/aws/file/"
enum ChannelMetadataKey {
static let conversationSubject = "KM_CONVERSATION_SUBJECT"
}
let emailSourceType = 7
extension ALMessage: ALKChatViewModelProtocol {
private var alContact: ALContact? {
let alContactDbService = ALContactDBService()
guard let alContact = alContactDbService.loadContact(byKey: "userId", value: to) else {
return nil
}
return alContact
}
private var alChannel: ALChannel? {
let alChannelService = ALChannelService()
// TODO: This is a workaround as other method uses closure.
// Later replace this with:
// alChannelService.getChannelInformation(, orClientChannelKey: , withCompletion: )
guard let groupId = groupId,
let alChannel = alChannelService.getChannelByKey(groupId)
else {
return nil
}
return alChannel
}
public var avatar: URL? {
guard let alContact = alContact, let url = alContact.contactImageUrl else {
return nil
}
return URL(string: url)
}
public var avatarImage: UIImage? {
return isGroupChat ? UIImage(named: "group_profile_picture-1", in: Bundle.applozic, compatibleWith: nil) : nil
}
public var avatarGroupImageUrl: String? {
guard let alChannel = alChannel, let avatar = alChannel.channelImageURL else {
return nil
}
return avatar
}
public var name: String {
guard let alContact = alContact, let id = alContact.userId else {
return ""
}
guard let displayName = alContact.getDisplayName(), !displayName.isEmpty else { return id }
return displayName
}
public var groupName: String {
guard let alChannel = alChannel else { return "" }
let name = alChannel.name ?? ""
guard
let userId = alChannel.getReceiverIdInGroupOfTwo(),
let contact = ALContactDBService().loadContact(byKey: "userId", value: userId)
else {
return name
}
return contact.getDisplayName()
}
public var theLastMessage: String? {
switch messageType {
case .text:
return message
case .photo:
return "Photo"
case .location:
return "Location"
case .voice:
return "Audio"
case .information:
return "Update"
case .video:
return "Video"
case .html:
return "Message"
case .faqTemplate:
return isMessageEmpty ? "FAQ" : message
case .button,
.form,
.quickReply,
.listTemplate,
.cardTemplate:
return latestRichMessageText()
case .imageMessage:
return isMessageEmpty ? "Photo" : message
case .email:
guard let channelMetadata = alChannel?.metadata,
let messageText = channelMetadata[ChannelMetadataKey.conversationSubject]
else {
return message
}
return messageText as? String
case .document:
return "Document"
case .contact:
return "Contact"
case .allButtons:
return isMessageEmpty ? "Buttons" : message
}
}
public var hasUnreadMessages: Bool {
if isGroupChat {
guard let alChannel = alChannel, let unreadCount = alChannel.unreadCount else {
return false
}
return unreadCount.boolValue
} else {
guard let alContact = alContact, let unreadCount = alContact.unreadCount else {
return false
}
return unreadCount.boolValue
}
}
var identifier: String {
guard let key = self.key else {
return ""
}
return key
}
var friendIdentifier: String? {
return nil
}
public var totalNumberOfUnreadMessages: UInt {
if isGroupChat {
guard let alChannel = alChannel, let unreadCount = alChannel.unreadCount else {
return 0
}
return UInt(truncating: unreadCount)
} else {
guard let alContact = alContact, let unreadCount = alContact.unreadCount else {
return 0
}
return UInt(truncating: unreadCount)
}
}
public var isGroupChat: Bool {
guard groupId != nil else {
return false
}
return true
}
public var contactId: String? {
return contactIds
}
public var channelKey: NSNumber? {
return groupId
}
public var createdAt: String? {
let isToday = ALUtilityClass.isToday(date)
return getCreatedAtTime(isToday)
}
public var channelType: Int16 {
guard let alChannel = alChannel else { return 0 }
return alChannel.type
}
public var isMessageEmpty: Bool {
return message == nil || message != nil && message.trim().isEmpty
}
public var messageMetadata: NSMutableDictionary? {
return metadata
}
}
extension ALMessage {
var isMyMessage: Bool {
return (type != nil) ? (type == myMessage) : false
}
public var messageType: ALKMessageType {
guard source != emailSourceType else {
// Attachments come as separate message.
if message == nil, let type = getAttachmentType() {
return type
}
return .email
}
switch Int32(contentType) {
case ALMESSAGE_CONTENT_DEFAULT:
return richMessageType()
case ALMESSAGE_CONTENT_LOCATION:
return .location
case ALMESSAGE_CHANNEL_NOTIFICATION:
return .information
case ALMESSAGE_CONTENT_TEXT_HTML:
return richMessageType()
case ALMESSAGE_CONTENT_VCARD:
return .contact
default:
guard let attachmentType = getAttachmentType() else { return .text }
return attachmentType
}
}
var date: Date {
guard let time = createdAtTime else { return Date() }
let sentAt = Date(timeIntervalSince1970: Double(time.doubleValue / 1000))
return sentAt
}
var time: String? {
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "HH:mm"
return dateFormatterGet.string(from: date)
}
var isSent: Bool {
guard let status = status else {
return false
}
return status == NSNumber(integerLiteral: Int(SENT.rawValue))
}
var isAllRead: Bool {
guard let status = status else {
return false
}
return status == NSNumber(integerLiteral: Int(DELIVERED_AND_READ.rawValue))
}
var isAllReceived: Bool {
guard let status = status else {
return false
}
return status == NSNumber(integerLiteral: Int(DELIVERED.rawValue))
}
var ratio: CGFloat {
// Using default
if messageType == .text {
return 1.7
}
return 0.9
}
var size: Int64 {
guard let fileMeta = fileMeta, let size = fileMeta.size, let sizeInt = Int64(size) else { return 0 }
return sizeInt
}
var thumbnailURL: URL? {
guard let fileMeta = fileMeta, let urlStr = fileMeta.thumbnailUrl, let url = URL(string: urlStr) else {
return nil
}
return url
}
var imageUrl: URL? {
guard let fileMeta = fileMeta, let urlStr = fileMeta.blobKey, let imageUrl = URL(string: imageBaseUrl + urlStr) else {
return nil
}
return imageUrl
}
var filePath: String? {
guard let filePath = imageFilePath else {
return nil
}
return filePath
}
var geocode: Geocode? {
guard messageType == .location else {
return nil
}
// Returns lat, long
func getCoordinates(from message: String) -> (Any, Any)? {
guard let messageData = message.data(using: .utf8),
let jsonObject = try? JSONSerialization.jsonObject(
with: messageData,
options: .mutableContainers
),
let messageJSON = jsonObject as? [String: Any]
else {
return nil
}
guard let lat = messageJSON["lat"],
let lon = messageJSON["lon"]
else {
return nil
}
return (lat, lon)
}
guard let message = message,
let (lat, lon) = getCoordinates(from: message)
else {
return nil
}
// Check if type is double or string
if let lat = lat as? Double,
let lon = lon as? Double
{
let location = CLLocationCoordinate2D(latitude: lat, longitude: lon)
return Geocode(coordinates: location)
} else {
guard let latString = lat as? String,
let lonString = lon as? String,
let lat = Double(latString),
let lon = Double(lonString)
else {
return nil
}
let location = CLLocationCoordinate2D(latitude: lat, longitude: lon)
return Geocode(coordinates: location)
}
}
var fileMetaInfo: ALFileMetaInfo? {
return fileMeta ?? nil
}
private func getAttachmentType() -> ALKMessageType? {
guard let fileMeta = fileMeta, (fileMeta.contentType != nil) else { return nil }
guard let index = fileMeta.contentType.firstIndex(of: "/"), (index < fileMeta.contentType.endIndex) else { return nil }
let contentPrefix = String(fileMeta.contentType.prefix(upTo: index))
switch contentPrefix {
case "image":
return .photo
case "audio":
return .voice
case "video":
return .video
default:
return .document
}
}
private func richMessageType() -> ALKMessageType {
guard let metadata = metadata,
let contentType = metadata["contentType"] as? String, contentType == "300",
let templateId = metadata["templateId"] as? String
else {
switch Int32(self.contentType) {
case ALMESSAGE_CONTENT_DEFAULT:
return .text
case ALMESSAGE_CONTENT_TEXT_HTML:
return .html
default:
return .text
}
}
switch templateId {
case "3":
return .button
case "6":
return .quickReply
case "7":
return .listTemplate
case "8":
return .faqTemplate
case "9":
return .imageMessage
case "10":
return .cardTemplate
case "11":
return .allButtons
case "12":
return .form
default:
return .text
}
}
func latestRichMessageText() -> String {
switch Int32(contentType) {
case ALMESSAGE_CONTENT_DEFAULT:
return isMessageEmpty ? "Message" : message
case ALMESSAGE_CONTENT_TEXT_HTML:
return "Message"
default:
return isMessageEmpty ? "Message" : message
}
}
}
public extension ALMessage {
var messageModel: ALKMessageModel {
let messageModel = ALKMessageModel()
messageModel.message = message
messageModel.isMyMessage = isMyMessage
messageModel.identifier = identifier
messageModel.date = date
messageModel.time = time
messageModel.avatarURL = avatar
messageModel.displayName = name
messageModel.contactId = contactId
messageModel.conversationId = conversationId
messageModel.channelKey = channelKey
messageModel.isSent = isSent
messageModel.isAllReceived = isAllReceived
messageModel.isAllRead = isAllRead
messageModel.messageType = messageType
messageModel.ratio = ratio
messageModel.size = size
messageModel.thumbnailURL = thumbnailURL
messageModel.imageURL = imageUrl
messageModel.filePath = filePath
messageModel.geocode = geocode
messageModel.fileMetaInfo = fileMetaInfo
messageModel.receiverId = to
messageModel.isReplyMessage = isAReplyMessage()
messageModel.metadata = metadata as? [String: Any]
messageModel.source = source
if let messageContentType = Message.ContentType(rawValue: contentType) {
messageModel.contentType = messageContentType
}
return messageModel
}
}
extension ALMessage {
override open func isEqual(_ object: Any?) -> Bool {
if let object = object as? ALMessage, let objectKey = object.key, let key = self.key {
return key == objectKey
} else {
return false
}
}
}
| 29.358531 | 127 | 0.573457 |
e27a4dc2325fd12229eaca5cfcaf54da6436a478 | 1,271 | //
// OAuth2+iOS.swift
// OAuth2
//
// Created by David Kraus on 11/26/15.
// Copyright 2015 Pascal Pfiffner
//
// 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.
//
#if os(tvOS)
import Foundation
#if !NO_MODULE_IMPORT
import Base
#endif
public final class OAuth2Authorizer: OAuth2AuthorizerUI {
/// The OAuth2 instance this authorizer belongs to.
public unowned let oauth2: OAuth2Base
init(oauth2: OAuth2) {
self.oauth2 = oauth2
}
// no webview or webbrowser available on tvOS
public func openAuthorizeURLInBrowser(_ url: URL) throws {
throw OAuth2Error.generic("Not implemented")
}
public func authorizeEmbedded(with config: OAuth2AuthConfig, at url: URL) throws {
throw OAuth2Error.generic("Not implemented")
}
}
#endif
| 24.921569 | 83 | 0.732494 |
08de419375718fdb13e7c2190a71e6d1687a175a | 909 | //
// NetworkManagerTests.swift
// SPHTechTestTests
//
// Created by Peter Guo on 18/3/19.
// Copyright © 2019 Peter Guo. All rights reserved.
//
import XCTest
@testable import SPHTechTest
import Foundation
import SystemConfiguration
class NetworkManagerTests: XCTestCase {
override func 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.
}
func testIsConnectedToNetwork() {
let condition = NetworkManager.sharedInstance.isConnectedToNetwork()
if condition{
XCTAssertEqual(condition, true, "Internet checking is wrong")
}else{
XCTAssertEqual(condition, false, "Internet checking is wrong")
}
}
}
| 25.971429 | 111 | 0.676568 |
7248e23eb5e72bf2a8460c6989766b258e1ad8ad | 1,426 | //
// SelectBoxConfiguration.swift
// HXPHPickerExample
//
// Created by Slience on 2020/12/29.
// Copyright © 2020 Silence. All rights reserved.
//
import UIKit
// MARK: 选择框配置类
public class SelectBoxConfiguration {
/// 选择框的大小
public var size: CGSize = CGSize(width: 25, height: 25)
/// 选择框的样式
public var style: SelectBoxView.Style = .number
/// 标题的文字大小
public var titleFontSize: CGFloat = 16
/// 选中之后的 标题 颜色
public var titleColor: UIColor = .white
/// 暗黑风格下选中之后的 标题 颜色
public var titleDarkColor: UIColor = .white
/// 选中状态下勾勾的宽度
public var tickWidth: CGFloat = 1.5
/// 选中之后的 勾勾 颜色
public var tickColor: UIColor = .white
/// 暗黑风格下选中之后的 勾勾 颜色
public var tickDarkColor: UIColor = .black
/// 未选中时框框中间的颜色
public var backgroundColor: UIColor = .black.withAlphaComponent(0.4)
/// 暗黑风格下未选中时框框中间的颜色
public var darkBackgroundColor: UIColor = .black.withAlphaComponent(0.2)
/// 选中之后的背景颜色
public var selectedBackgroundColor: UIColor = .systemTintColor
/// 暗黑风格下选中之后的背景颜色
public var selectedBackgroudDarkColor: UIColor = .systemTintColor
/// 未选中时的边框宽度
public var borderWidth: CGFloat = 1.5
/// 未选中时的边框颜色
public var borderColor: UIColor = .white
/// 暗黑风格下未选中时的边框颜色
public var borderDarkColor: UIColor = .white
public init() { }
}
| 23.377049 | 76 | 0.643759 |
50a6e904f8ac327ef599b47b156e66a5ccc0c964 | 1,067 | //
// UIImage+Blurred.swift
// GhibliMovies
//
// Created by Clément Cardonnel on 23/10/2020.
//
import UIKit
extension UIImage {
/// Apply a gaussian blur to the image, with the given intensity
func blurred(radius: CGFloat = 50) -> UIImage {
let ciContext = CIContext(options: nil)
guard
let ciImage = CIImage(image: self),
let ciFilter = CIFilter(name: "CIGaussianBlur") else {
print("Failed to blur the image.")
return self
}
ciFilter.setValue(ciImage, forKey: kCIInputImageKey)
// actual blur, can be done many times with different
// radiuses without running preparation again
ciFilter.setValue(radius, forKey: "inputRadius")
if let outputImage = ciFilter.outputImage {
let cgImage = ciContext.createCGImage(outputImage, from: ciImage.extent)!
return UIImage(cgImage: cgImage)
} else {
print("Failed to blur the image.")
return self
}
}
}
| 27.358974 | 85 | 0.597001 |
ffca403d13d42add04b9dc4157361d40a1035331 | 1,840 | import UIKit
class TradeItYahooViewController: TradeItViewController {
override func viewDidLoad() {
self.enableThemeOnLoad = false
super.viewDidLoad()
self.enableCustomNavController()
}
func fireViewEventNotification(view: TradeItNotification.View, title: String? = nil) {
let title = title ?? "NO TITLE"
NotificationCenter.default.post(
name: TradeItNotification.Name.viewDidAppear,
object: nil,
userInfo: [
TradeItNotification.UserInfoKey.view.rawValue: view.rawValue,
TradeItNotification.UserInfoKey.viewTitle.rawValue: title
]
)
}
func fireButtonTapEventNotification(view: TradeItNotification.View, button: TradeItNotification.Button) {
NotificationCenter.default.post(
name: TradeItNotification.Name.buttonTapped,
object: nil,
userInfo: [
TradeItNotification.UserInfoKey.view.rawValue: view.rawValue,
TradeItNotification.UserInfoKey.button.rawValue: button
]
)
}
func fireDidSelectRowEventNotification(view: TradeItNotification.View, title: String? = nil, label: String? = nil, rowType: TradeItNotification.RowType) {
let title = title ?? "NO TITLE"
let label = label ?? "NO LABEL"
NotificationCenter.default.post(
name: TradeItNotification.Name.didSelectRow,
object: nil,
userInfo: [
TradeItNotification.UserInfoKey.view.rawValue: view.rawValue,
TradeItNotification.UserInfoKey.viewTitle.rawValue: title,
TradeItNotification.UserInfoKey.rowType.rawValue: rowType,
TradeItNotification.UserInfoKey.rowLabel.rawValue: label
]
)
}
}
| 38.333333 | 158 | 0.640761 |
1ac7a357bfaf8105d732bf4a9742058becee22e6 | 3,035 | //
// MainViewModel.swift
// Demo App
//
// Created by Iñigo Flores Rabasa on 13/03/20.
// Copyright © 2020 Iñigo Flores Rabasa. All rights reserved.
//
import Foundation
import CoreData
import Bond
struct MainViewModelDataSource: ViewModelDataSource {
let context: Context
}
class MainViewModel {
private let router: MainViewRouter
private(set) var context: Context
private let appDelegate = UIApplication.shared.delegate as! AppDelegate
private let coreDatacontext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let storedApps = Observable<[AppEntity]>([])
let titleView = Observable("")
init(dataSource: MainViewModelDataSource, router: MainViewRouter) {
self.context = dataSource.context
self.router = router
if Reachability.isConnectedToNetwork() {
getInfo()
} else {
fetchInfoFromCoreData()
}
}
func getInfo() {
self.context.apiService.getInformation(Success: { [weak self] (result) in
guard let `self` = self else { return }
self.setEntries(entryArray: result.entry ?? [], title: result.title?.label ?? "")
}) { (error) in
print("Error")
}
}
func setEntries(entryArray: [Entry], title: String) {
titleView.value = title
if !entryArray.isEmpty {
storedApps.value = saveInfoInCoreData(result: entryArray)
}
}
func onTap(selected: AppEntity, logo: UIImage ) {
let dataSource = DetailViewModelDataSource(context: context, entry: selected, logo: logo)
router.routeToDetail(dataSource: dataSource)
}
func fetchInfoFromCoreData() {
do {
storedApps.value = try coreDatacontext.fetch(AppEntity.fetchRequest())
titleView.value = "No conection, stored values"
} catch let error as NSError {
debugPrint("Could not fetch \(error), \(error.userInfo)")
}
}
func saveInfoInCoreData(result: [Entry]) -> [AppEntity] {
emptyCoreData()
var array = [AppEntity]()
for element in result {
let appData = AppEntity(entity: AppEntity.entity(), insertInto: coreDatacontext)
appData.name = element.name?.label ?? ""
appData.image = element.image?.first?.label ?? ""
appData.releaseDate = element.releaseDate?.label ?? ""
appData.rigths = element.rights?.label ?? ""
appData.summary = element.summary?.label ?? ""
array.append(appData)
}
appDelegate.saveContext()
return array
}
func emptyCoreData() {
do {
let objects = try coreDatacontext.fetch(AppEntity.fetchRequest())
for obj in objects {
coreDatacontext.delete(obj as! NSManagedObject)
}
} catch let error as NSError {
debugPrint("Could not fetch \(error), \(error.userInfo)")
}
}
}
| 32.98913 | 113 | 0.611862 |
339c15a086077e9ab4f786811a90ef8f0ff16bc7 | 3,264 | //
// RouteResults.swift
// tpg offline
//
// Created by Rémy Da Costa Faro on 10/09/2017.
// Copyright © 2018 Rémy Da Costa Faro. All rights reserved.
//
import Foundation
struct RouteResults: Decodable {
var connections: [RouteConnection]
}
struct RouteConnection: Decodable {
var duration: String?
var from: RouteResultsStops
var to: RouteResultsStops
var sections: [Sections]?
struct RouteResultsStops: Decodable {
struct Station: Decodable {
var id: String
var name: String
var coordinate: Coordinate
struct Coordinate: Decodable {
var x: Double
var y: Double
}
}
var departureTimestamp: Int?
var arrivalTimestamp: Int?
var station: Station
}
struct Sections: Decodable {
struct Walk: Decodable {
var duration: Int?
}
struct Journey: Decodable {
var lineCode: String
var compagny: String
var category: String
var to: String
var passList: [RouteResultsStops]
public init(lineCode: String,
compagny: String,
category: String,
to: String,
passList: [RouteResultsStops]) {
self.lineCode = lineCode
self.compagny = compagny
self.category = category
self.to = to
self.passList = passList
}
enum CodingKeys: String, CodingKey {
case lineCode = "number"
case compagny = "operator"
case category
case to
case passList
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let lineCode = try container.decode(String.self, forKey: .lineCode)
let compagny = try container.decode(String.self, forKey: .compagny)
let category = try container.decode(String.self, forKey: .category)
let to = try container.decode(String.self, forKey: .to)
var passList =
try container.decode([RouteResultsStops].self, forKey: .passList)
for (index, result) in passList.enumerated() {
guard let stop = App.stops
.filter({ $0.sbbId == result.station.id })[safe: 0] else {
continue
}
var localisations = stop.localisations
for (index, localisation) in localisations.enumerated() {
localisations[index].destinations = localisation.destinations.filter({
$0.line == lineCode &&
$0.destinationTransportAPI == to
})
}
localisations = localisations.filter({ !$0.destinations.isEmpty })
guard let localisation = localisations[safe: 0] else {
continue
}
passList[index].station.coordinate.x =
localisation.location.coordinate.latitude
passList[index].station.coordinate.y =
localisation.location.coordinate.longitude
}
self.init(lineCode: lineCode,
compagny: compagny,
category: category,
to: to,
passList: passList)
}
}
var walk: Walk?
var journey: Journey?
var departure: RouteResultsStops
var arrival: RouteResultsStops
}
}
| 28.137931 | 82 | 0.599571 |
eb0aa6ea50c8ed4724fd8f36de64269c99fd3abf | 837 | /*
Copyright 2017 Ryuichi Intellectual Property and the Yanagiba project contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import XCTest
#if !os(macOS)
public func allTests() -> [XCTestCaseEntry] {
return [
testCase(LocatableNodeTests.allTests),
testCase(TopLevelDeclarationTests.allTests),
]
}
#endif
| 31 | 85 | 0.750299 |
9188415ffde7579890c52052ce295d71ccf2c602 | 2,499 | //
// ExtensionTests.swift
// SwiftlySalesforce
//
// For license & details see: https://www.github.com/mike4aday/SwiftlySalesforce
// Copyright (c) 2016. All rights reserved.
//
import XCTest
@testable import SwiftlySalesforce
class ExtensionTests: XCTestCase {
func testThatItParsesSalesforceDateTime() {
let dateString = "2015-09-21T13:31:23.909+0000"
let date = DateFormatter.salesforceDateTimeFormatter.date(from: dateString)
let comps = Calendar(identifier: .gregorian).dateComponents(in: TimeZone(abbreviation: "GMT")!, from: date!)
XCTAssertNotNil(date)
XCTAssertEqual(comps.year, 2015)
XCTAssertEqual(comps.month, 9)
XCTAssertEqual(comps.day, 21)
XCTAssertEqual(comps.hour, 13)
XCTAssertEqual(comps.minute, 31)
XCTAssertEqual(comps.second, 23)
}
func testThatItParsesSalesforceDate() {
let dateString = "2015-09-21"
let date = DateFormatter.salesforceDateFormatter.date(from: dateString)
XCTAssertNotNil(date)
let comps = Calendar(identifier: .gregorian).dateComponents(in: TimeZone(abbreviation: "GMT")!, from: date!)
XCTAssertEqual(comps.year, 2015)
XCTAssertEqual(comps.month, 9)
XCTAssertEqual(comps.day, 21)
}
func testThatItInitializesURLWithOptionalString() {
let s1: String? = nil
let s2: String? = "www.salesforce.com"
let url1 = URL(string: s1)
let url2 = URL(string: s2)
XCTAssertNil(url1)
XCTAssertNotNil(url2)
}
func testThatItGetsQueryItemsFromURL() {
let url = URL(string: "https://www.salesforce.com/test?name1=value1&name2=value2")!
let url2 = URL(string: "https://www.salesforce.com/test")!
XCTAssertEqual(url.value(forQueryItem: "name1"), "value1")
XCTAssertEqual(url.value(forQueryItem: "name2"), "value2")
XCTAssertNil(url.value(forQueryItem: "SOMETHING"))
XCTAssertNil(url2.value(forQueryItem: "SOMETHING"))
}
func testThatItInitsQueryComponentsFromURLString() {
let s = "https://www.salesforce.com"
let params: [String: Any] = ["q": "SELECT Id FROM Account", "Age": 23, "City": ""]
let comps = URLComponents(string: s, parameters: params)!
let url = comps.url
debugPrint(comps)
XCTAssertEqual("www.salesforce.com", url?.host)
XCTAssertTrue(comps.queryItems!.count == 3)
XCTAssertTrue(comps.queryItems!.contains(URLQueryItem(name: "Age", value: "23")))
XCTAssertTrue(comps.queryItems!.contains(URLQueryItem(name: "q", value: "SELECT Id FROM Account")))
XCTAssertTrue(comps.queryItems!.contains(URLQueryItem(name: "City", value: "")))
}
}
| 32.454545 | 110 | 0.728691 |
7175a149c16e59d8305152276e70d9cc8735b4c2 | 4,801 | //
// EventValidator.swift
// Split
//
// Created by Javier L. Avrudsky on 21/01/2019.
// Copyright © 2019 Split. All rights reserved.
//
import Foundation
/**
A validator for Track events
*/
protocol EventValidator {
///
/// Validates a split change instance
///
/// - Parameters:
/// - key: Matching key to validate
/// - trafficTypeName: Traffic type to validate
/// - eventTypeId: Event type to validate
/// - value: track value to validate
/// - Returns: nil when validations succeded, otherwise ValidationErrorInfo instance
///
func validate(key: String?, trafficTypeName: String?,
eventTypeId: String?, value: Double?,
properties: [String: Any]?) -> ValidationErrorInfo?
}
class DefaultEventValidator: EventValidator {
private let kMaxMatchingKeyLength = ValidationConfig.default.maximumKeyLength
private let kTrackEventNameValidationPattern = ValidationConfig.default.trackEventNamePattern
var keyValidator: KeyValidator
var splitCache: SplitCacheProtocol
init(splitCache: SplitCacheProtocol) {
keyValidator = DefaultKeyValidator()
self.splitCache = splitCache
}
func validate(key: String?, trafficTypeName: String?,
eventTypeId: String?, value: Double?, properties: [String: Any]?) -> ValidationErrorInfo? {
if let resultInfo = keyValidator.validate(matchingKey: key, bucketingKey: nil) {
return resultInfo
}
if trafficTypeName == nil {
return ValidationErrorInfo(error: .some,
message: "you passed a null or undefined traffic_type_name, " +
"traffic_type_name must be a non-empty string")
}
if trafficTypeName!.isEmpty() {
return ValidationErrorInfo(error: .some,
message: "you passed an empty traffic_type_name, " +
"traffic_type_name must be a non-empty string")
}
if eventTypeId == nil {
return ValidationErrorInfo(error: .some,
message: "you passed a null or undefined event_type, " +
"event_type must be a non-empty String")
}
if eventTypeId!.isEmpty() {
return ValidationErrorInfo(error: .some,
message: "you passed an empty event_type, " +
"event_type must be a non-empty String")
}
if !isTypeValid(eventTypeId!) {
return ValidationErrorInfo(error: .some,
message:
"you passed \(eventTypeId ?? "null"), event name must adhere " +
"to the regular expression \(kTrackEventNameValidationPattern). " +
"This means an event name must be alphanumeric, cannot be more than 80 characters long, " +
"and can only include a dash, underscore, " +
"period, or colon as separators of alphanumeric characters")
}
var validationInfo: ValidationErrorInfo?
if trafficTypeName!.hasUpperCaseChar() {
validationInfo = ValidationErrorInfo(warning: .trafficTypeNameHasUppercaseChars,
message:
"traffic_type_name should be all lowercase - converting string to lowercase")
}
if !splitCache.exists(trafficType: trafficTypeName!) {
let message = "traffic_type_name \(trafficTypeName!) does not have any corresponding " +
"Splits in this environment, make sure you’re tracking " +
"your events to a valid traffic type defined in the Split console"
if validationInfo != nil {
validationInfo!.addWarning(.trafficTypeWithoutSplitInEnvironment, message: message)
} else {
validationInfo = ValidationErrorInfo(warning: .trafficTypeWithoutSplitInEnvironment, message: message)
}
}
return validationInfo
}
private func isTypeValid(_ typeName: String) -> Bool {
let validationRegex: NSRegularExpression? = try? NSRegularExpression(pattern: kTrackEventNameValidationPattern,
options: .caseInsensitive)
if let regex = validationRegex {
let range = regex.rangeOfFirstMatch(in: typeName, options: [],
range: NSRange(location: 0,
length: typeName.count))
return range.location == 0 && range.length == typeName.count
}
return false
}
}
| 41.034188 | 119 | 0.583837 |
717f061ea4038af0b69561a38e487f73d8e6d8ef | 2,172 | //
// AppDelegate.swift
// Date_String_URL
//
// Created by student on 2019/10/24.
// Copyright © 2019年 Libra. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.212766 | 285 | 0.755985 |
5bbccadfc72026770ded5cda530cca9c99e9ca92 | 1,868 | //
// CKRecordValue+Helpers.swift
// CloudKitWebServices
//
// Created by Marcin Krzyzanowski on 07/11/15.
// Copyright © 2015 Marcin Krzyżanowski. All rights reserved.
//
// TODO:
// - Location
// - Lists... [DOUBLE], [BYTES], ... etc
//
import CloudKit
extension CKRecordValue /*: CKDictionaryRepresentable */ {
func toCKDictionary() -> [String: AnyObject] {
var field = [String: AnyObject]()
if let value = self as? CKReference {
field = ["type": "REFERENCE", "value": ["recordName": value.recordID.recordName, "zone": value.recordID.zoneID.zoneName, "action": value.referenceAction.toCKWReferenceAction().rawValue]]
} else if let valueList = self as? [CKReference] where !valueList.isEmpty {
field = ["type": "REFERENCE_LIST", "value": valueList.map { $0.toCKDictionary() }]
} else if let value = self as? NSNumber where value.isReal() {
field = ["type": "DOUBLE", "value": value]
} else if let value = self as? NSNumber where !value.isReal() {
field = ["type": "INT64", "value": value]
} else if let value = self as? NSData {
field = ["type": "BYTES", "value": value.base64EncodedStringWithOptions([])]
} else if let value = self as? NSDate {
field = ["type": "TIMESTAMP", "value": Int(value.timeIntervalSince1970 * 1000) as NSNumber]
} else if let value = self as? String {
field = ["type": "STRING", "value": value]
} else if let value = self as? CKWAsset, valueInfo = value.info as? CKWAsset.Info {
field = ["type": "ASSETID", "value": valueInfo.toCKDictionary()]
} else if let valueList = self as? [CKWAsset] where !valueList.isEmpty {
field = ["type": "ASSETID_LIST", "value": valueList.map({ $0.toCKDictionary() })]
}
return field
}
}
| 46.7 | 198 | 0.607602 |
29a55c51f58ef2a90d6d8104c70c9a06180592a3 | 299 | //
// File.swift
//
//
// Created by Jesulonimi on 2/20/21.
//
import Foundation
public class EvalDeltaKeyValue : Codable {
var key:String?;
var value:EvalDelta?;
enum CodingKeys:String,CodingKey {
case key="key"
case value="value"
}
init() {
}
}
| 13.590909 | 42 | 0.575251 |
ef22d6b21e73082e790f55f2fb4f85f899ce1332 | 1,235 | //
// DemoUITests.swift
// DemoUITests
//
// Created by Shinji Hayashi on 2017/12/22.
// Copyright © 2017年 shin884. All rights reserved.
//
import XCTest
class DemoUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 33.378378 | 182 | 0.660729 |
914d8bd1424f9205051c4e94912e0049858d1125 | 5,189 | //
// DefaultPropertyDecoder.swift
// xibdump
//
// Created by Sergey Atroschenko on 4/1/19.
//
import Cocoa
class DefaultParameterDecoder: NSObject, TagDecoderProtocol {
let parameterName: String
let tagName: String
let tagMapper: [String: String]?
var topLevelDecoder: Bool = true
static let uiParametersNamesList: [String] = [
"UIOpaque", "UIPreferredMaxLayoutWidth", "UIMinimumScaleFactor", "UINumberOfLines", "UITag", "UIAlpha",
"UIMinimumFontSize", "UIProgress", "UIValue", "UIMinValue", "UIMaxValue", "UISelectedSegmentIndex",
"UINumberOfPages", "UICurrentPage", "UIMinimumValue", "UIMaximumValue", "UIStepValue", "UIMaximumZoomScale",
"UIMinimumZoomScale", "UIMinuteInterval", "UICountDownDuration", "UISectionIndexMinimumDisplayRowCount",
"UIEstimatedRowHeight", "UIRowHeight", "UISectionHeaderHeight", "UIEstimatedSectionHeaderHeight",
"UISectionFooterHeight", "UIEstimatedSectionFooterHeight", "UIIndentationLevel", "UIIndentationWidth"
]
static func allDecoders() -> [TagDecoderProtocol] {
var result = [TagDecoderProtocol]()
DefaultParameterDecoder.uiParametersNamesList.forEach { name in
result.append(DefaultParameterDecoder(uiKitName: name))
}
result.append(contentsOf: [
DefaultParameterDecoder(parameterName: "UIStackViewSpacing", tagName: "spacing"),
DefaultParameterDecoder(parameterName: "MTKViewClearDepthCoderKey", tagName: "clearDepth"),
DefaultParameterDecoder(parameterName: "MTKViewClearStencilCoderKey", tagName: "clearStencil"),
DefaultParameterDecoder(parameterName: "MTKViewSampleCountCoderKey", tagName: "sampleCount"),
DefaultParameterDecoder(parameterName: "MTKViewPreferredFramesPerSecondCoderKey", tagName: "preferredFramesPerSecond"),
DefaultParameterDecoder(parameterName: "ibPreferredRenderingAPI", tagName: "preferredRenderingAPI"),
DefaultParameterDecoder(parameterName: "_preferredFramesPerSecond", tagName: "preferredFramesPerSecond"),
DefaultParameterDecoder(parameterName: "UITabBarItemWidth", tagName: "itemWidth"),
DefaultParameterDecoder(parameterName: "UITabBarItemSpacing", tagName: "itemSpacing"),
DefaultParameterDecoder(parameterName: "UIInsetsContentViewsToSafeArea", tagName: "contentViewInsetsToSafeArea"),
DefaultParameterDecoder(parameterName: "UILineSpacing", tagName: "minimumLineSpacing"),
DefaultParameterDecoder(parameterName: "UIInteritemSpacing", tagName: "minimumInteritemSpacing"),
DefaultParameterDecoder(parameterName: "UITapRecognizer.numberOfTapsRequired", tagName: "numberOfTapsRequired"),
DefaultParameterDecoder(parameterName: "UITapRecognizer.numberOfTouchesRequired", tagName: "numberOfTouchesRequired"),
DefaultParameterDecoder(parameterName: "UISwipeGestureRecognizer.numberOfTouchesRequired", tagName: "numberOfTouchesRequired"),
DefaultParameterDecoder(parameterName: "UIPanGestureRecognizer.maximumNumberOfTouches", tagName: "maximumNumberOfTouches"),
DefaultParameterDecoder(parameterName: "UIPanGestureRecognizer.minimumNumberOfTouches", tagName: "minimumNumberOfTouches"),
DefaultParameterDecoder(parameterName: "UILongPressGestureRecognizer.minimumPressDuration", tagName: "minimumPressDuration"),
DefaultParameterDecoder(parameterName: "UILongPressGestureRecognizer.allowableMovement", tagName: "allowableMovement")
])
result.append(contentsOf: ListParameterDecoder.all())
result.append(contentsOf: BoolParameterDecoder.all())
result.append(contentsOf: FirstStringDecoder.all())
return result
}
init(parameterName: String, tagName: String, tagMapper: [String: String]? = nil) {
self.parameterName = parameterName
self.tagName = tagName
self.tagMapper = tagMapper
super.init()
}
convenience init(uiKitName: String) {
self.init(parameterName: uiKitName, tagName: uiKitName.systemParameterName(), tagMapper: nil)
}
func handledClassNames() -> [String] {
return [Utils.decoderKey(parameterName: parameterName, className: "", isTopLevel: topLevelDecoder)]
}
func parse(parentObject: XibObject, parameter: XibParameterProtocol, context: ParserContext) -> TagDecoderResult {
if parameter.name == parameterName {
let parameterValue = parameter.stringValue()
var finalTagName = tagName
if let tagMapper = tagMapper {
let parentClassName = parentObject.originalClassName(context: context)
if let newTag = tagMapper[parentClassName] {
finalTagName = newTag
}
}
let tagParameter = TagParameter(name: finalTagName, value: parameterValue)
return .parameters([tagParameter], false)
}
return .empty(false)
}
}
| 50.872549 | 139 | 0.697244 |
d5b8adb77729ca92ab71febb93ed0147b5fdbfaa | 454 | // 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 Q<T where g:A{
enum S{
struct D{
var
a}}func d<T
| 32.428571 | 79 | 0.744493 |
011a55b0d5e23a4dcb2db544a6bb6e82d9bd542c | 359 | //
// File.swift
//
//
// Created by Dushant Singh on 2021-10-04.
//
import Foundation
public enum URLScheme {
case http, https
case other(scheme: String)
var rawValue: String {
switch self {
case .http: return "http"
case .https: return "https"
case .other(let scheme): return scheme
}
}
}
| 16.318182 | 46 | 0.568245 |
eb77f4d31a9c7ae6573a975a96cd44a9808d1a0f | 5,394 | //
// AuthorView.swift
// githubsample
//
// Created by Felipe Antonio Cardoso on 30/01/19.
// Copyright © 2019 Felipe Antonio Cardoso. All rights reserved.
//
import UIKit
class AuthorView: UIView {
lazy var avatarImageView: UIImageView = {
let imageView = UIImageView(forAutoLayout: ())
imageView.contentMode = UIView.ContentMode.scaleAspectFit
imageView.clipsToBounds = true
return imageView
}()
lazy var nameLabel: UILabel = {
let label = UILabel(forAutoLayout: ())
return label
}()
override func layoutSubviews() {
super.layoutSubviews()
avatarImageView.layer.cornerRadius = (avatarImageView.frame.size.width / 2.0)
avatarImageView.layer.borderWidth = 1.0
avatarImageView.layer.borderColor = UIColor.black.cgColor
}
override func didMoveToSuperview() {
super.didMoveToSuperview()
buildViewHierarchy()
setupConstraints()
}
func buildViewHierarchy() {
addSubview(avatarImageView)
addSubview(nameLabel)
}
func setupConstraints() {
setupAvatarImageViewConstraints()
setupNameLabelConstraints()
}
}
extension AuthorView {
private func setupAvatarImageViewConstraints() {
let leftConstraint = NSLayoutConstraint(
item: avatarImageView,
attribute: NSLayoutConstraint.Attribute.left,
relatedBy: NSLayoutConstraint.Relation.equal,
toItem: self,
attribute: NSLayoutConstraint.Attribute.left,
multiplier: 1,
constant: 0
)
let bottomConstraint = NSLayoutConstraint(
item: avatarImageView,
attribute: NSLayoutConstraint.Attribute.bottom,
relatedBy: NSLayoutConstraint.Relation.greaterThanOrEqual,
toItem: self,
attribute: NSLayoutConstraint.Attribute.bottom,
multiplier: 0.5,
constant: 0
)
let topConstraint = NSLayoutConstraint(
item: avatarImageView,
attribute: NSLayoutConstraint.Attribute.top,
relatedBy: NSLayoutConstraint.Relation.greaterThanOrEqual,
toItem: self,
attribute: NSLayoutConstraint.Attribute.top,
multiplier: 0.5,
constant: 0
)
let centerYConstraint = NSLayoutConstraint(
item: avatarImageView,
attribute: NSLayoutConstraint.Attribute.centerY,
relatedBy: NSLayoutConstraint.Relation.equal,
toItem: self,
attribute: NSLayoutConstraint.Attribute.centerY,
multiplier: 1,
constant: 0
)
let heightConstraint = NSLayoutConstraint(
item: avatarImageView,
attribute: NSLayoutConstraint.Attribute.height,
relatedBy: NSLayoutConstraint.Relation.equal,
toItem: nil,
attribute: NSLayoutConstraint.Attribute.notAnAttribute,
multiplier: 1,
constant: 28
)
let widthtConstraint = NSLayoutConstraint(
item: avatarImageView,
attribute: NSLayoutConstraint.Attribute.width,
relatedBy: NSLayoutConstraint.Relation.equal,
toItem: nil,
attribute: NSLayoutConstraint.Attribute.notAnAttribute,
multiplier: 1,
constant: 28
)
NSLayoutConstraint.activate([
leftConstraint,
bottomConstraint,
centerYConstraint,
topConstraint,
widthtConstraint,
heightConstraint
])
}
private func setupNameLabelConstraints() {
let leftConstraint = NSLayoutConstraint(
item: nameLabel,
attribute: NSLayoutConstraint.Attribute.left,
relatedBy: NSLayoutConstraint.Relation.equal,
toItem: avatarImageView,
attribute: NSLayoutConstraint.Attribute.right,
multiplier: 1,
constant: 8
)
let rightConstraint = NSLayoutConstraint(
item: nameLabel,
attribute: NSLayoutConstraint.Attribute.right,
relatedBy: NSLayoutConstraint.Relation.equal,
toItem: self,
attribute: NSLayoutConstraint.Attribute.right,
multiplier: 1,
constant: 0
)
let bottomConstraint = NSLayoutConstraint(
item: nameLabel,
attribute: NSLayoutConstraint.Attribute.bottom,
relatedBy: NSLayoutConstraint.Relation.equal,
toItem: self,
attribute: NSLayoutConstraint.Attribute.bottom,
multiplier: 1,
constant: 0
)
let topConstraint = NSLayoutConstraint(
item: nameLabel,
attribute: NSLayoutConstraint.Attribute.top,
relatedBy: NSLayoutConstraint.Relation.equal,
toItem: self,
attribute: NSLayoutConstraint.Attribute.top,
multiplier: 1,
constant: 0
)
NSLayoutConstraint.activate([
leftConstraint,
rightConstraint,
bottomConstraint,
topConstraint
])
}
}
| 30.474576 | 85 | 0.591212 |
227b8f31f23ec3774be10907f3627d454325b34a | 2,409 | // RUN: %empty-directory(%t)
// RUN: %clang -c -v %target-cc-options -g -O0 -isysroot %sdk %S/Inputs/isPrespecialized.cpp -o %t/isPrespecialized.o -I %clang-include-dir -I %swift_src_root/include/ -I %llvm_src_root/include -I %llvm_obj_root/include -L %clang-include-dir/../lib/swift/macosx
// RUN: %target-build-swift -v %mcp_opt %s %t/isPrespecialized.o -import-objc-header %S/Inputs/isPrespecialized.h -Xfrontend -prespecialize-generic-metadata -target %module-target-future -lc++ -L %clang-include-dir/../lib/swift/macosx -sdk %sdk -o %t/main
// RUN: %target-codesign %t/main
// RUN: %target-run %t/main
// REQUIRES: OS=macosx
// REQUIRES: executable_test
// UNSUPPORTED: use_os_stdlib
// UNSUPPORTED: swift_test_mode_optimize
// UNSUPPORTED: swift_test_mode_optimize_size
func ptr<T>(to ty: T.Type) -> UnsafeMutableRawPointer {
UnsafeMutableRawPointer(mutating: unsafePointerToMetadata(of: ty))!
}
func unsafePointerToMetadata<T>(of ty: T.Type) -> UnsafePointer<T.Type> {
unsafeBitCast(ty, to: UnsafePointer<T.Type>.self)
}
protocol Natural {}
enum Zero : Natural {}
enum Successor<N : Natural> : Natural {}
extension Natural {
static func withSuccessor<
Invocation : WithSuccessorInvocation
>
(
invoke invocation: Invocation
)
-> Invocation.Return
{
invocation.invoke(Successor<Self>.self)
}
static func withSuccessor<
Invocation : WithSuccessorInvocation
>
(
offsetBy count: UInt,
invoke invocation: Invocation
)
-> Invocation.Return
{
if isCanonicalStaticallySpecializedGenericMetadata(ptr(to: Self.self)) {
fatalError()
}
switch count {
case 0:
return invocation.invoke(Self.self)
case 1:
return withSuccessor(invoke: invocation)
default:
return Successor<Self>.withSuccessor(
offsetBy: count - 1,
invoke: invocation
)
}
}
}
protocol WithSuccessorInvocation {
associatedtype Return
func invoke<N : Natural>( _ t: N.Type) -> Return
}
struct PointerInvocation : WithSuccessorInvocation {
typealias Return = UnsafeMutableRawPointer
func invoke<N : Natural>(_ t: N.Type) -> Return {
ptr(to: t)
}
}
allocateDirtyAndFreeChunk()
_ = Zero.withSuccessor(offsetBy: 10000, invoke: PointerInvocation())
| 29.024096 | 261 | 0.664591 |
feb0e00093fb110673246fd185ac0de41d22ecc0 | 262 | public enum Mimetype: String {
case any = "*"
case applicationJson = "application/json"
case applicationFormURLEncoded = "application/x-www-form-urlencoded"
case applicationOctetStream = "application/octet-stream"
}
| 7.081081 | 72 | 0.652672 |
fcfcdaacda908d348473026538fb2df7d080f12e | 2,088 | //
// MapTableViewCell.swift
// HandyAccess
//
// Created by Miti Shah on 2/18/17.
// Copyright © 2017 NYCHandyAccess. All rights reserved.
//
import UIKit
class MapTableViewCell: UITableViewCell {
static let cellIdentifier = "mapTableViewCellIdentifier"
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: .default, reuseIdentifier: reuseIdentifier)
self.addSubview(mapNameLabel)
self.addSubview(mapDescriptionLabel)
self.selectionStyle = .none
self.mapNameLabel.snp.makeConstraints { (view) in
view.leading.top.equalToSuperview().offset(8)
view.trailing.equalToSuperview().inset(8)
}
self.mapDescriptionLabel.snp.makeConstraints { (view) in
view.top.equalTo(self.mapNameLabel.snp.bottom).offset(8)
view.leading.equalToSuperview().offset(8)
view.trailing.bottom.equalToSuperview().inset(8)
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
let mapNameLabel: UILabel = {
let label = UILabel()
label.text = "Location Name"
label.font = UIFont.systemFont(ofSize: 20, weight: 8)
label.numberOfLines = 0
return label
}()
let mapDescriptionLabel: UILabel = {
let label = UILabel()
label.text = "Location Description"
label.font = UIFont.systemFont(ofSize: 16, weight: 6)
label.numberOfLines = 0
return label
}()
}
| 31.636364 | 78 | 0.560345 |
873081d95d98f9acce791681df032944a84af0a4 | 440 |
//@@parrot-mock
class MockExampleDataFetcherWithMultipleCompletionParameters: ExampleDataFetcherWithMultipleCOmpletionParameters {
final class Stub {
var fetchCallCount = 0
var fetchCalledWith = [(String?, String?) -> ()]()
}
var stub = Stub()
func parrotResetMock() {
stub = Stub()
}
func fetch(completion: @escaping (String?, String?) -> ()) {
stub.fetchCallCount += 1
stub.fetchCalledWith.append(completion)
}
} | 20 | 114 | 0.709091 |
48e6a4cf951e50e9c7d0f765bf0f9abaa3b56c99 | 2,556 | //
// ViewController.swift
// iOSEngineerCodeCheck
//
// Created by 史 翔新 on 2020/04/20.
// Copyright © 2020 YUMEMI Inc. All rights reserved.
//
import UIKit
final class SearchViewController: UIViewController {
@IBOutlet private weak var searchBar: UISearchBar!
@IBOutlet private weak var tableView: UITableView!
private var presenter: SearchPresenterInput!
func inject(presenter: SearchPresenterInput) {
self.presenter = presenter
}
override func viewDidLoad() {
super.viewDidLoad()
setup()
presenter.viewDidLoad()
}
private func setup() {
tableView.estimatedRowHeight = 118.5
tableView.rowHeight = UITableView.automaticDimension
tableView.register(R.nib.repositoryCell)
}
}
extension SearchViewController: UISearchBarDelegate {
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
presenter.didTapSearchButton(text: searchBar.text)
}
}
extension SearchViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
presenter.didSelectRow(at: indexPath)
}
}
extension SearchViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return presenter.numberOfRepos
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.cell, for: indexPath)!
if let repo = presenter.repo(forRow: indexPath.row) {
cell.setCell(repo: repo, languageColor: repo.gitHubColor!)
}
return cell
}
}
extension SearchViewController: SearchPresenterOutput {
func updateRepos(_ repos: [Repo]) {
tableView.reloadData()
//tableView.insertRows(at: [index], with: .fade)
}
func transitionToDetail(repo: Repo) {
let detailVC = R.storyboard.detail.instantiateInitialViewController()!
let model = DetailModel(repo: repo)
let presenter = DetailPresenter(repo: repo, view: detailVC as DetailPresenterOutput, model: model)
detailVC.inject(presenter: presenter)
navigationController?.present(detailVC, animated: true, completion: nil)
}
func closeKeyboard() {
searchBar.resignFirstResponder()
}
}
| 29.37931 | 106 | 0.678404 |
081a5d5c6122df37a3f8512a05534351f3727f4c | 1,833 | //
// ThrowingClosurePublisher.swift
// ClosurePublisher
//
// Created by Tim Gymnich on 7/10/19.
//
import Combine
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension Publishers {
/// In contrast with `Publishers.Just`, a `Closure` publisher will evaluate it's closure on every receive call.
public struct ThrowingClosure<ReturnType>: Publisher {
public typealias Output = ReturnType
public typealias Failure = Error
private var closure: () throws -> ReturnType
public init(closure: @escaping () throws -> ReturnType) {
self.closure = closure
}
public func receive<S>(subscriber: S) where S : Subscriber, ThrowingClosure.Failure == S.Failure, ThrowingClosure.Output == S.Input {
let subscription = ThrowingClosureSubscription(subscriber: subscriber, closure: closure)
subscriber.receive(subscription: subscription)
}
}
private final class ThrowingClosureSubscription<SubscriberType: Subscriber, ReturnType>: Subscription where SubscriberType.Input == ReturnType, SubscriberType.Failure == Error {
private var subscriber: SubscriberType?
private var closure: () throws -> ReturnType
typealias ErrorType = Error
init(subscriber: SubscriberType, closure: @escaping () throws -> ReturnType) {
self.subscriber = subscriber
self.closure = closure
}
func request(_ demand: Subscribers.Demand) {
do {
_ = subscriber?.receive(try closure())
} catch {
_ = subscriber?.receive(completion: .failure(error))
}
}
func cancel() {
self.subscriber = nil
}
}
}
| 33.327273 | 181 | 0.610475 |
095ccfa6b4d3d30bbeea6cc473606ca064f11d02 | 1,293 | //
// ExitButtonSection.swift
//
//
// Created by Jevon Mao on 1/30/21.
//
import SwiftUI
@available(iOS 13.0, tvOS 13.0, *)
struct ExitButtonSection: View {
//Action is closing the alert or modal on tap
var action: () -> Void
var buttonSizeConstant: CGFloat {
screenSize.width < 400 ? 40-(1000-screenSize.width)/80 : 40
}
@EnvironmentObject var schemaStore: PermissionSchemaStore
var body: some View {
Button(action: {
#if !os(tvOS)
let haptics = HapticsManager()
if schemaStore.shouldStayInPresentation {
haptics.notificationImpact(.error)
}
#endif
action()
}, label: {
Circle()
.fill(Color(.systemGray4))
.frame(width: buttonSizeConstant, height: buttonSizeConstant)
.overlay(
Image(systemName: "xmark")
.font(.system(size: 18, weight: .bold, design: .rounded))
.minimumScaleFactor(0.2)
.foregroundColor(Color(.systemGray))
.padding(4)
)
})
.accessibility(identifier: "Exit button")
}
}
| 28.733333 | 81 | 0.507347 |
c122edb22cdb041d094dfcad9fc889a0a58b05ed | 1,169 |
// RUN: %target-swift-emit-silgen -module-name force_cast_chained_optional %s | %FileCheck %s
class Foo {
var bar: Bar!
}
class Bar {
var bas: C!
}
class C {}
class D: C {}
// CHECK-LABEL: sil hidden [ossa] @$s27force_cast_chained_optional4testyAA1DCAA3FooCF
// CHECK: bb0([[ARG:%.*]] : @guaranteed $Foo):
// CHECK: class_method [[ARG]] : $Foo, #Foo.bar!getter : (Foo) -> () -> Bar?, $@convention(method) (@guaranteed Foo) ->
// CHECK: select_enum_addr {{%.*}}
// CHECK: cond_br {{%.*}}, [[SOME_BAR:bb[0-9]+]], [[NO_BAR:bb[0-9]+]]
//
// CHECK: [[SOME_BAR]]:
// CHECK: [[PAYLOAD_ADDR:%.*]] = unchecked_take_enum_data_addr {{%.*}} : $*Optional<Bar>
// CHECK: [[BAR:%.*]] = load [copy] [[PAYLOAD_ADDR]]
// CHECK: [[BORROWED_BAR:%.*]] = begin_borrow [[BAR]]
// CHECK: [[METHOD:%.*]] = class_method [[BORROWED_BAR]] : $Bar, #Bar.bas!getter : (Bar) -> () -> C?, $@convention(method) (@guaranteed Bar) ->
// CHECK: apply [[METHOD]]([[BORROWED_BAR]])
// CHECK: end_borrow [[BORROWED_BAR]]
// CHECK: unconditional_checked_cast {{%.*}} : $C to D
//
// CHECK: [[NO_BAR]]:
// CHECK: unreachable
func test(_ x: Foo) -> D {
return x.bar?.bas as! D
}
| 33.4 | 145 | 0.597092 |
48e7b0268b27581d737d4906dd325fca3cd2a16c | 2,323 | /*
Copyright 2016 Ryuichi Intellectual Property and the Yanagiba project contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import XCTest
@testable import AST
class ParserBinaryOperatorExpressionTests: XCTestCase {
func testBinaryOperators() {
let testOps = [
// regular operators
"/",
"-",
"+",
"--",
"++",
"+=",
"=-",
"==",
"!*",
"*<",
"<>",
"<!>",
">?>?>",
"&|^~?",
">>>!!>>",
"??",
// dot operators
"..",
"...",
".......................",
"../",
"...++",
"..--"
]
for testOp in testOps {
for space in ["", " ", " "] {
let testCode = "foo\(space)\(testOp)\(space)bar"
let expectedCode = "foo \(testOp) bar"
parseExpressionAndTest(testCode, expectedCode, testClosure: { expr in
guard let biOperator = expr as? BinaryOperatorExpression else {
XCTFail("Failed in getting a binary operator expression")
return
}
XCTAssertEqual(biOperator.binaryOperator, testOp)
XCTAssertTrue(biOperator.leftExpression is IdentifierExpression)
XCTAssertTrue(biOperator.rightExpression is IdentifierExpression)
})
}
}
}
func testSourceRange() {
let testExprs: [(testString: String, expectedEndColumn: Int)] = [
("foo / bar", 10),
("foo <> bar", 11),
("foo ... bar", 12),
]
for t in testExprs {
parseExpressionAndTest(t.testString, t.testString, testClosure: { expr in
XCTAssertEqual(expr.sourceRange, getRange(1, 1, 1, t.expectedEndColumn))
})
}
}
static var allTests = [
("testBinaryOperators", testBinaryOperators),
("testSourceRange", testSourceRange),
]
}
| 27.329412 | 85 | 0.582867 |
082ca3dca007f3c320a6fefd72b00b84e55e0be5 | 1,443 | import UIKit
/**
# ABSTRACTION
Alt sınıfların ortak özelliklerini taşıyan ama nesnesi olmayan, inheritance veren soyutlanmış sınıftır.
## Notes:
1. Aşağıda Inheritance uygulanmamış ve uygulanmış kullanımına ait örnek bulabilirsiniz
## Abstraction Örneği
*/
// MARK: - Abstract Class
class Ticket {
var ticketNumber: String
var firstName: String
var lastName: String
init(_ ticketNumber: String, _ firstName: String, _ lastName: String) {
self.ticketNumber = ticketNumber
self.firstName = firstName
self.lastName = lastName
}
}
class BusTicket: Ticket {
var peronNumber: String
// MARK: - Constructor Method
init(_ ticketNumber: String, _ firstName: String, _ lastName: String, _ peronNumber: String) {
self.peronNumber = peronNumber
super.init(ticketNumber, firstName, lastName)
}
}
class FlightTicket: Ticket {
var gateNumber: String
// MARK: - Constructor Method
init(_ ticketNumber: String, _ firstName: String, _ lastName: String, _ gateNumber: String) {
self.gateNumber = gateNumber
super.init(ticketNumber, firstName, lastName)
}
}
var busTicket = BusTicket("1234", "Erdem", "Karakaya", "6")
var flightTicket = FlightTicket("TK1234", "Erdem", "Karakaya", "G-4")
// Yukarıdaki 2 bilette görüldüğü üzere Abstract Class olan Ticket Class özelliklerini kullandık fakat Ticket nesnesi hiç yaratmadık.
| 27.75 | 133 | 0.700624 |
d53a5dab7ef2dad73f84d3ad82b857a783912186 | 2,167 | //
// AppDelegate.swift
// DNAlertManager
//
// Created by mainone on 16/12/27.
// Copyright © 2016年 wjn. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.106383 | 285 | 0.755422 |
e6bc3c60dde084475afb3022d41475e09349b980 | 1,060 | //
// TrustPolicy.swift
// NetworkKit
//
// Created by Aleksandar Sergeev Petrov on 7.10.20.
//
import Foundation
import Alamofire
public typealias RevocationOptions = Alamofire.RevocationTrustEvaluator.Options
public enum APITrustPolicyType {
/// **THIS SHOULD NEVER BE USED IN PRODUCTION!**
case none
///
case host
///
case revocation(options: RevocationOptions)
///
case pinnedCertificates(certificatesProvider: PinnedCertificatesProvider)
///
case publicKeys(keysProvider: PublicKeysProvider)
}
public protocol PinnedCertificatesProvider {
var certificates: [SecCertificate] { get }
var acceptSelfSignedCertificates: Bool { get }
}
extension PinnedCertificatesProvider {
var certificates: [SecCertificate] {
Bundle.main.af.certificates
}
var acceptSelfSignedCertificates: Bool {
false
}
}
public protocol PublicKeysProvider {
var keys: [SecKey] { get }
}
extension PinnedCertificatesProvider {
var keys: [SecKey] {
Bundle.main.af.publicKeys
}
}
| 21.2 | 79 | 0.708491 |
dd3ef3a3c7b1a1ede1aaa7ac3d0523a080e5d5ad | 17,805 | // Copyright 2020-2021 Dave Verwer, Sven A. Schmidt, and other contributors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
@testable import App
import XCTVapor
import SnapshotTesting
import SPIManifest
class PackageShowModelTests: SnapshotTestCase {
typealias PackageResult = PackageController.PackageResult
func test_init_no_packageName() async throws {
// Tests behaviour when we're lacking data
// setup package without package name
let pkg = try savePackage(on: app.db, "1".url)
try await Repository(package: pkg, name: "bar", owner: "foo").save(on: app.db)
let version = try App.Version(package: pkg,
latest: .defaultBranch,
packageName: nil,
reference: .branch("main"))
try await version.save(on: app.db)
let pr = try await PackageResult.query(on: app.db, owner: "foo", repository: "bar")
// MUT
let m = PackageShow.Model(result: pr,
history: nil,
productCounts: .mock,
swiftVersionBuildInfo: nil,
platformBuildInfo: nil)
// validate
XCTAssertNotNil(m)
XCTAssertEqual(m?.title, "bar")
}
func test_gitHubOwnerUrl() throws {
var model = PackageShow.Model.mock
model.repositoryOwner = "owner"
XCTAssertEqual(model.gitHubOwnerUrl, "https://github.com/owner")
}
func test_gitHubRepositoryUrl() throws {
var model = PackageShow.Model.mock
model.repositoryOwner = "owner"
model.repositoryName = "repository"
XCTAssertEqual(model.gitHubRepositoryUrl, "https://github.com/owner/repository")
}
func test_history() throws {
var model = PackageShow.Model.mock
model.history = .init(
since: "7 months",
commitCount: .init(label: "12 commits", url: "https://example.com/commits.html"),
releaseCount: .init(label: "2 releases", url: "https://example.com/releases.html")
)
let renderedHistory = model.historyListItem().render(indentedBy: .spaces(2))
assertSnapshot(matching: renderedHistory, as: .lines)
}
func test_history_archived_package() throws {
var model = PackageShow.Model.mock
model.history = .init(
since: "7 months",
commitCount: .init(label: "12 commits", url: "https://example.com/commits.html"),
releaseCount: .init(label: "2 releases", url: "https://example.com/releases.html")
)
model.isArchived = true
let renderedHistory = model.historyListItem().render(indentedBy: .spaces(2))
assertSnapshot(matching: renderedHistory, as: .lines)
}
func test_archived_warning_line_for_active_package() throws {
var model = PackageShow.Model.mock
model.isArchived = false
let renderedHistory = model.archivedListItem().render(indentedBy: .spaces(2))
assertSnapshot(matching: renderedHistory, as: .lines)
}
func test_archived_warning_line_for_archived_package() throws {
var model = PackageShow.Model.mock
model.isArchived = true
let renderedHistory = model.archivedListItem().render(indentedBy: .spaces(2))
assertSnapshot(matching: renderedHistory, as: .lines)
}
func test_activity_variants__missing_open_issue() throws {
var model = PackageShow.Model.mock
model.activity?.openIssues = nil
let renderedActivity = model.activityListItem().render(indentedBy: .spaces(2))
assertSnapshot(matching: renderedActivity, as: .lines)
}
func test_activity_variants__missing_open_PRs() throws {
var model = PackageShow.Model.mock
model.activity?.openPullRequests = nil
let renderedActivity = model.activityListItem().render(indentedBy: .spaces(2))
assertSnapshot(matching: renderedActivity, as: .lines)
}
func test_activity_variants__missing_open_issues_and_PRs() throws {
var model = PackageShow.Model.mock
model.activity?.openIssues = nil
model.activity?.openPullRequests = nil
let renderedActivity = model.activityListItem().render(indentedBy: .spaces(2))
assertSnapshot(matching: renderedActivity, as: .lines)
}
func test_activity_variants__missing_last_closed_issue() throws {
var model = PackageShow.Model.mock
model.activity?.lastIssueClosedAt = nil
let renderedActivity = model.activityListItem().render(indentedBy: .spaces(2))
assertSnapshot(matching: renderedActivity, as: .lines)
}
func test_activity_variants__missing_last_closed_PR() throws {
var model = PackageShow.Model.mock
model.activity?.lastPullRequestClosedAt = nil
let renderedActivity = model.activityListItem().render(indentedBy: .spaces(2))
assertSnapshot(matching: renderedActivity, as: .lines)
}
func test_activity_variants__missing_last_closed_issue_and_PR() throws {
var model = PackageShow.Model.mock
model.activity?.lastIssueClosedAt = nil
model.activity?.lastPullRequestClosedAt = nil
let renderedActivity = model.activityListItem().render(indentedBy: .spaces(2))
assertSnapshot(matching: renderedActivity, as: .lines)
}
func test_activity_variants__missing_everything() throws {
var model = PackageShow.Model.mock
model.activity?.openIssues = nil
model.activity?.openPullRequests = nil
model.activity?.lastIssueClosedAt = nil
model.activity?.lastPullRequestClosedAt = nil
XCTAssertEqual(model.activityListItem().render(), "")
}
func test_dependenciesPhrase_with_dependencies() throws {
let model = PackageShow.Model.mock
XCTAssertEqual(model.dependenciesPhrase(), "This package depends on 2 other packages.")
}
func test_dependenciesPhrase_no_dependencies() throws {
var model = PackageShow.Model.mock
model.dependencies = []
XCTAssertEqual(model.dependenciesPhrase(), "This package has no package dependencies.")
}
func test_dependenciesPhrase_nil_dependencies() throws {
var model = PackageShow.Model.mock
model.dependencies = nil
XCTAssertEqual(model.dependenciesPhrase(), nil)
}
func test_stars_formatting() throws {
var model = PackageShow.Model.mock
model.stars = 999
XCTAssertEqual(model.starsListItem().render(), "<li class=\"stars\">999 stars</li>")
model.stars = 1_000
XCTAssertEqual(model.starsListItem().render(), "<li class=\"stars\">1,000 stars</li>")
model.stars = 1_000_000
XCTAssertEqual(model.starsListItem().render(), "<li class=\"stars\">1,000,000 stars</li>")
}
func test_num_libraries_formatting() throws {
var model = PackageShow.Model.mock
model.productCounts?.libraries = 0
XCTAssertEqual(model.librariesListItem().render(), "<li class=\"libraries\">No libraries</li>")
model.productCounts?.libraries = 1
XCTAssertEqual(model.librariesListItem().render(), "<li class=\"libraries\">1 library</li>")
model.productCounts?.libraries = 2
XCTAssertEqual(model.librariesListItem().render(), "<li class=\"libraries\">2 libraries</li>")
}
func test_num_executables_formatting() throws {
var model = PackageShow.Model.mock
model.productCounts?.executables = 0
XCTAssertEqual(model.executablesListItem().render(), "<li class=\"executables\">No executables</li>")
model.productCounts?.executables = 1
XCTAssertEqual(model.executablesListItem().render(), "<li class=\"executables\">1 executable</li>")
model.productCounts?.executables = 2
XCTAssertEqual(model.executablesListItem().render(), "<li class=\"executables\">2 executables</li>")
}
func test_BuildInfo_init() throws {
// ensure nil propagation when all versions' values are nil
// (the generic type is irrelevant, we're just using Int for simplicity)
XCTAssertNil(BuildInfo<Int>.init(stable: nil, beta: nil, latest: nil))
XCTAssertNotNil(BuildInfo<Int>.init(stable: .init(referenceName: "foo", results: 1),
beta: nil,
latest: nil))
}
func test_groupBuildInfo() throws {
let result1: BuildResults = .init(status5_3: .compatible,
status5_4: .compatible,
status5_5: .compatible,
status5_6: .compatible)
let result2: BuildResults = .init(status5_3: .incompatible,
status5_4: .incompatible,
status5_5: .incompatible,
status5_6: .incompatible)
let result3: BuildResults = .init(status5_3: .unknown,
status5_4: .unknown,
status5_5: .unknown,
status5_6: .unknown)
do { // three distinct groups
let buildInfo: BuildInfo = .init(stable: .init(referenceName: "1.2.3",
results: result1),
beta: .init(referenceName: "2.0.0-b1",
results: result2),
latest: .init(referenceName: "main",
results: result3))!
// MUT
let res = PackageShow.Model.groupBuildInfo(buildInfo)
// validate
XCTAssertEqual(res, [
.init(references: [.init(name: "1.2.3", kind: .release)], results: result1),
.init(references: [.init(name: "2.0.0-b1", kind: .preRelease)], results: result2),
.init(references: [.init(name: "main", kind: .defaultBranch)], results: result3),
])
}
do { // stable and latest share the same result and should be grouped
let buildInfo: BuildInfo = .init(stable: .init(referenceName: "1.2.3",
results: result1),
beta: .init(referenceName: "2.0.0-b1",
results: result2),
latest: .init(referenceName: "main",
results: result1))!
// MUT
let res = PackageShow.Model.groupBuildInfo(buildInfo)
// validate
XCTAssertEqual(res, [
.init(references: [.init(name: "1.2.3", kind: .release),
.init(name: "main", kind: .defaultBranch)], results: result1),
.init(references: [.init(name: "2.0.0-b1", kind: .preRelease)], results: result2),
])
}
}
func test_languagePlatformInfo() async throws {
// setup
let pkg = try savePackage(on: app.db, "1")
try await Repository(package: pkg,
defaultBranch: "default",
name: "bar",
owner: "foo").save(on: app.db)
try await [
try App.Version(package: pkg, reference: .branch("branch")),
try App.Version(package: pkg,
commitDate: daysAgo(1),
latest: .defaultBranch,
reference: .branch("default"),
supportedPlatforms: [.macos("10.15"), .ios("13")],
swiftVersions: ["5.2", "5.3"].asSwiftVersions),
try App.Version(package: pkg, reference: .tag(.init(1, 2, 3))),
try App.Version(package: pkg,
commitDate: daysAgo(3),
latest: .release,
reference: .tag(.init(2, 1, 0)),
supportedPlatforms: [.macos("10.13"), .ios("10")],
swiftVersions: ["4", "5"].asSwiftVersions),
try App.Version(package: pkg,
commitDate: daysAgo(2),
latest: .preRelease,
reference: .tag(.init(3, 0, 0, "beta")),
supportedPlatforms: [.macos("10.14"), .ios("13")],
swiftVersions: ["5", "5.2"].asSwiftVersions),
].save(on: app.db)
let pr = try await PackageResult.query(on: app.db,
owner: "foo",
repository: "bar")
// MUT
let lpInfo = PackageShow.Model
.languagePlatformInfo(packageUrl: "1",
defaultBranchVersion: pr.defaultBranchVersion,
releaseVersion: pr.releaseVersion,
preReleaseVersion: pr.preReleaseVersion)
// validate
XCTAssertEqual(lpInfo.stable?.link, .init(label: "2.1.0",
url: "1/releases/tag/2.1.0"))
XCTAssertEqual(lpInfo.stable?.swiftVersions, ["4", "5"])
XCTAssertEqual(lpInfo.stable?.platforms, [.macos("10.13"), .ios("10")])
XCTAssertEqual(lpInfo.beta?.link, .init(label: "3.0.0-beta",
url: "1/releases/tag/3.0.0-beta"))
XCTAssertEqual(lpInfo.beta?.swiftVersions, ["5", "5.2"])
XCTAssertEqual(lpInfo.beta?.platforms, [.macos("10.14"), .ios("13")])
XCTAssertEqual(lpInfo.latest?.link, .init(label: "default", url: "1"))
XCTAssertEqual(lpInfo.latest?.swiftVersions, ["5.2", "5.3"])
XCTAssertEqual(lpInfo.latest?.platforms, [.macos("10.15"), .ios("13")])
}
func test_packageDependencyCodeSnippet() {
XCTAssertEqual(
PackageShow.Model.packageDependencyCodeSnippet(
ref: .tag(.init("6.0.0-b1")!),
packageURL: "https://github.com/Alamofire/Alamofire.git"
),
".package(url: "https://github.com/Alamofire/Alamofire.git", from: "6.0.0-b1")")
XCTAssertEqual(
PackageShow.Model.packageDependencyCodeSnippet(
ref: .tag(.init("5.5.0")!),
packageURL: "https://github.com/Alamofire/Alamofire.git"
),
".package(url: "https://github.com/Alamofire/Alamofire.git", from: "5.5.0")"
)
XCTAssertEqual(
PackageShow.Model.packageDependencyCodeSnippet(
ref: .branch("main"),
packageURL: "https://github.com/Alamofire/Alamofire.git"
),
".package(url: "https://github.com/Alamofire/Alamofire.git", branch: "main")"
)
}
func test_packageDependencyCodeSnippets() {
XCTAssertEqual(
PackageShow.Model.packageDependencyCodeSnippets(
packageURL: "https://github.com/Alamofire/Alamofire.git",
defaultBranchReference: .branch("main"),
releaseReference: .tag(1, 2, 3),
preReleaseReference: nil
),
[
.defaultBranch: .init(label: "main",
url:".package(url: "https://github.com/Alamofire/Alamofire.git", branch: "main")"),
.release: .init(label: "1.2.3",
url: ".package(url: "https://github.com/Alamofire/Alamofire.git", from: "1.2.3")")
]
)
}
func test_relativeDocumentationURL() throws {
var model = PackageShow.Model.mock
model.repositoryOwner = "foo"
model.repositoryName = "bar"
// MUT
XCTAssertEqual(model.relativeDocumentationURL(reference: "main", target: "bazqux"),
"/foo/bar/main/documentation/bazqux")
model.repositoryOwner = "Foo"
model.repositoryName = "Bar"
// MUT
XCTAssertEqual(model.relativeDocumentationURL(reference: "Main", target: "BazQux"),
"/Foo/Bar/Main/documentation/bazqux")
}
}
// local typealiases / references to make tests more readable
fileprivate typealias Version = PackageShow.Model.Version
fileprivate typealias BuildInfo = PackageShow.Model.BuildInfo
fileprivate typealias BuildResults = PackageShow.Model.SwiftVersionResults
fileprivate typealias BuildStatusRow = PackageShow.Model.BuildStatusRow
private extension PackageShow.Model.ProductCounts {
static var mock: Self {
.init(libraries: 0, executables: 0)
}
}
| 44.736181 | 141 | 0.571356 |
e6bdccc7c0519c6bfb1dc2fe88fd2b595d88bc95 | 484 | //
// Feed.swift
// DecodingHeterogeneousArrays
//
// Created by Ben Scheirman on 5/28/19.
// Copyright © 2019 Fickle Bits, LLC. All rights reserved.
//
import Foundation
class Feed : Codable {
var posts: [Post] = []
init() {
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.posts = try container.decodeHeterogeneousArray(family: PostClassFamily.self, forKey: .posts)
}
}
| 22 | 105 | 0.669421 |
e4fc68cea323b2e4598a171e92f41f79c20b4025 | 1,101 | //
// BKLanguage.swift
// BaseKitSwift
//
// Created by ldc on 2020/6/2.
// Copyright © 2020 Xiamen Hanin. All rights reserved.
//
import Foundation
public class BKLanguage: NSObject {
public enum `Type`: String, Equatable, CustomStringConvertible {
case en, hans, hant, ja
public var description: String {
switch self {
case .en:
return "en"
case .hans:
return "zh-cn"
case .hant:
return "tc"
case .ja:
return "jp"
}
}
}
public static var current: Type {
let preferredLang = (Bundle.main.preferredLocalizations.first! as NSString)
if preferredLang.hasPrefix("zh") {
if preferredLang.hasPrefix("zh-Hant") {
return .hant
}else {
//zh-Hans
return .hans
}
}else if preferredLang.hasPrefix("ja") {
return .ja
}else {
return .en
}
}
}
| 22.9375 | 83 | 0.475931 |
4bc692400c2940df11fc69faf1407c6492db3d4e | 949 | import UIKit
class SettingsTableViewDataSource: NSObject, UITableViewDataSource {
let viewModel :SettingsViewModel
init(viewModel :SettingsViewModel) {
self.viewModel = viewModel
super.init()
}
func registerCellsIdentifiers(tableView: UITableView) {
tableView.registerCell(UITableViewCell.self)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel.settings.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = tableView.dequeueReusableCell(forIndexPath: indexPath)
switch viewModel.settings[indexPath.row] {
case .Acknowledgements:
cell.textLabel?.text = "Acknowledgements"
cell.accessoryType = .DisclosureIndicator
}
return cell
}
}
| 29.65625 | 109 | 0.67334 |
0eb88a3ccc3532988431d74dac113ec04c09816a | 11,851 | //
// The MIT License (MIT)
//
// Copyright (c) 2016 Srdan Rasic (@srdanrasic)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// A disposable is an object that can be used to cancel a signal observation.
///
/// Disposables are returned by `observe*` and `bind*` methods.
///
/// let disposable = signal.observe { ... }
///
/// Disposing the disposable cancels the observation. A signal is guaranteed not to
/// fire any event after is has been disposed.
///
/// disposable.dispose()
public protocol Disposable: Cancellable {
/// Dispose the signal observation or binding.
func dispose()
/// Returns `true` is already disposed.
var isDisposed: Bool { get }
}
extension Disposable {
@inlinable
public func cancel() {
dispose()
}
}
/// A disposable that cannot be disposed.
public struct NonDisposable: Disposable {
public static let instance = NonDisposable()
private init() {}
public func dispose() {}
public var isDisposed: Bool {
return false
}
}
/// A disposable that just encapsulates disposed state.
public final class SimpleDisposable: Disposable {
private let lock = NSRecursiveLock(name: "com.reactive_kit.simple_disposable")
private var _isDisposed: Bool
public var isDisposed: Bool {
get {
lock.lock(); defer { lock.unlock() }
return _isDisposed
}
set {
lock.lock(); defer { lock.unlock() }
_isDisposed = newValue
}
}
public func dispose() {
lock.lock(); defer { lock.unlock() }
_isDisposed = true
}
public init(isDisposed: Bool = false) {
self._isDisposed = isDisposed
}
}
/// A disposable that executes the given block upon disposing.
public final class BlockDisposable: Disposable {
private let lock = NSRecursiveLock(name: "com.reactive_kit.block_disposable")
private var handler: (() -> ())?
public var isDisposed: Bool {
lock.lock(); defer { lock.unlock() }
return handler == nil
}
public init(_ handler: @escaping () -> ()) {
self.handler = handler
}
public func dispose() {
lock.lock()
guard let handler = handler else {
lock.unlock()
return
}
self.handler = nil
lock.unlock()
handler()
}
}
/// A disposable that disposes itself upon deallocation.
public final class DeinitDisposable: Disposable {
private let lock = NSRecursiveLock(name: "com.reactive_kit.deinit_disposable")
private var _otherDisposable: Disposable?
public var otherDisposable: Disposable? {
set {
lock.lock(); defer { lock.unlock() }
_otherDisposable = newValue
}
get {
lock.lock(); defer { lock.unlock() }
return _otherDisposable
}
}
public var isDisposed: Bool {
lock.lock(); defer { lock.unlock() }
return _otherDisposable == nil
}
public init(disposable: Disposable) {
_otherDisposable = disposable
}
public func dispose() {
lock.lock()
guard let otherDisposable = _otherDisposable else {
lock.unlock()
return
}
_otherDisposable = nil
lock.unlock()
otherDisposable.dispose()
}
deinit {
dispose()
}
}
/// A disposable that disposes a collection of disposables upon its own disposing.
public final class CompositeDisposable: Disposable {
private let lock = NSRecursiveLock(name: "com.reactive_kit.composite_disposable")
private var disposables: [Disposable]?
public var isDisposed: Bool {
lock.lock(); defer { lock.unlock() }
return disposables == nil
}
public init() {
self.disposables = []
}
public init(_ disposables: [Disposable]) {
self.disposables = disposables
}
public func add(disposable: Disposable) {
lock.lock(); defer { lock.unlock() }
if disposables == nil {
disposable.dispose()
} else {
disposables = disposables.map { $0 + [disposable] }
}
}
public static func += (left: CompositeDisposable, right: Disposable) {
left.add(disposable: right)
}
public func dispose() {
lock.lock()
guard let disposables = disposables else {
lock.unlock()
return
}
self.disposables = nil
lock.unlock()
disposables.forEach { $0.dispose() }
}
}
/// A disposable that disposes other disposable upon its own disposing.
public final class SerialDisposable: Disposable {
private let lock = NSRecursiveLock(name: "com.reactive_kit.serial_disposable")
private var _isDisposed = false
public var isDisposed: Bool {
lock.lock(); defer { lock.unlock() }
return _isDisposed
}
/// Will dispose other disposable immediately if self is already disposed.
public var otherDisposable: Disposable? {
didSet {
lock.lock()
if _isDisposed {
let otherDisposable = self.otherDisposable
lock.unlock()
otherDisposable?.dispose()
} else {
lock.unlock()
}
}
}
public init(otherDisposable: Disposable?) {
self.otherDisposable = otherDisposable
}
public func dispose() {
lock.lock()
if !_isDisposed {
_isDisposed = true
let otherDisposable = self.otherDisposable
lock.unlock()
otherDisposable?.dispose()
} else {
lock.unlock()
}
}
}
/// A container of disposables that will dispose the disposables upon deinit.
/// A bag is a prefered way to handle disposables:
///
/// let bag = DisposeBag()
///
/// signal
/// .observe { ... }
/// .dispose(in: bag)
///
/// When bag gets deallocated, it will dispose all disposables it contains.
public protocol DisposeBagProtocol: Disposable {
func add(disposable: Disposable)
}
/// A container of disposables that will dispose the disposables upon deinit.
/// A bag is a prefered way to handle disposables:
///
/// let bag = DisposeBag()
///
/// signal
/// .observe { ... }
/// .dispose(in: bag)
///
/// When bag gets deallocated, it will dispose all disposables it contains.
public final class DisposeBag: DisposeBagProtocol {
private let lockDisposables = NSRecursiveLock(name: "com.reactive_kit.dispose_bag.lock_disposables")
private let lockSubject = NSRecursiveLock(name: "com.reactive_kit.dispose_bag.lock_subject")
private var disposables: [Disposable] = []
private var subject: ReplayOneSubject<Void, Never>? = nil
/// `true` if bag is empty, `false` otherwise.
public var isDisposed: Bool {
lockDisposables.lock(); defer { lockDisposables.unlock() }
return disposables.count == 0
}
public init() {
}
/// Add the given disposable to the bag.
/// Disposable will be disposed when the bag is deallocated.
public func add(disposable: Disposable) {
lockDisposables.lock(); defer { lockDisposables.unlock() }
disposables.append(disposable)
}
/// Add the given disposables to the bag.
/// Disposables will be disposed when the bag is deallocated.
public func add(disposables: [Disposable]) {
lockDisposables.lock(); defer { lockDisposables.unlock() }
self.disposables.append(contentsOf: disposables)
}
/// Add a disposable to a dispose bag.
public static func += (left: DisposeBag, right: Disposable) {
left.add(disposable: right)
}
/// Add multiple disposables to a dispose bag.
public static func += (left: DisposeBag, right: [Disposable]) {
left.add(disposables: right)
}
/// Disposes all disposables that are currenty in the bag.
public func dispose() {
lockDisposables.lock()
let disposables = self.disposables
self.disposables.removeAll()
lockDisposables.unlock()
disposables.forEach { $0.dispose() }
}
/// A signal that fires `completed` event when the bag gets deallocated.
public var deallocated: SafeSignal<Void> {
lockSubject.lock(); defer { lockSubject.unlock() }
if subject == nil {
subject = ReplayOneSubject()
}
return subject!.toSignal()
}
deinit {
dispose()
subject?.send(completion: .finished)
}
}
/// A type-erasing cancellable object that executes a provided closure when canceled (disposed).
/// The closure will be executed upon deinit if it has not been executed already.
public final class AnyCancellable: Disposable {
private let lock = NSRecursiveLock(name: "com.reactive_kit.any_cancellable")
private var handler: (() -> ())?
public var isDisposed: Bool {
lock.lock(); defer { lock.unlock() }
return handler == nil
}
public init(_ handler: @escaping () -> ()) {
self.handler = handler
}
deinit {
dispose()
}
public func dispose() {
lock.lock()
guard let handler = handler else {
lock.unlock()
return
}
self.handler = nil
lock.unlock()
handler()
}
}
extension AnyCancellable: Hashable {
public static func == (lhs: AnyCancellable, rhs: AnyCancellable) -> Bool {
return lhs === rhs
}
public func hash(into hasher: inout Hasher) {
hasher.combine(ObjectIdentifier(self))
}
}
extension AnyCancellable {
public convenience init(_ disposable: Disposable) {
self.init(disposable.dispose)
}
final public func store<C>(in collection: inout C) where C: RangeReplaceableCollection, C.Element == AnyCancellable {
collection.append(self)
}
final public func store(in set: inout Set<AnyCancellable>) {
set.insert(self)
}
}
extension Disposable {
/// Put the disposable in the given bag. Disposable will be disposed when
/// the bag is either deallocated or disposed.
public func dispose(in disposeBag: DisposeBagProtocol) {
disposeBag.add(disposable: self)
}
public func store(in disposeBag: DisposeBagProtocol) {
disposeBag.add(disposable: self)
}
public func store<C>(in collection: inout C) where C: RangeReplaceableCollection, C.Element == AnyCancellable {
collection.append(AnyCancellable(self))
}
public func store(in set: inout Set<AnyCancellable>) {
set.insert(AnyCancellable(self))
}
}
| 28.419664 | 121 | 0.626445 |
d5c4ad2f34e3115b3b999c3f21cb50d97792e07e | 4,966 | //
// GDAXSwiftTests.swift
// GDAXSwiftTests
//
// Created by Alexandre Barbier on 04/12/2017.
// Copyright © 2017 Alexandre Barbier. All rights reserved.
//
import XCTest
@testable import GDAXSwift
class GDAXSwiftTests: XCTestCase {
override func setUp() {
super.setUp()
//put your credentials here (GDAX API key secret etc)
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testTicker() {
let expect = expectation(description:"")
let sub = GDAX.feed.subscribeTicker(for: [gdax_value(from:.LTC, to:.BTC)]) { (message) in
XCTAssert(message.product_id == "LTC-BTC")
expect.fulfill()
}
waitForExpectations(timeout:5.0) { (error) in
sub.unsubscribe()
if error != nil {
XCTFail(error!.localizedDescription)
}
}
}
func testHeartbeat() {
let expect = expectation(description:"")
let sub = GDAX.feed.subscribeHeartbeat(for: [gdax_value(from:.LTC, to:.BTC)]) { (message) in
XCTAssert(message.product_id == "LTC-BTC")
expect.fulfill()
}
waitForExpectations(timeout:5.0) { (error) in
sub.unsubscribe()
if error != nil {
XCTFail(error!.localizedDescription)
}
}
}
func testFull() {
var expect: XCTestExpectation? = expectation(description:"")
let sub = GDAX.feed.subscribeFull(for: [gdax_value(from:.LTC, to:.BTC)]) { (message) in
XCTAssert(message.product_id == "LTC-BTC")
expect?.fulfill()
expect = nil
}
waitForExpectations(timeout:5.0) { (error) in
sub.unsubscribe()
if error != nil {
XCTFail(error!.localizedDescription)
}
}
}
func testProductlevel1() {
let expect = expectation(description:"")
GDAX.market.product(productId: "LTC-EUR").getBook { (response) in
expect.fulfill()
}
waitForExpectations(timeout:5.0) { (error) in
if error != nil {
XCTFail(error!.localizedDescription)
}
}
}
func testProductlevel2() {
let expect = expectation(description:"")
GDAX.market.product(productId: "LTC-EUR").getBook(level: 2) { (response) in
expect.fulfill()
}
waitForExpectations(timeout:5.0) { (error) in
if error != nil {
XCTFail(error!.localizedDescription)
}
}
}
func testProductlevel3() {
let expect = expectation(description:"")
GDAX.market.product(productId: "LTC-EUR").getBook(level: 3) { (response) in
expect.fulfill()
}
waitForExpectations(timeout:5.0) { (error) in
if error != nil {
XCTFail(error!.localizedDescription)
}
}
}
func testProductTrades() {
let expect = expectation(description:"")
GDAX.market.product(productId: "LTC-EUR").getTrades { (response, error) in
expect.fulfill()
}
waitForExpectations(timeout:5.0) { (error) in
if error != nil {
XCTFail(error!.localizedDescription)
}
}
}
func testProductStats() {
let expect = expectation(description:"")
GDAX.market.product(productId: "LTC-EUR").get24hStats { (response, error) in
XCTAssert(response != nil)
expect.fulfill()
}
waitForExpectations(timeout:5.0) { (error) in
if error != nil {
XCTFail(error!.localizedDescription)
}
}
}
func testProductLastTick() {
let expect = expectation(description:"")
GDAX.market.product(productId: "LTC-EUR").getLastTick { (response, error) in
expect.fulfill()
}
waitForExpectations(timeout:5.0) { (error) in
if error != nil {
XCTFail(error!.localizedDescription)
}
}
}
func testLevel2() {
let expect = expectation(description:"")
let sub = GDAX.feed.subscribeLevel2(for: [gdax_value(from: .LTC, to: .EUR)]) { (message) in
XCTAssert(message.product_id == "LTC-EUR")
expect.fulfill()
}
waitForExpectations(timeout:5.0) { (error) in
sub.unsubscribe()
if error != nil {
XCTFail(error!.localizedDescription)
}
}
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 28.215909 | 111 | 0.539871 |
0a807d181af33f63c490c664382c08cc2ac2b8bd | 983 | //
// PIDRunnerTests.swift
// PIDRunnerTests
//
// Created by Dawid Cieslak on 08/04/2018.
// Copyright © 2018 Dawid Cieslak. All rights reserved.
//
import XCTest
@testable import PIDRunner
class PIDRunnerTests: 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.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.567568 | 111 | 0.636826 |
ac842dfcf7ca6dfa858c5c910bd51680322223b1 | 9,674 | //
//
// UIDeviceIdentiferSwift.swift
// UIDeviceIdentifierSwift
//
// Created by andres on 29/10/2015.
// Copyright © 2015 Andres Ortiz. All rights reserved.
//
import Foundation
class UIDeviceIdentifierSwift {
func platform() -> String {
var size: size_t = 0;
sysctlbyname("hw.machine", nil, &size, nil, 0);
var machine = [CChar](count: Int(size), repeatedValue: 0)
sysctlbyname("hw.machine", &machine, &size, nil, 0);
return String.fromCString(machine)!
}
func platformString() -> String {
let modelDevice = platform()
if (modelDevice == "iPhone1,1") { return "iPhone 1G" };
if (modelDevice == "iPhone1,2") { return "iPhone 3G" };
if (modelDevice == "iPhone2,1") { return "iPhone 3GS" };
if (modelDevice == "iPhone3,1") { return "iPhone 4 (GSM)" };
if (modelDevice == "iPhone3,2") { return "iPhone 4 (GSM Rev A)" };
if (modelDevice == "iPhone3,3") { return "iPhone 4 (CDMA)" };
if (modelDevice == "iPhone4,1") { return "iPhone 4S" };
if (modelDevice == "iPhone5,1") { return "iPhone 5 (GSM)" };
if (modelDevice == "iPhone5,2") { return "iPhone 5 (GSM+CDMA)" };
if (modelDevice == "iPhone5,3") { return "iPhone 5C (GSM)" };
if (modelDevice == "iPhone5,4") { return "iPhone 5C (GSM+CDMA)" };
if (modelDevice == "iPhone6,1") { return "iPhone 5S (GSM)" };
if (modelDevice == "iPhone6,2") { return "iPhone 5S (GSM+CDMA)" };
if (modelDevice == "iPhone7,1") { return "iPhone 6 Plus" };
if (modelDevice == "iPhone7,2") { return "iPhone 6" };
if (modelDevice == "iPhone8,1") { return "iPhone 6s" };
if (modelDevice == "iPhone8,2") { return "iPhone 6s Plus" };
if (modelDevice == "iPod1,1") { return "iPod Touch 1G" };
if (modelDevice == "iPod2,1") { return "iPod Touch 2G" };
if (modelDevice == "iPod3,1") { return "iPod Touch 3G" };
if (modelDevice == "iPod4,1") { return "iPod Touch 4G" };
if (modelDevice == "iPod5,1") { return "iPod Touch 5G" };
if (modelDevice == "iPod7,1") { return "iPod Touch 6G" };
if (modelDevice == "iPad1,1") { return "iPad 1" };
if (modelDevice == "iPad2,1") { return "iPad 2 (WiFi)" };
if (modelDevice == "iPad2,2") { return "iPad 2 (GSM)" };
if (modelDevice == "iPad2,3") { return "iPad 2 (CDMA)" };
if (modelDevice == "iPad2,4") { return "iPad 2" };
if (modelDevice == "iPad2,5") { return "iPad Mini (WiFi)" };
if (modelDevice == "iPad2,6") { return "iPad Mini (GSM)" };
if (modelDevice == "iPad2,7") { return "iPad Mini (GSM+CDMA)" };
if (modelDevice == "iPad3,1") { return "iPad 3 (WiFi)" };
if (modelDevice == "iPad3,2") { return "iPad 3 (GSM+CDMA)" };
if (modelDevice == "iPad3,3") { return "iPad 3 (GSM)" };
if (modelDevice == "iPad3,4") { return "iPad 4 (WiFi)" };
if (modelDevice == "iPad3,5") { return "iPad 4 (GSM)" };
if (modelDevice == "iPad3,6") { return "iPad 4 (GSM+CDMA)" };
if (modelDevice == "iPad4,1") { return "iPad Air (WiFi)" };
if (modelDevice == "iPad4,2") { return "iPad Air (WiFi/Cellular)" };
if (modelDevice == "iPad4,3") { return "iPad Air (China)" };
if (modelDevice == "iPad4,4") { return "iPad Mini Retina (WiFi)" };
if (modelDevice == "iPad4,5") { return "iPad Mini Retina (WiFi/Cellular)" };
if (modelDevice == "iPad4,6") { return "iPad Mini Retina (China)" };
if (modelDevice == "iPad4,7") { return "iPad Mini 3 (WiFi)" };
if (modelDevice == "iPad4,8") { return "iPad Mini 3 (WiFi/Cellular)" };
if (modelDevice == "iPad5,1") { return "iPad Mini 4 (WiFi)" };
if (modelDevice == "iPad5,2") { return "iPad Mini 4 (WiFi/Cellular)" };
if (modelDevice == "iPad5,3") { return "iPad Air 2 (WiFi)" };
if (modelDevice == "iPad5,4") { return "iPad Air 2 (WiFi/Cellular)" };
if (modelDevice == "i386") { return "Simulator" };
if (modelDevice == "x86_64") { return "Simulator" };
return modelDevice
}
func platformStringSimple() -> String {
let modelDevice = platform()
if (modelDevice == "iPhone1,1") { return "iPhone 1G" };
if (modelDevice == "iPhone1,2") { return "iPhone 3G" };
if (modelDevice == "iPhone2,1") { return "iPhone 3GS" };
if (modelDevice == "iPhone3,1") { return "iPhone 4" };
if (modelDevice == "iPhone3,2") { return "iPhone 4" };
if (modelDevice == "iPhone3,3") { return "iPhone 4" };
if (modelDevice == "iPhone4,1") { return "iPhone 4S" };
if (modelDevice == "iPhone5,1") { return "iPhone 5" };
if (modelDevice == "iPhone5,2") { return "iPhone 5" };
if (modelDevice == "iPhone5,3") { return "iPhone 5C" };
if (modelDevice == "iPhone5,4") { return "iPhone 5C" };
if (modelDevice == "iPhone6,1") { return "iPhone 5S" };
if (modelDevice == "iPhone6,2") { return "iPhone 5S" };
if (modelDevice == "iPhone7,1") { return "iPhone 6 Plus" };
if (modelDevice == "iPhone7,2") { return "iPhone 6" };
if (modelDevice == "iPhone8,1") { return "iPhone 6s" };
if (modelDevice == "iPhone8,2") { return "iPhone 6s Plus" };
if (modelDevice == "iPod1,1") { return "iPod Touch 1G" };
if (modelDevice == "iPod2,1") { return "iPod Touch 2G" };
if (modelDevice == "iPod3,1") { return "iPod Touch 3G" };
if (modelDevice == "iPod4,1") { return "iPod Touch 4G" };
if (modelDevice == "iPod5,1") { return "iPod Touch 5G" };
if (modelDevice == "iPod7,1") { return "iPod Touch 6G" };
if (modelDevice == "iPad1,1") { return "iPad 1" };
if (modelDevice == "iPad2,1") { return "iPad 2" };
if (modelDevice == "iPad2,2") { return "iPad 2" };
if (modelDevice == "iPad2,3") { return "iPad 2" };
if (modelDevice == "iPad2,4") { return "iPad 2" };
if (modelDevice == "iPad2,5") { return "iPad Mini" };
if (modelDevice == "iPad2,6") { return "iPad Mini" };
if (modelDevice == "iPad2,7") { return "iPad Mini" };
if (modelDevice == "iPad3,1") { return "iPad 3" };
if (modelDevice == "iPad3,2") { return "iPad 3" };
if (modelDevice == "iPad3,3") { return "iPad 3" };
if (modelDevice == "iPad3,4") { return "iPad 4" };
if (modelDevice == "iPad3,5") { return "iPad 4" };
if (modelDevice == "iPad3,6") { return "iPad 4" };
if (modelDevice == "iPad4,1") { return "iPad Air" };
if (modelDevice == "iPad4,2") { return "iPad Air" };
if (modelDevice == "iPad4,3") { return "iPad Air" };
if (modelDevice == "iPad4,4") { return "iPad Mini Retina" };
if (modelDevice == "iPad4,5") { return "iPad Mini Retina" };
if (modelDevice == "iPad4,6") { return "iPad Mini Retina" };
if (modelDevice == "iPad4,7") { return "iPad Mini 3" };
if (modelDevice == "iPad4,8") { return "iPad Mini 3" };
if (modelDevice == "iPad5,1") { return "iPad Mini 4" };
if (modelDevice == "iPad5,2") { return "iPad Mini 4" };
if (modelDevice == "iPad5,3") { return "iPad Air 2" };
if (modelDevice == "iPad5,4") { return "iPad Air 2" };
if (modelDevice == "i386") { return "Simulator" };
if (modelDevice == "x86_64") { return "Simulator" };
return modelDevice
}
}
| 68.609929 | 86 | 0.423403 |
f7e47a4812ab7522f007195ccaa020a640ef7e9a | 3,384 | //
// ComponentsCheckboxes.swift
// Forms
//
// Created by Konrad on 6/3/20.
// Copyright © 2020 Limbo. All rights reserved.
//
import FormsUtils
import UIKit
public enum ComponentsCheckboxes: ComponentsList {
public static func checkbox() -> Checkbox {
let component = Checkbox()
component.batchUpdate {
component.images = Checkbox.State<LazyImage?>({ UIImage.from(name: "stop") })
.with(selected: { UIImage.from(name: "checkmark.square.fill") })
.with(disabledSelected: { UIImage.from(name: "checkmark.square.fill") })
component.imageSize = CGSize(size: 22)
component.marginEdgeInset = UIEdgeInsets(
vertical: 8,
horizontal: 16)
component.onSetTheme = Strong(component) { (component) in
component.backgroundColors = .init(Theme.Colors.clear)
component.imageColors = Checkbox.State<UIColor?>(Theme.Colors.primaryDark)
.with(disabled: Theme.Colors.tertiaryDark)
.with(disabledSelected: Theme.Colors.tertiaryDark)
component.titleColors = Checkbox.State<UIColor?>(Theme.Colors.primaryDark)
.with(disabled: Theme.Colors.tertiaryDark)
.with(disabledSelected: Theme.Colors.tertiaryDark)
component.titleFonts = .init(Theme.Fonts.bold(ofSize: 12))
component.valueColors = Checkbox.State<UIColor?>(Theme.Colors.secondaryDark)
.with(disabled: Theme.Colors.tertiaryDark)
.with(disabledSelected: Theme.Colors.tertiaryDark)
component.valueFonts = .init(Theme.Fonts.regular(ofSize: 10))
}
}
return component
}
public static func radio() -> Checkbox {
let component = Checkbox()
component.batchUpdate {
component.groupKey = "_radio_group"
component.images = Checkbox.State<LazyImage?>({ UIImage.from(name: "circle") })
.with(selected: { UIImage.from(name: "stop.circle") })
.with(disabledSelected: { UIImage.from(name: "stop.circle") })
component.imageSize = CGSize(size: 22)
component.marginEdgeInset = UIEdgeInsets(
vertical: 8,
horizontal: 16)
component.onSetTheme = Strong(component) { (component) in
component.backgroundColors = .init(Theme.Colors.clear)
component.imageColors = Checkbox.State<UIColor?>(Theme.Colors.primaryDark)
.with(disabled: Theme.Colors.tertiaryDark)
.with(disabledSelected: Theme.Colors.tertiaryDark)
component.titleColors = Checkbox.State<UIColor?>(Theme.Colors.primaryDark)
.with(disabled: Theme.Colors.tertiaryDark)
.with(disabledSelected: Theme.Colors.tertiaryDark)
component.titleFonts = .init(Theme.Fonts.bold(ofSize: 12))
component.valueColors = Checkbox.State<UIColor?>(Theme.Colors.secondaryDark)
.with(disabled: Theme.Colors.tertiaryDark)
.with(disabledSelected: Theme.Colors.tertiaryDark)
component.valueFonts = .init(Theme.Fonts.regular(ofSize: 10))
}
}
return component
}
}
| 48.342857 | 92 | 0.60195 |
626a6ff14631cfb936c56ef7741062fc5b642660 | 3,347 | /// 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 CoreLocation
final class LocationManager: NSObject, ObservableObject {
var locationManager = CLLocationManager()
var previousLocation: CLLocation?
@Published var locationString = ""
override init() {
super.init()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
}
func startLocationServices() {
if locationManager.authorizationStatus == .authorizedAlways || locationManager.authorizationStatus == .authorizedWhenInUse {
locationManager.startUpdatingLocation()
} else {
locationManager.requestWhenInUseAuthorization()
}
}
}
extension LocationManager: CLLocationManagerDelegate {
func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
if locationManager.authorizationStatus == .authorizedAlways || locationManager.authorizationStatus == .authorizedWhenInUse {
locationManager.startUpdatingLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let latest = locations.first else { return }
if previousLocation == nil {
previousLocation = latest
} else {
let distanceInMeters = previousLocation?.distance(from: latest) ?? 0
previousLocation = latest
locationString = "You are \(Int(distanceInMeters)) meters from your start point."
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
guard let clError = error as? CLError else { return }
switch clError {
case CLError.denied:
print("Access denied")
default:
print("Catch all errors")
}
}
}
| 38.918605 | 128 | 0.744249 |
f4415fad0f299d9dd4a599419e1f9eb3bd4978a9 | 638 | public struct AdvertisementProperties {
public var action: String?
public var details: [Int: TrackingValue]?
public var id: String?
public init(
id: String?,
action: String? = nil,
details: [Int: TrackingValue]? = nil
) {
self.action = action
self.details = details
self.id = id
}
internal func merged(over other: AdvertisementProperties) -> AdvertisementProperties {
return AdvertisementProperties(
id: id ?? other.id,
action: action ?? other.action,
details: details.merged(over: other.details)
)
}
}
| 25.52 | 90 | 0.592476 |
fc19c98de3b99601899b7c01688d3007e2ac4471 | 406 | //
// KairosEnrollResult.swift
// Levels
//
// Created by Emanuel Guerrero on 4/21/18.
// Copyright © 2018 The SilverLogic. All rights reserved.
//
import Foundation
struct KairosEnrollResult: Codable {
let faceId: String
let images: [KairosEnrollImage]
// MARK: - CodingKeys
enum CodingKeys: String, CodingKey {
case faceId = "face_id"
case images
}
}
| 18.454545 | 58 | 0.64532 |
e54c6008ed00aa75a235e972bbd687471e05cc7f | 192 | // © 2018–2022 J. G. Pusey (see LICENSE.md)
public extension String {
// MARK: Public Instance Properties
var displayWidth: Int {
reduce(0) { $0 + $1.displayWidth }
}
}
| 17.454545 | 43 | 0.598958 |
eb254341dacac83f03230fee3884aeafc1aeef5b | 12,472 | //===------------------- DependencyKey.swift ------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020-2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Foundation
import TSCBasic
/// A filename from another module
/*@_spi(Testing)*/ public struct ExternalDependency: Hashable, Comparable, CustomStringConvertible {
let file: VirtualPath
/// Cache this
let isSwiftModule: Bool
/*@_spi(Testing)*/ public init(_ fileName: String)
throws {
self.init(try VirtualPath(path: fileName))
}
init(_ file: VirtualPath) {
self.file = file
self.isSwiftModule = file.extension == FileType.swiftModule.rawValue
}
func modTime(_ fileSystem: FileSystem) -> Date? {
try? fileSystem.getFileInfo(file).modTime
}
var swiftModuleFile: TypedVirtualPath? {
isSwiftModule ? TypedVirtualPath(file: file, type: .swiftModule) : nil
}
public var description: String {
switch file.extension {
case FileType.swiftModule.rawValue:
// Swift modules have an extra component at the end that is not descriptive
return file.parentDirectory.basename
default:
return file.basename
}
}
public var shortDescription: String {
DependencySource(file).map { $0.shortDescription }
?? file.basename
}
public static func < (lhs: Self, rhs: Self) -> Bool {
lhs.file.name < rhs.file.name
}
}
/// Since the integration surfaces all externalDependencies to be processed later,
/// a combination of the dependency and fingerprint are needed.
public struct FingerprintedExternalDependency: Hashable, Equatable, ExternalDependencyAndFingerprintEnforcer {
let externalDependency: ExternalDependency
let fingerprint: String?
init(_ externalDependency: ExternalDependency, _ fingerprint: String?) {
self.externalDependency = externalDependency
self.fingerprint = fingerprint
assert(verifyExternalDependencyAndFingerprint())
}
var externalDependencyToCheck: ExternalDependency? { externalDependency }
var incrementalDependencySource: DependencySource? {
guard let _ = fingerprint,
let swiftModuleFile = externalDependency.swiftModuleFile
else {
return nil
}
return DependencySource(swiftModuleFile)
}
}
/// A `DependencyKey` carries all of the information necessary to uniquely
/// identify a dependency node in the graph, and serves as a point of identity
/// for the dependency graph's map from definitions to uses.
public struct DependencyKey: Hashable, CustomStringConvertible {
/// Captures which facet of the dependency structure a dependency key represents.
///
/// A `DeclAspect` is used to separate dependencies with a scope limited to
/// a single file (or declaration within a file) from dependencies with a
/// scope that may affect many files.
///
/// Those dependencies that are localized to a single file or declaration are
/// a part of the "implementation" aspect. Changes to nodes with the
/// implementation aspect do not require uses of that node to be recompiled.
/// The Swift frontend models all uses of declarations in a file as part of
/// the implementation aspect.
///
/// The remaining kind of dependencies are a part of the "interface" aspect.
/// Changes to nodes with the interface aspect *require* all uses of the node
/// to be rebuilt. The Swift frontend models the definitions of types,
/// functions, and members with an interface node.
///
/// Special Considerations
/// ======================
///
/// When the Swift frontend creates dependency nodes, they occur in
/// interface/implementation pairs. The idea being that the implementation
/// aspect node depends on the interface aspect node but, crucially, not
/// vice versa. This models the fact that changes to the interface of a node
/// must cause its implementation to be recompiled.
///
/// Dumping Dependency Graphs
/// =========================
///
/// When the driver's dependency graph is dumped as a dot file, nodes with
/// the interface aspect are yellow and nodes with the implementations aspect
/// are white. Each node holds an instance variable describing which
/// aspect of the entity it represents.
/*@_spi(Testing)*/ public enum DeclAspect: Comparable {
/// The "interface" aspect.
case interface
/// The "implementation" aspect.
case implementation
}
/// Enumerates the current sorts of dependency nodes in the dependency graph.
/*@_spi(Testing)*/ public enum Designator: Hashable, CustomStringConvertible {
/// A top-level name.
///
/// Corresponds to the top-level names that occur in a given file. When
/// a top-level name matching this name is added, removed, or modified
/// the corresponding dependency node will be marked for recompilation.
///
/// The `name` parameter is the human-readable name of the top-level
/// declaration.
case topLevel(name: String)
/// A dependency originating from the lookup of a "dynamic member".
///
/// A "dynamic member lookup" is the Swift frontend's term for lookups that
/// occur against instances of `AnyObject`. Because an `AnyObject` node
/// behaves like `id` in that it can recieve any kind of Objective-C
/// message, the compiler takes care to log these names separately.
///
/// The `name` parameter is the human-readable base name of the Swift method
/// the dynamic member was imported as. e.g. `-[NSString initWithString:]`
/// appears as `init`.
///
/// - Note: This is distinct from "dynamic member lookup", which uses
/// a normal `member` constraint.
case dynamicLookup(name: String)
/// A dependency that resides outside of the module being built.
///
/// These dependencies correspond to clang modules and their immediate
/// dependencies, header files imported via the bridging header, and Swift
/// modules that do not have embedded incremental dependency information.
/// Because of this, the Swift compiler and Driver have very little
/// information at their disposal to make scheduling decisions relative to
/// the other kinds of dependency nodes. Thus, when the modification time of
/// an external dependency node changes, the Driver is forced to rebuild all
/// uses of the dependency.
///
/// The full path to the external dependency as seen by the frontend is
/// available from this node.
case externalDepend(ExternalDependency)
/// A source file - acts as the root for all dependencies provided by
/// declarations in that file.
///
/// The `name` of the file is a path to the `swiftdeps` file named in
/// the output file map for a given Swift file.
///
/// If the filename is a swiftmodule, and if it was built by a compilation with
/// `-enable-experimental-cross-module-incremental-build`, the swiftmodule file
/// contains a special section with swiftdeps information for the module
/// in it. In that case the enclosing node should have a fingerprint.
///
case sourceFileProvide(name: String)
/// A "nominal" type that is used, or defined by this file.
///
/// Unlike a top-level name, a `nominal` dependency always names exactly
/// one unique declaration (opp. many declarations with the same top-level
/// name). The `context` field of this type is the mangled name of this
/// type. When a component of the mangling for the nominal type changes,
/// the corresponding dependency node will be marked for recompilation.
/// These nodes generally capture the space of ABI-breaking changes made to
/// types themselves such as the addition or removal of generic parameters,
/// or a change in base name.
case nominal(context: String)
/// A "potential member" constraint models the abstract interface of a
/// particular type or protocol. They can be thought of as a kind of
/// "globstar" member constraint. Whenever a member is added, removed or
/// modified, or the type itself is deleted, the corresponding dependency
/// node will be marked for recompilation.
///
/// Potential member nodes are used to model protocol conformances and
/// superclass constraints where the modification of members affects the
/// layout of subclasses or protocol conformances.
///
/// Like `nominal` nodes, the `context` field is the mangled name of the
/// subject type.
case potentialMember(context: String)
/// A member of a type.
///
/// The `context` field corresponds to the mangled name of the type. The
/// `name` field corresponds to the *unmangled* name of the member.
case member(context: String, name: String)
var externalDependency: ExternalDependency? {
switch self {
case let .externalDepend(externalDependency):
return externalDependency
default:
return nil
}
}
public var context: String? {
switch self {
case .topLevel(name: _):
return nil
case .dynamicLookup(name: _):
return nil
case .externalDepend(_):
return nil
case .sourceFileProvide(name: _):
return nil
case .nominal(context: let context):
return context
case .potentialMember(context: let context):
return context
case .member(context: let context, name: _):
return context
}
}
public var name: String? {
switch self {
case .topLevel(name: let name):
return name
case .dynamicLookup(name: let name):
return name
case .externalDepend(let path):
return path.file.name
case .sourceFileProvide(name: let name):
return name
case .member(context: _, name: let name):
return name
case .nominal(context: _):
return nil
case .potentialMember(context: _):
return nil
}
}
public var kindName: String {
switch self {
case .topLevel: return "top-level"
case .nominal: return "nominal"
case .potentialMember: return "potential member"
case .member: return "member"
case .dynamicLookup: return "dynamic lookup"
case .externalDepend: return "external"
case .sourceFileProvide: return "source file"
}
}
public var description: String {
switch self {
case let .topLevel(name: name):
return "top-level name '\(name)'"
case let .nominal(context: context):
return "type '\(context)'"
case let .potentialMember(context: context):
return "potential members of '\(context)'"
case let .member(context: context, name: name):
return "member '\(name)' of '\(context)'"
case let .dynamicLookup(name: name):
return "AnyObject member '\(name)'"
case let .externalDepend(externalDependency):
return "import '\(externalDependency.shortDescription)'"
case let .sourceFileProvide(name: name):
return "source file \((try? VirtualPath(path: name).basename) ?? name)"
}
}
}
/*@_spi(Testing)*/ public let aspect: DeclAspect
/*@_spi(Testing)*/ public let designator: Designator
/*@_spi(Testing)*/ public init(
aspect: DeclAspect,
designator: Designator)
{
self.aspect = aspect
self.designator = designator
}
/*@_spi(Testing)*/ public var correspondingImplementation: Self? {
guard aspect == .interface else {
return nil
}
return Self(aspect: .implementation, designator: designator)
}
public var description: String {
"\(aspect) of \(designator)"
}
@discardableResult
func verify() -> Bool {
// This space reserved for future use.
return true
}
}
// MARK: - Comparing
/// Needed to sort nodes to make tracing deterministic to test against emitted diagnostics
extension DependencyKey: Comparable {
public static func < (lhs: Self, rhs: Self) -> Bool {
lhs.aspect != rhs.aspect ? lhs.aspect < rhs.aspect :
lhs.designator < rhs.designator
}
}
extension DependencyKey.Designator: Comparable {
}
| 37.793939 | 110 | 0.677117 |
0e7d5c822e7b6e4f25d9425d3b80ee700e055539 | 8,730 | //
// ICXDataInputViewController.swift
// iconex_ios
//
// Copyright © 2018 ICON Foundation. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import ICONKit
import BigInt
enum EncodeType {
case utf8
case hex
}
class ICXDataInputViewController: BaseViewController {
@IBOutlet weak var closeButton: UIButton!
@IBOutlet weak var navTitle: UILabel!
@IBOutlet weak var removeButton: UIButton!
@IBOutlet weak var doneButton: UIButton!
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var stepContainer: UIView!
@IBOutlet weak var removeContainer: UIView!
@IBOutlet weak var stepView: UIView!
@IBOutlet weak var typeLabel: UILabel!
@IBOutlet weak var lengthLabel: UILabel!
@IBOutlet weak var placeholder: UILabel!
@IBOutlet weak var bottomConstraint: NSLayoutConstraint!
var handler: ((String?) -> Void)?
var type: EncodeType = .utf8
var savedData: String? = nil
var stepPrice: BigUInt?
var costs: Response.StepCosts?
var walletAmount: BigUInt?
var sendAmount: BigUInt?
var isModify: Bool = false
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
initializeUI()
initialize()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
switch self.type {
case .utf8:
self.placeholder.text = "Hello ICON"
case .hex:
self.placeholder.text = "0x1234..."
}
if let saved = savedData {
textView.text = saved
textView.isEditable = false
stepContainer.isHidden = true
removeContainer.isHidden = false
self.doneButton.setTitle("Common.Modify".localized, for: .normal)
} else {
textView.isEditable = true
stepContainer.isHidden = false
removeContainer.isHidden = true
self.doneButton.setTitle("Common.Done".localized, for: .normal)
}
self.textChanged()
}
func initializeUI() {
self.navTitle.text = "Transfer.DataTitle".localized
self.lengthLabel.text = "0"
self.textView.text = nil
self.textView.delegate = self
self.typeLabel.text = self.type == .utf8 ? "UTF-8" : "HEX"
self.doneButton.setTitleColor(UIColor.white, for: .normal)
self.doneButton.setTitleColor(UIColor(179, 179, 179), for: .disabled)
self.removeButton.styleDark()
self.removeButton.setTitle("Common.Remove".localized, for: .normal)
self.removeButton.cornered()
}
func initialize() {
closeButton.rx.controlEvent(UIControl.Event.touchUpInside).subscribe(onNext: { [unowned self] in
if let text = self.textView.text, text != "" {
Alert.Confirm(message: "Transfer.Data.Cancel".localized, cancel: "Common.No".localized, confirm: "Common.Yes".localized, handler: { [unowned self] in
self.dismiss(animated: true, completion: nil)
}, nil).show(self)
} else {
self.dismiss(animated: true, completion: nil)
}
}).disposed(by: disposeBag)
doneButton.rx.controlEvent(UIControl.Event.touchUpInside).subscribe(onNext: { [unowned self] in
if self.savedData != nil && self.isModify == false {
self.isModify = true
self.textView.isEditable = true
self.textView.becomeFirstResponder()
self.doneButton.setTitle("Common.Done".localized, for: .normal)
return
}
guard let text = self.textView.text, text != "" else {
return
}
var encoded = text
if self.type == .hex {
let set = CharacterSet(charactersIn: "0123456789ABCDEF").inverted
guard text.prefix0xRemoved().uppercased().rangeOfCharacter(from: set) == nil, text.prefix0xRemoved().hexToData() != nil else {
Alert.Basic(message: "Error.InputData".localized).show(self)
return
}
} else {
guard let hexData = text.data(using: .utf8) else {
Alert.Basic(message: "Error.InputData".localized).show(self)
return
}
encoded = hexData.hexEncodedString()
}
let length = encoded.bytes.count
guard length <= 250 * 1024 else {
Alert.Basic(message: String(format: "Error.Data.Exceeded".localized, 250)).show(self)
return
}
guard let costs = self.costs, let amount = self.walletAmount, let stepPrice = self.stepPrice else { return }
guard let stepDefault = BigUInt(costs.defaultValue.prefix0xRemoved(), radix: 16) else { return }
let stepLimit = 2 * stepDefault * stepPrice
var sendValue = BigUInt(0)
if let send = self.sendAmount {
sendValue = send
}
Log.Debug("amount - \(amount) , stepLimit - \(stepLimit) , sendValue - \(sendValue)")
if amount > sendValue, stepLimit > (amount - sendValue) {
Alert.Basic(message: "Error.Transfer.InsufficientFee.ICX".localized).show(self)
return
}
self.textView.resignFirstResponder()
if let handler = self.handler{
handler(text)
}
self.dismiss(animated: true, completion: nil)
}).disposed(by: disposeBag)
removeButton.rx.tap.subscribe(onNext: { [unowned self] in
let alert = Alert.Confirm(message: "Alert.Transfer.Data.Delete".localized, handler: {
if let handler = self.handler {
handler(nil)
}
self.dismiss(animated: true, completion: nil)
})
alert.show(self)
}).disposed(by: disposeBag)
keyboardHeight().observeOn(MainScheduler.instance).subscribe(onNext: { [unowned self] (height: CGFloat) in
var keyHeight: CGFloat = height
if #available(iOS 11.0, *) {
keyHeight = height - self.view.safeAreaInsets.bottom
}
self.bottomConstraint.constant = keyHeight
}).disposed(by: disposeBag)
textView.rx.didChange.observeOn(MainScheduler.instance).subscribe(onNext: { [unowned self] in
self.textChanged()
}).disposed(by: disposeBag)
textView.rx.text.map { $0!.length > 0 }.subscribe(onNext: {
self.placeholder.isHidden = $0
self.doneButton.isEnabled = ($0 && self.costs != nil)
}).disposed(by: disposeBag)
}
func textChanged() {
if let inputString = self.textView.text {
let length = Float(inputString.bytes.count) / 1024.0
self.lengthLabel.textColor = UIColor.black
if length < 1.0 {
self.lengthLabel.text = String(format: "%d", inputString.bytes.count) + "B"
} else {
self.lengthLabel.text = String(format: "%.0f", length) + "KB"
if length > 250 * 1024 {
self.lengthLabel.textColor = UIColor.red
}
}
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if savedData == nil {
self.textView.becomeFirstResponder()
}
}
}
extension ICXDataInputViewController: UITextViewDelegate {
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
guard let former = textView.text as NSString? else { return false }
let value = former.replacingCharacters(in: range, with: text)
guard let hexData = value.data(using: .utf8) else { return false }
let hexEncoded = hexData.hexEncodedString()
let count = hexEncoded.bytes.count
if count > 250 * 1024 {
Alert.Basic(message: String(format: "Error.Data.Exceeded".localized, 250)).show(self)
return false
}
return true
}
}
| 36.835443 | 165 | 0.570561 |
3addc7dabb7988bc60561bc3954cb69f9deba49f | 1,570 | //
// ViewController.swift
// tvAdd
//
// Created by Michael Chirico on 10/7/18.
// Copyright © 2018 Michael Chirico. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tableView0: UITableView!
@IBOutlet weak var tableView1: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
delegates()
}
func delegates() {
tableView0.delegate = self
tableView1.delegate = self
tableView0.dataSource = self
tableView1.dataSource = self
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == tableView0 {
return 2
}
if tableView == tableView1 {
return 40
}
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if tableView == tableView0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell0")
if let tvc = cell as? TableViewCell0 {
tvc.label0.text = "one"
tvc.label1.text = "s"
}
return cell!
}
let cell = tableView.dequeueReusableCell(withIdentifier: "cell1")
if let tvc = cell as? TableViewCell1 {
tvc.label0.text = "two"
tvc.label1.text = "s"
}
return cell!
}
}
| 18.915663 | 98 | 0.614013 |
1c86df42aa46f16be4dc04f6961e66758c30c74a | 1,414 | //
// WeatherData.swift
// MobileWeather
//
// Created by Joel Fischer on 9/17/21.
// Copyright © 2021 Ford. All rights reserved.
//
import CoreLocation
import Foundation
struct WeatherData: Decodable {
let location: CLLocationCoordinate2D
let current: CurrentForecast
let minutely: [MinutelyForecast]
let hourly: [HourlyForecast]
let daily: [DailyForecast]
let alerts: [WeatherAlert]?
init() {
location = CLLocationCoordinate2D(latitude: 42.4829483, longitude: -83.1426719)
current = CurrentForecast()
minutely = []
hourly = []
daily = []
alerts = []
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
location = CLLocationCoordinate2D(latitude: try values.decode(Double.self, forKey: .lat), longitude: try values.decode(Double.self, forKey: .lon))
current = try values.decode(CurrentForecast.self, forKey: .current)
minutely = try values.decode([MinutelyForecast].self, forKey: .minutely)
hourly = try values.decode([HourlyForecast].self, forKey: .hourly)
daily = try values.decode([DailyForecast].self, forKey: .daily)
alerts = try values.decodeIfPresent([WeatherAlert].self, forKey: .alerts)
}
enum CodingKeys: String, CodingKey {
case lat, lon, current, minutely, hourly, daily, alerts
}
}
| 32.136364 | 154 | 0.669731 |
89c8faf240494ceaadb1124a95b9f0120a24aa90 | 1,206 | //
// Code_Test_Keith_HunterUITests.swift
// Code Test Keith HunterUITests
//
// Created by Keith Hunter on 12/21/18.
// Copyright © 2018 Keith Hunter. All rights reserved.
//
import XCTest
class Code_Test_Keith_HunterUITests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 34.457143 | 182 | 0.699005 |
1da87c8f32fba5b88524ccb60c92ba7893dbb107 | 6,413 | //
// CountDownBtn.swift
// WLXUtils
//
// Created by wlx on 2020/11/30.
//
import Foundation
/**
动画类型
*/
enum CountDownAnimationType {
case None //没有动画
case Scale //缩放动画
case Rotate //旋转动画
}
/// 自定义倒计时按钮
@IBDesignable class CountDownBtn: UIButton {
/// 倒计时中的背景颜色
@IBInspectable var enabled_bgColor: UIColor = UIColor.clear
/// 倒计时时数字颜色
@IBInspectable var numberColor :UIColor = UIColor.black{
didSet{
timeLabel.textColor = numberColor
}
}
/// 时间长度(秒)
@IBInspectable var count :Int = 0 {
didSet{
startCount = count
originNum = count
}
}
/// 动画类型,默认没有动画
var animaType: CountDownAnimationType = CountDownAnimationType.None
override var frame: CGRect {
set{
super.frame = newValue
timeLabel.frame = Size.kAdaptRect(rect: frame)
}
get{
return super.frame
}
}
override var backgroundColor: UIColor?{
set{
super.backgroundColor = newValue
if normalBgColor == nil {
normalBgColor = backgroundColor
}
}
get{
return super.backgroundColor
}
}
private var btnTitle :String?
private var normalBgColor: UIColor?
private var timer: Timer!
private var startCount = 0
private var originNum = 0
//倒计时Label
private var timeLabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
btnTitle = self.title(for: .normal)
self.addLabel()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
btnTitle = self.title(for: .normal)
self.addLabel()
}
private func addLabel() {
timeLabel.frame = CGRect(x: 0, y: 0, width: Size.kAdaptWidth(self.frame.width) , height: Size.kAdaptHeight(self.frame.height) )
//CGRectMake(0, 0, CGRectGetWidth(self.frame), CGRectGetHeight(self.frame))
timeLabel.backgroundColor = UIColor.clear
timeLabel.font = UIFont.font14
timeLabel.textAlignment = NSTextAlignment.center
timeLabel.textColor = numberColor
timeLabel.text = ""
self.addSubview(timeLabel)
}
/**
开启倒计时
*/
func startCountDown() {
//设置为按钮字号在addLabel()会失败
timeLabel.font = self.titleLabel?.font
timeLabel.text = "\(self.originNum)秒重新获取"
self.setTitle("", for: .normal)
self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(CountDownBtn.countDown), userInfo: nil, repeats: true)
self.backgroundColor = enabled_bgColor
self.isEnabled = false
switch self.animaType {
case .Scale:
self.numAnimation()
case .Rotate:
self.rotateAnimation()
default:
return
}
}
// 倒计时开始
@objc private func countDown() {
self.startCount -= 1
timeLabel.text = "\(self.startCount)秒重新获取"
//倒计时完成后停止定时器,移除动画
if self.startCount <= 0 {
if self.timer == nil {
return
}
self.setTitle(btnTitle, for: .normal)
timeLabel.layer.removeAllAnimations()
timeLabel.text = ""
self.timer.invalidate()
self.timer = nil
self.isEnabled = true
self.startCount = self.originNum
self.backgroundColor = normalBgColor
}
}
//放大动画
private func numAnimation() {
let duration: CFTimeInterval = 1
let beginTime = CACurrentMediaTime()
// Scale animation
let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale")
scaleAnimation.keyTimes = [0, 0.5, 1]
scaleAnimation.values = [1, 1.5, 2]
scaleAnimation.duration = duration
// Opacity animation
let opacityAnimaton = CAKeyframeAnimation(keyPath: "opacity")
opacityAnimaton.keyTimes = [0, 0.5, 1]
opacityAnimaton.values = [1, 0.5, 0]
opacityAnimaton.duration = duration
// Animation
let animation = CAAnimationGroup()
animation.animations = [scaleAnimation, opacityAnimaton]
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear)
animation.duration = duration
animation.repeatCount = HUGE
animation.isRemovedOnCompletion = false
animation.beginTime = beginTime
timeLabel.layer.add(animation, forKey: "animation")
self.layer.addSublayer(timeLabel.layer)
}
// 旋转变小动画
private func rotateAnimation() {
let duration: CFTimeInterval = 1
let beginTime = CACurrentMediaTime()
// Rotate animation
let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotateAnimation.fromValue = NSNumber(value: 0)
rotateAnimation.toValue = NSNumber(value: Double.pi * 2)
rotateAnimation.duration = duration;
// Scale animation
let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale")
scaleAnimation.keyTimes = [0]
scaleAnimation.values = [1, 2]
scaleAnimation.duration = 0
// Opacity animation
let opacityAnimaton = CAKeyframeAnimation(keyPath: "opacity")
opacityAnimaton.keyTimes = [0, 0.5]
opacityAnimaton.values = [1, 0]
opacityAnimaton.duration = duration
// Scale animation
let scaleAnimation2 = CAKeyframeAnimation(keyPath: "transform.scale")
scaleAnimation2.keyTimes = [0, 0.5]
scaleAnimation2.values = [2, 0]
scaleAnimation2.duration = duration
let animation = CAAnimationGroup()
animation.animations = [rotateAnimation, scaleAnimation, opacityAnimaton, scaleAnimation2]
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear)
animation.duration = duration
animation.repeatCount = HUGE
animation.isRemovedOnCompletion = false
animation.beginTime = beginTime
timeLabel.layer.add(animation, forKey: "animation")
self.layer.addSublayer(timeLabel.layer)
}
}
| 31.436275 | 147 | 0.602214 |
e6a1a22184ae3f4e9a8ab1c8d5877cdb98d58610 | 5,540 | //
// RoomModel.swift
// Enigma (iOS)
//
// Created by Ananya George on 10/18/21.
//
import Foundation
import SwiftUI
struct RoomsModel: Codable, Hashable {
var journey: Journey?
var room: Room?
static var data = RoomsModel(journey: Journey(id: nil, userId: nil, roomId: "1234", stars: 0, powerupUsed: .no, roomUnlocked: true, powerupId: "12345", questionsStatus: ["solved","unlocked","locked"]), room: Room(id: "1234", roomNo: "3", questionId: [], media: "https://firebasestorage.googleapis.com/v0/b/enigma-8.appspot.com/o/Room%2FRoom%207.png?alt=media&token=adc9c32c-18e8-4d28-bd26-30dd00192d39", title: "Room 3", starQuota: 0))
}
struct RoomUnlock {
struct RoomUnlockRequest: Codable {
var roomId: String?
}
struct RoomUnlockResponse: Codable {
var roomStatus: String?
var starsNeeded: Int?
private enum CodingKeys: String, CodingKey {
case starsNeeded = "starsNeeded"
case roomStatus = "status"
}
var status: RoomStatus {
return RoomStatus(rawValue: roomStatus ?? "locked") ?? .locked
}
}
}
enum RoomStatus: String {
case locked = "locked"
case canUnlock = "canUnlock"
case unlocked = "unlocked"
case complete = "complete"
}
struct AllRoomsResponse: Codable {
var stars: Int?
var data: [RoomsModel?]?
var nextRoomsUnlockedIn: Int?
}
struct Room: Codable, Hashable {
var _id: String?
var roomNo: String?
var questionId: [String?]?
var media: String?
var title: String?
var starQuota: Int?
var mediaURL: URL? {
URL(string: media ?? "")
}
init(id: String?, roomNo: String?, questionId: [String?]?, media: String?, title: String?, starQuota: Int?) {
self._id = id
self.roomNo = roomNo
self.questionId = questionId
self.media = media
self.title = title
self.starQuota = starQuota
}
}
struct Journey: Codable, Hashable {
var _id: String?
var userId: String?
var roomId: String?
var stars: Int?
var powerupUsed: PowerupUsed?
var roomUnlocked: Bool?
var powerupId: String?
var questionsStatus: [questionStatus]?
init(id: String?, userId: String?, roomId: String?, stars: Int?, powerupUsed: PowerupUsed,roomUnlocked: Bool?, powerupId: String?, questionsStatus: [String]?) {
self._id = id
self.userId = userId
self.roomId = roomId
self.stars = stars
self.powerupUsed = powerupUsed
self.roomUnlocked = roomUnlocked
self.powerupId = powerupId
if let questionsStatus = questionsStatus {
self.questionsStatus = questionsStatus.map { questionStatus(rawValue: $0) ?? .locked }
}
}
var roomStatus: questionStatus {
guard let questionsStatus = questionsStatus else {
return .null
}
if !(roomUnlocked ?? true) {
return .locked
}
if questionsStatus == Array(repeating: .solved, count: 3) {
return .solved
}else {
return .unlocked
}
}
var isSmooth : Bool {
return roomStatus == .solved
}
var showArrow: Bool {
return (roomStatus == .solved) || (roomStatus == .unlocked)
}
}
enum PowerupUsed: String, Codable {
case yes = "yes"
case no = "no"
case active = "active"
case null = ""
}
enum questionStatus: String, Codable {
case solved = "solved"
case locked = "locked"
case unlocked = "unlocked"
case null = ""
var color: Color {
switch self {
case .solved:
return .roomGreen
case .locked, .null:
return .roomGrey
case .unlocked:
return .roomBlue
}
}
var roomColor: Color {
switch self {
case .solved:
return .roomGreen
case .locked, .null:
return .roomGrey
case .unlocked:
return .roomBlue
}
}
var progressImage: String {
if self == .solved {
return "Key"
} else {
return "unsolved_key"
}
}
}
extension AllRoomsResponse {
static let sampleData: AllRoomsResponse = AllRoomsResponse(data: [
RoomsModel(journey: Journey(id: nil, userId: nil, roomId: nil, stars: 0, powerupUsed: .yes, roomUnlocked: false, powerupId: nil, questionsStatus: ["locked", "locked", "locked"]),room: Room(id: "61656a08fdeca6f21cf87708", roomNo: "3", questionId: [
"61621059336ae702be39fe7a"
], media: "https://google.com/url?cd=vfe&psig=AOvVaw2CnTXmnerWF7EZiB1oqpQK&sa=i&source=images&url=https%3A%2F%2Fpixabay.com%2Fimages%2Fsearch%2F&ust=1633859516954000&ved=0CAsQjRxqFwoTCMDUiJOHvfMCFQAAAAAdAAAAABAD", title: "Room 3", starQuota: 30))
])
}
/// Sample Response from Backend
/*
"room": {
"_id": "61656a08fdeca6f21cf87708",
"roomNo": "3",
"questionId": [
"61621059336ae702be39fe7a"
],
"media": "https://google.com/url?cd=vfe&psig=AOvVaw2CnTXmnerWF7EZiB1oqpQK&sa=i&source=images&url=https%3A%2F%2Fpixabay.com%2Fimages%2Fsearch%2F&ust=1633859516954000&ved=0CAsQjRxqFwoTCMDUiJOHvfMCFQAAAAAdAAAAABAD",
"title": "Room 3",
"starQuota": 30
},
"journey": {
"_id": null,
"userId": null,
"roomId": null,
"stars": 0,
"powerupUsed": false,
"roomUnlocked": false,
"powerupId": null,
"questionsStatus": [
"locked",
"locked",
"locked"
]
}
*/
| 27.29064 | 439 | 0.606498 |
2f3c9240d98261ff18caedfd4eed926fd2fd0900 | 4,681 | import UIKit
import UserNotifications
final class BackgroundFetchService: NSObject, AccountService {
static let shared = BackgroundFetchService()
var isAskAuthorization: Bool?
fileprivate override init() {
super.init()
setup()
}
public func setup() {
let isEnable = Preference.shared.isBackgroundEnable
if isEnable {
turnOn()
} else {
turnOff()
}
}
public func turnOn() {
Preference.shared.isBackgroundEnable = true
UIApplication.shared.setMinimumBackgroundFetchInterval(UIApplication.backgroundFetchIntervalMinimum)
}
public func turnOff() {
Preference.shared.isBackgroundEnable = false
UIApplication.shared.setMinimumBackgroundFetchInterval(UIApplication.backgroundFetchIntervalNever)
}
private func push(messageCount: Int) {
if #available(iOS 10.0, *) {
let content = UNMutableNotificationContent()
content.title = "您有 \(messageCount) 条未读提醒"
// content.body = String.messageTodayGank
content.sound = UNNotificationSound.default
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
let requestIdentifier = "v2ex now message"
let request = UNNotificationRequest(identifier: requestIdentifier, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
} else {
// Fallback on earlier versions
}
}
public func initAuthorization() {
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().getNotificationSettings(completionHandler: { settings in
GCD.runOnMainThread { [weak self] in
switch settings.authorizationStatus {
case .notDetermined:
self?.isAskAuthorization = false
case .authorized:
self?.isAskAuthorization = true
case .denied:
self?.isAskAuthorization = true
default:
if #available(iOS 12.0, *) {
if settings.authorizationStatus == .provisional {
self?.isAskAuthorization = true
}
}
}
}
})
}
}
public func checkAuthorization() {
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().getNotificationSettings(completionHandler: { settings in
GCD.runOnMainThread { [weak self] in
switch settings.authorizationStatus {
case .notDetermined:
self?.authorize()
case .authorized:
log.verbose("UserNotifications authorized")
case .denied:
UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!, options: [:], completionHandler: nil)
default:
if #available(iOS 12.0, *) {
if settings.authorizationStatus == .provisional {
log.verbose("UserNotifications provisional")
}
}
}
}
})
}
}
public func authorize() {
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) { (granted, error) in
GCD.runOnMainThread { [weak self] in
self?.initAuthorization()
if granted {
self?.turnOn()
} else {
log.verbose("UserNotifications denied")
}
}
}
}
}
public func performFetchWithCompletionHandler(_ completionHandler: @escaping (UIBackgroundFetchResult) -> Void){
guard AccountModel.isLogin else {
completionHandler(.noData)
return
}
queryNewMessage(success: { [weak self] noticeCount in
guard noticeCount.boolValue else {
completionHandler(.noData)
return
}
self?.push(messageCount: noticeCount)
completionHandler(.newData)
}) { error in
completionHandler(.failed)
}
}
}
| 35.732824 | 138 | 0.528092 |
f5d32230f4c3921d98166df4c1be279a7c3a1ca4 | 1,034 | //
// NSManagedObjectContext+RepoLifetimeType.swift
// DBRepo
//
// Created by Daniel Bennett on 09/07/2016.
// Copyright © 2016 Dan Bennett. All rights reserved.
//
import Foundation
import CoreData
extension NSManagedObjectContext : RepoLifetimeType {
public func addEntity<T : EntityType>(type : T.Type) throws -> T {
guard let managedObject = NSEntityDescription.insertNewObjectForEntityForName(type.className, inManagedObjectContext: self) as? T else {
throw NSError(domain: "co.uk.danbennett", code: 8001, userInfo: [NSLocalizedDescriptionKey : "No entity matches name \(type.className)"])
}
return managedObject
}
public func removeEntity<T : EntityType>(entity : T) throws {
guard let managedObject = entity as? NSManagedObject else {
throw NSError(domain: "co.uk.danbennett", code: 8001, userInfo: [NSLocalizedDescriptionKey : "None NSManagedObject used in context \(entity)"])
}
self.deleteObject(managedObject)
}
} | 36.928571 | 155 | 0.695358 |
b962d4ed0339657adaeeba8cca3b7caee07fe98d | 1,784 | //
// ObservableConvertibleType+Signal.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 9/19/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import RxSwift
extension ObservableConvertibleType {
/**
Converts observable sequence to `Signal` trait.
- parameter onErrorJustReturn: Element to return in case of error and after that complete the sequence.
- returns: Signal trait.
*/
public func asSignal(onErrorJustReturn: Element) -> Signal<Element> {
let source = self
.asObservable()
.observe(on: SignalSharingStrategy.scheduler)
.catchAndReturn(onErrorJustReturn)
return Signal(source)
}
/**
Converts observable sequence to `Signal` trait.
- parameter onErrorSignalWith: Signal that continues to emit the sequence in case of error.
- returns: Signal trait.
*/
public func asSignal(onErrorSignalWith: Signal<Element>) -> Signal<Element> {
let source = self
.asObservable()
.observe(on: SignalSharingStrategy.scheduler)
.catch { _ in
onErrorSignalWith.asObservable()
}
return Signal(source)
}
/**
Converts observable sequence to `Signal` trait.
- parameter onErrorRecover: Calculates signal that continues to emit the sequence in case of error.
- returns: Signal trait.
*/
public func asSignal(onErrorRecover: @escaping (_ error: Swift.Error) -> Signal<Element>) -> Signal<Element> {
let source = self
.asObservable()
.observe(on: SignalSharingStrategy.scheduler)
.catch { error in
onErrorRecover(error).asObservable()
}
return Signal(source)
}
}
| 30.758621 | 114 | 0.634529 |
b9dcee0347d20b60f9ddde0ea334479c375cd0e4 | 2,455 | //
// CoreDataWrapper.swift
// Sample
//
// Created by Shydow Lee on 7/15/21.
//
import Foundation
import CoreData
protocol CoreDataWrapper {
associatedtype M
associatedtype E: NSManagedObject
static func transform(from model: M, context: NSManagedObjectContext) -> E
static func transform(from entity: E) -> M
}
extension CoreDataWrapper {
func save(model: M) {
let context = CoreDataManager.shared.context
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
}
func delete(id: String) {
let context = CoreDataManager.shared.context
let request = E.fetchRequest()
request.predicate = NSPredicate(format: "id = %?", id)
do {
let entities = try context.fetch(request)
for entity in entities {
context.delete(entity as! NSManagedObject)
}
} catch {
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
}
func loadAll() -> [M] {
let context = CoreDataManager.shared.context
let request = E.fetchRequest()
request.predicate = NSPredicate(format: "TRUEPREDICATE")
var results: [M] = []
do {
let entities = try context.fetch(request)
for entity in entities {
results.append(Self.transform(from: entity as! Self.E))
}
} catch {
return []
}
return results
}
func load(by predicate: NSPredicate) -> [M] {
let context = CoreDataManager.shared.context
let request = E.fetchRequest()
request.predicate = predicate
var results: [M] = []
do {
let entities = try context.fetch(request)
for entity in entities {
results.append(Self.transform(from: entity as! Self.E))
}
} catch {
return []
}
return results
}
}
| 30.308642 | 195 | 0.569857 |
296f279a7217f0fb26fdbd8d3b82499172da7c33 | 3,483 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2018 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
/// The supported C language standard to use for compiling C sources in the package.
public enum CLanguageStandard: String, Encodable {
/// The identifier for the C89 language standard.
case c89
/// The identifier for the C90 language standard.
case c90
/// The identifier for the ISO 9899:1990 language standard.
case iso9899_1990 = "iso9899:1990"
/// The identifier for the ISO 9899:1994 language standard.
case iso9899_199409 = "iso9899:1994"
/// The identifier for the GNU89 language standard.
case gnu89
/// The identifier for the GNU90 language standard.
case gnu90
/// The identifier for the C99 language standard.
case c99
/// The identifier for the ISO 9899:1999 language standard.
case iso9899_1999 = "iso9899:1999"
/// The identifier for the GNU99 language standard.
case gnu99
/// The identifier for the C11 language standard.
case c11
/// The identifier for the ISO 9899:2011 language standard.
case iso9899_2011 = "iso9899:2011"
/// The identifier for the GNU11 language standard.
case gnu11
}
/// The supported C++ language standards to use for compiling C++ sources in the package.
public enum CXXLanguageStandard: String, Encodable {
/// The identifier for the C++98 language standard.
case cxx98 = "c++98"
/// The identifier for the C++03 language standard.
case cxx03 = "c++03"
/// The identifier for the GNU++98 language standard.
case gnucxx98 = "gnu++98"
/// The identifier for the GNU++03 language standard.
case gnucxx03 = "gnu++03"
/// The identifier for the C++11 language standard.
case cxx11 = "c++11"
/// The identifier for the GNU++11 language standard.
case gnucxx11 = "gnu++11"
/// The identifier for the C++14 language standard.
case cxx14 = "c++14"
/// The identifier for the GNU++14 language standard.
case gnucxx14 = "gnu++14"
/// The identifier for the C++1z language standard.
case cxx1z = "c++1z"
/// The identifier for the GNU++1z language standard.
case gnucxx1z = "gnu++1z"
}
#if !PACKAGE_DESCRIPTION_4
/// The version of the Swift language to use for compiling Swift sources in the package.
public enum SwiftVersion {
@available(_PackageDescription, introduced: 4, obsoleted: 5)
case v3
@available(_PackageDescription, introduced: 4)
case v4
@available(_PackageDescription, introduced: 4)
case v4_2
@available(_PackageDescription, introduced: 5)
case v5
/// A user-defined value for the Swift version.
///
/// The value is passed as-is to the Swift compiler's `-swift-version` flag.
case version(String)
}
extension SwiftVersion: Encodable {
public func encode(to encoder: Encoder) throws {
let value: String
switch self {
case .v3:
value = "3"
case .v4:
value = "4"
case .v4_2:
value = "4.2"
case .v5:
value = "5"
case .version(let v):
value = v
}
var container = encoder.singleValueContainer()
try container.encode(value)
}
}
#endif
| 32.551402 | 89 | 0.665805 |
1aa2658550f3eac88c16cfcc61c75af6643d1896 | 1,082 | // swift-tools-version:5.3
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "Coalescing Operators",
products: [
// Products define the executables and libraries a package produces, and make them visible to other packages.
.library(
name: "Coalescing Operators",
targets: ["Coalescing Operators"]),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages this package depends on.
.target(
name: "Coalescing Operators",
dependencies: []),
.testTarget(
name: "Coalescing OperatorsTests",
dependencies: ["Coalescing Operators"]),
]
)
| 37.310345 | 117 | 0.636784 |
e801e5adfa42e980fd90d17fdfcbc003557cd542 | 233 | //
// Tip.swift
// Tipsy
//
// Created by Tarokh on 6/30/20.
// Copyright © 2020 The App Brewery. All rights reserved.
//
import Foundation
struct Tip {
// define some variables
var amountPerPerson: Double?
}
| 13.705882 | 58 | 0.626609 |
1c6001924771858e2d7f73b017f992ab74dd40d3 | 114 | import XCTest
import BotterTests
var tests = [XCTestCaseEntry]()
tests += BotterTests.allTests()
XCTMain(tests)
| 14.25 | 31 | 0.77193 |
14fdb66d46a027d5561efed5a293431782ad651e | 44 | for i in reverse(0 ... 10) {
println(i)
}
| 11 | 28 | 0.545455 |
0a5a2a5974748e04433b80b3ef5bf3034e2ce179 | 2,715 | //
// SceneDelegate.swift
// Followers
//
// Created by Stefano Bertagno on 10/03/2020.
//
import SwiftUI
import UIKit
internal 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).
// Create the SwiftUI view that provides the window contents.
let contentView = ContentView()
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
}
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 neccessarily 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.
}
}
| 46.016949 | 147 | 0.707919 |
8fa9f802aa91e9730837d0ada2209ab49d837fff | 507 | import Foundation
import ProjectDescription
import TuistCore
extension TuistCore.Arguments {
/// Maps a ProjectDescription.Arguments instance into a TuistCore.Arguments instance.
/// - Parameters:
/// - manifest: Manifest representation of arguments model.
/// - generatorPaths: Generator paths.
static func from(manifest: ProjectDescription.Arguments) -> TuistCore.Arguments {
Arguments(environment: manifest.environment, launchArguments: manifest.launchArguments)
}
}
| 36.214286 | 95 | 0.751479 |
f78c9abca8e4c4d6f422eba33e05a58e120657c5 | 17,575 | //
// GameScene.swift
// Flappy
//
// Created by Mateus Sales on 04/02/19.
// Copyright © 2019 Mateus Sales. All rights reserved.
//
import SpriteKit
class GameScene: SKScene {
var floor: SKSpriteNode! // Variável que representa o chão
var intro: SKSpriteNode! // Variável que representa a tela de introdução
var player: SKSpriteNode! // Variável que representa o player
var gameArea: CGFloat = 410.0 // Área jogável
var velocity: Double = 100.0 // Constante de velocidade
var gameFinished = false // Flag para sinalizar que o jogo foi finalizado
var gameStarted = false // Flag para sinalizar que o jogo foi iniciado
var restart = false // Controla se o jogo pode ser reiniciado ou não
var scoreLabel: SKLabelNode! // Label que será mostrada na parte superior indicando quantos obstáculos foram superados
var score: Int = 0 // Pontuação do usuário, contabilizada pela quantidade de obstáculos superados
var flyForce: CGFloat = 30 // Força que vai impulsionar o peixe para cima, eixo Y
var playerCategory: UInt32 = 1 // Categoria do player para os testes de contato
var enemyCategory: UInt32 = 2 // Categoria do inimigo para contatos, entende-se por inimigos o chão e os arpões
var scoreCategory: UInt32 = 4 // Categoria do laser que vai contabilizar a pontuação do jogador
var timer: Timer! // Tempo de aparecimento de um inimigo para o outro
weak var gameViewController: GameViewController? // Instancia utilizada da controller utilizada para reestartar a cena após game over
let scoreSound = SKAction.playSoundFileNamed("bonus.mp3", waitForCompletion: false) // Som que vai tocar quando o jogador superar um inimigo
let gameOverSound = SKAction.playSoundFileNamed("hit.mp3", waitForCompletion: false) // Som que vai tocar quando o jogador colidir com o inimigo
override func didMove(to view: SKView) {
physicsWorld.contactDelegate = self // Informando que esta classe implementará o protocolo SKPhysicsContactDelegate
addBackground() // Adicionando uma imagem como fundo
addFloor() // Adicionando o chão
addIntro() // Adicionando tela de introdução
addPlayer() // Adicionando player na cena
moveFloor() // Movendo o chão para passar ideia de movimento
}
func addBackground(){
let background = SKSpriteNode(imageNamed: "background") // Criando um fundo a partir de uma imagem que está nos assets
background.position = CGPoint(x: size.width / 2, y: size.height / 2) // Posição imagem levando em consideração que a ancora é no canto esquerno na parte inferior da tela
// O posicionamento no eixo Z mostra a profunidade e organização dos seus elementos, elementos com zPosition = 1 estão na frente de elementos com zPosition = 0, e assim sucessivamente
background.zPosition = 0 // Siginifica que está mais no fundo
addChild(background) // Adicionando fundo como filho da cena
}
func addFloor(){
floor = SKSpriteNode(imageNamed: "floor") // Criando objeto a partir de uma imagem
floor.zPosition = 2 // Definindo profundidade deste objeto na cena
floor.position = CGPoint(x: floor.size.width/2, y: size.height - gameArea - floor.size.height/2) // Definindo a posição do objeto
addChild(floor) // Adicionando como filho da cena
// Linha invisivel que fica na parte inferior da tela para identificar o contado do player com o chão
let invisibleFloor = SKNode() // Criando uma variável a partir da classe SKNode
invisibleFloor.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: size.width, height: 1)) // Definindo o corpo físico do objeto neste caso por meio de um retângulo, que mais parece uma linha, pois possui 1px de altura e largura correspondente ao tamanho da tela do dispositivo, este objeto servirá para delimitar o contato com o player
invisibleFloor.physicsBody?.isDynamic = false // Com esta propriedade colocada como falsa o objeto fica estático não sofrendo ação de forças externas
invisibleFloor.physicsBody?.categoryBitMask = enemyCategory // Categoria do inimigo para fazer os testes de contato com os outros objetos no game
invisibleFloor.physicsBody?.contactTestBitMask = playerCategory // Definindo categoria de contato do objeto
invisibleFloor.position = CGPoint(x: size.width/2, y: size.height - gameArea) // Posição do objeto
invisibleFloor.zPosition = 2 // Profundidade do objeto
addChild(invisibleFloor) // Adicionando como filho da cena
// Linha invisivel que fica na parte superior da tela, impedindo o player de sair dos limites da mesma
let invisibleRoof = SKNode() // Criando uma variável a partir da classe SKNode
invisibleRoof.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: size.width, height: 1)) // Definindo o corpo físico do objeto neste caso por meio de um retângulo, que mais parece uma linha, pois possui 1px de altura e largura correspondente ao tamanho da tela do dispositivo, este objeto servirá para delimitar o contato com o player
invisibleRoof.physicsBody?.isDynamic = false // Com esta propriedade colocada como falsa o objeto fica estático não sofrendo ação de forças externas
invisibleRoof.position = CGPoint(x: size.width/2, y: size.height) // Posição do objeto
invisibleRoof.zPosition = 2 // Profundidade do objeto
addChild(invisibleRoof) // Adicionando como filho da cena
}
// Função utilizada para criar a tela de introdução do game
func addIntro(){
intro = SKSpriteNode(imageNamed: "intro") // Criando um nó a partir de uma imagem
intro.zPosition = 3 // Definindo a profundidade do objeto
intro.position = CGPoint(x: size.width/2, y: size.height - 210.0) // Posição do objeto
addChild(intro) // Adicionando como filho da cena
}
// Função utilizada para criar o player
func addPlayer(){
player = SKSpriteNode(imageNamed: "player1") // Criando o player a partir de uma textura(imagem)
player.zPosition = 4 // Definindo profundidade do objeto
player.position = CGPoint(x: 60, y: size.height - gameArea/2) // Posição inicial do objeto
var playerTextures = [SKTexture]() // Array que vai armazenar os frames que vamos utilizar para animar
// Adicionando ao array as imagens que importamos para os Assets
for i in 1...4 {
playerTextures.append(SKTexture(imageNamed: "player\(i)"))
}
let animationAction = SKAction.animate(with: playerTextures, timePerFrame: 0.09) // Animação frame a frame com 0.09s
let repeatAction = SKAction.repeatForever(animationAction) // Repetição "para sempre" da animação
player.run(repeatAction) // Executar a animação
addChild(player) // Adicionando como filho da cena
}
// Função utilizada para mover o chão
func moveFloor() {
let duration = Double(floor.size.width/2)/velocity //Fazer andar metade da largura e voltar pra onde estava
let moveFloorAction = SKAction.moveBy(x: -floor.size.width/2, y: 0, duration: duration) // Movendo o chão
let resetXAction = SKAction.moveBy(x: floor.size.width/2, y: 0, duration: 0) // Resetando a animação de movimento
let sequenceAction = SKAction.sequence([moveFloorAction, resetXAction]) // Colocando em sequência as animações dando impressão de que o chão está se movimentando constantemente, isso pq a figura é simétrica
let repeatAction = SKAction.repeatForever(sequenceAction) // Repetição constante da animação
floor.run(repeatAction) // Executando a animação
}
// Esta label ficará na parte superior e mostrará para o jogador quantos obstáculos ele superou
func addScore() {
scoreLabel = SKLabelNode(fontNamed: "Chalkduster") // Personalizando a fonte
scoreLabel.fontSize = 94 // Tamanho da fonte
scoreLabel.text = "\(score)" // Definindo o conteúdo da string
scoreLabel.zPosition = 5 // Defininco a profundidade do objeto
scoreLabel.position = CGPoint(x: size.width/2, y: size.height - 100) // Posição do objeto
scoreLabel.alpha = 0.8 // Opacidade
addChild(scoreLabel) // Adicionando como filho da cena
}
// Função que contém toda a lógica dos inimigos
func spawnEnemies() {
let initialPosition = CGFloat(arc4random_uniform(132) + 74) // Sorteia a posição no eixo Y do inimigo
let enemyNumber = Int(arc4random_uniform(4) + 1) // Sorteia o número do inimigo, isto definirá o modelo do mesmo
let enemiesDistance = self.player.size.height * 2.5 // Espaço entre os inimigos
let enemyTop = SKSpriteNode(imageNamed: "enemytop\(enemyNumber)") // Inimigo da parte superior construído a partir de uma imagem
let enemyWidth = enemyTop.size.width // Largura do inimigo
let enemyHeight = enemyTop.size.height // Altura do inimigo
enemyTop.position = CGPoint(x: size.width + enemyWidth/2, y: size.height - initialPosition + enemyHeight/2) // Posição do inimigo superior
enemyTop.zPosition = 1 // Profundidade do inimigo superior
enemyTop.physicsBody = SKPhysicsBody(rectangleOf: enemyTop.size) // Corpo físico do inimigo superior
enemyTop.physicsBody?.isDynamic = false // Corpo estático, não sofre ação de forças externas
enemyTop.physicsBody?.categoryBitMask = enemyCategory // Categoria de contato do inimigo da parte superior
enemyTop.physicsBody?.contactTestBitMask = playerCategory // Categoria de contato
let enemyBottom = SKSpriteNode(imageNamed: "enemybottom\(enemyNumber)") // Inimigo da parte inferior construído a prtir de uma imagem
enemyBottom.position = CGPoint(x: size.width + enemyWidth/2, y: enemyTop.position.y - enemyTop.size.height - enemiesDistance) // Posição do inimigo inferior
enemyBottom.zPosition = 1 // Corpo físico do inimigo inferior
enemyBottom.physicsBody = SKPhysicsBody(rectangleOf: enemyBottom.size) // Corpo físico do inimigo inferior
enemyBottom.physicsBody?.isDynamic = false // Corpo estático, não sofre ação de forças externas
enemyBottom.physicsBody?.categoryBitMask = enemyCategory // Categoria de contato do inimigo da parte inferior
enemyBottom.physicsBody?.contactTestBitMask = playerCategory // Categoria de contato
// Laser que vai ficar entre os dois inimigos(superior e inferior), quando identificar o contato entre o player e este laser vou incrementando a variável score
let laser = SKNode() // Criando um nó que será o laser
laser.position = CGPoint(x: enemyTop.position.x + enemyWidth/2, y: enemyTop.position.y - enemyTop.size.height/2 - enemiesDistance/2) // Posição do laser
laser.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: 1, height: enemiesDistance)) // Corpo físico do laser
laser.physicsBody?.isDynamic = false // Corpo estático, não sofre ação de forças externas
laser.physicsBody?.categoryBitMask = scoreCategory // Categoria de contato
// O inimigo precisa se movimentar da parte esquerda da tela até a parte direita, o player não se movimenta no eixo X apenas no eixo Y, o que se movimenta são os inimigos e o chão dando assim a ideia de movimento
let distance = size.width + enemyWidth // Largura da tela + largura do inimigo
let duration = Double(distance)/velocity // Cálculo da duração do movimento
let moveAction = SKAction.moveBy(x: -distance, y: 0, duration: duration) // Ação do que movimenta os inimigos e o laser
let removeAction = SKAction.removeFromParent() // Quando terminar o movimento ele já estará fora da tela, então removo o mesmo
let sequenceAction = SKAction.sequence([moveAction, removeAction]) // Ação que sequencia os movimentos
enemyTop.run(sequenceAction) // Aplicando a sequencia de movimentos que foi criada ao inimigo superior
enemyBottom.run(sequenceAction) // Aplicando a sequencia de movimentos que foi criada ao inimigo inferior
laser.run(sequenceAction) // Aplicando a sequencia de movimentos que foi criada ao laser
// Adicionando como filhos da cena
addChild(enemyTop)
addChild(enemyBottom)
addChild(laser)
}
// Esta função será chamada sempre que o contato player-inimigo ou player-chão for identificado
func gameOver(){
timer.invalidate() // Parar o timer
player.zRotation = 0 // Rotação no eixo Z do player
player.texture = SKTexture(imageNamed: "playerDead") // Mudando a texrtura para uma textura de "peixinho morto"
// Percorre todos os nós da cena e remove a ação de todos, assim o jogo fica completamente estático
for node in self.children {
node.removeAllActions()
}
player.physicsBody?.isDynamic = false // Player passa a ser um objeto estático
gameFinished = true // Flag de game finalizado vai para verdadeiro, assim no touchesBegan(_ touches: ) podemos tomar a decisão correta
gameStarted = false // Flag de game iniciado vai para falso
// Coloca na tela a imagem de game over do game
Timer.scheduledTimer(withTimeInterval: 1.5, repeats: false) { (timer) in
let gameOverImage = SKSpriteNode(imageNamed: "GameOver.png")
gameOverImage.size = CGSize(width: 308, height: 207)
gameOverImage.position = CGPoint(x: self.size.width/2, y: self.size.height/2)
gameOverImage.zPosition = 5
self.addChild(gameOverImage)
self.restart = true
}
}
// Quando ele toca na tela este método é disparado
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if !gameFinished {
if !gameStarted {
intro.removeFromParent() // Remove a tela de introdução da cena
addScore()
player.physicsBody = SKPhysicsBody(circleOfRadius: player.size.width - 42) // Inicializando corpo físico do player a partir de uma textura
player.physicsBody?.isDynamic = true // Agora sofre a ação da gravidade
player.physicsBody?.allowsRotation = true // Mudar o ângulo do player baseado no impulso aplicado
player.physicsBody?.applyImpulse(CGVector(dx: 0, dy: flyForce)) // Aplicando impulso no player, apenas no eixo Y
player.physicsBody?.categoryBitMask = playerCategory // Definindo a categoria do player
player.physicsBody?.contactTestBitMask = scoreCategory // Definindo categoria de teste de contato
player.physicsBody?.collisionBitMask = enemyCategory // Definindo categoria de colisão
gameStarted = true // Flag para sinalizar que o jogo vai iniciar
// A cada 2.5 segundos aparece um novo inimigo na tela
timer = Timer.scheduledTimer(withTimeInterval: 2.5, repeats: true) { (timer) in
self.spawnEnemies() // Função que tem a lógica dos inimigos
}
} else {
player.physicsBody?.velocity = CGVector.zero // Definindo velocidade como zero, para não afetar no impulso que vamos aplicar no player
player.physicsBody?.applyImpulse(CGVector(dx: 0, dy: flyForce)) // Aplicando o impulso
}
} else {
// Quando cair neste caso a tela que estará sendo exibida é a Game Over
if restart { // Caso a flag de restart seja verdadeira
restart = false // Colocamos ela para falso
gameViewController?.presentScene() // Apresentamos a GameScene novamente e uma nova partida é iniciada
}
}
}
override func update(_ currentTime: TimeInterval) {
if gameStarted {
// Calcula a velocidade do player no eixo Y, para rotacionar o mesmo conforme esta velocidade
let yVelocity = player.physicsBody!.velocity.dy * 0.001 as CGFloat // Cáculo da velocidade
player.zRotation = yVelocity // Rotação no eixo Z do player
}
}
}
// Protocolo implementado para verificar os contatos entre os corpos existentes no jogo
extension GameScene: SKPhysicsContactDelegate {
func didBegin(_ contact: SKPhysicsContact) {
if gameStarted{ // Se o game tiver começado, verifico se existiu contato com o laser(score)
if contact.bodyA.categoryBitMask == scoreCategory || contact.bodyB.categoryBitMask == scoreCategory {
// Se verdadeiro incremento a variável score e emito um som, signifca que o player passou entre os dois inimigos e não tocou o chão
score += 1
scoreLabel.text = "\(score)"
run(scoreSound)
// Se o contato for com a categoria que definimos para o chão e para os inimigos, chamo instantaneamente a função de Game Over
} else if contact.bodyA.categoryBitMask == enemyCategory || contact.bodyB.categoryBitMask == enemyCategory {
gameOver() // Chamada para a função game over
run(gameOverSound) // Feedback sonoro para o usuário saber que acabou de tocar em algum inimigo
}
}
}
}
| 63.909091 | 347 | 0.688933 |
56ab92211e021897bc2ac24c741d93d1c9e367e5 | 441 | //
// NSManagedObjectContext+Extensions.swift
// TFCoreData
//
// Created by Wojciech Nagrodzki on 23/07/2017.
//
import CoreData
extension NSManagedObjectContext {
func refreshObjectsWithoutPersistentChangedValues() {
let objectsWithoutPersistentChangedValues = updatedObjects.filter { !$0.hasPersistentChangedValues }
objectsWithoutPersistentChangedValues.forEach { refresh($0, mergeChanges: false) }
}
}
| 25.941176 | 108 | 0.752834 |
d6e9937ff9871c2511790935c0ea54c3562c54fa | 1,632 | //
// The MIT License (MIT)
//
// Copyright (c) 2015-present Badoo Trading Limited.
//
// 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.
@available(iOS 11, *)
public final class CompoundMessageCollectionViewCell<Configuration: Equatable>: BaseMessageCollectionViewCell<CompoundBubbleView> {
// This is required to check in presenter wether we need to update content views.
// If configuration didn't change, content views will be the same
var lastAppliedConfiguration: Configuration?
public override func createBubbleView() -> CompoundBubbleView! {
return CompoundBubbleView()
}
}
| 49.454545 | 131 | 0.762868 |
bf9d02af9a1ac2516a3d920463d98d51a3a3ecaf | 15,984 | import UIKit
// MARK: - SwipeMenuViewOptions
public struct SwipeMenuViewOptions {
public struct TabView {
public enum Style {
case flexible
case segmented
// TODO: case infinity
}
public enum Addition {
case underline
case circle
case none
}
public struct ItemView {
/// ItemView width. Defaults to `100.0`.
public var width: CGFloat = 100.0
/// ItemView side margin. Defaults to `5.0`.
public var margin: CGFloat = 5.0
/// ItemView font. Defaults to `14 pt as bold SystemFont`.
public var font: UIFont = UIFont.boldSystemFont(ofSize: 14)
/// ItemView clipsToBounds. Defaults to `true`.
public var clipsToBounds: Bool = true
/// ItemView textColor. Defaults to `.lightGray`.
public var textColor: UIColor = UIColor(red: 170 / 255, green: 170 / 255, blue: 170 / 255, alpha: 1.0)
/// ItemView selected textColor. Defaults to `.black`.
public var selectedTextColor: UIColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0)
}
public struct AdditionView {
public struct Underline {
/// Underline height if addition style select `.underline`. Defaults to `2.0`.
public var height: CGFloat = 2.0
}
public struct Circle {
/// Circle cornerRadius if addition style select `.circle`. Defaults to `nil`.
/// `AdditionView.height / 2` in the case of nil.
public var cornerRadius: CGFloat? = nil
}
/// AdditionView side margin. Defaults to `0.0`.
@available(*, deprecated, message: "Use `SwipeMenuViewOptions.TabView.AdditionView.padding` instead.")
public var margin: CGFloat = 0.0
/// AdditionView paddings. Defaults to `.zero`.
public var padding: UIEdgeInsets = .zero
/// AdditionView backgroundColor. Defaults to `.black`.
public var backgroundColor: UIColor = .black
/// AdditionView animating duration. Defaults to `0.3`.
public var animationDuration: Double = 0.3
/// Underline style options.
public var underline = Underline()
/// Circle style options.
public var circle = Circle()
}
/// TabView height. Defaults to `44.0`.
public var height: CGFloat = 44.0
/// TabView side margin. Defaults to `0.0`.
public var margin: CGFloat = 0.0
/// TabView background color. Defaults to `.clear`.
public var backgroundColor: UIColor = .clear
/// TabView clipsToBounds. Defaults to `true`.
public var clipsToBounds: Bool = true
/// TabView style. Defaults to `.flexible`. Style type has [`.flexible` , `.segmented`].
public var style: Style = .flexible
/// TabView addition. Defaults to `.underline`. Addition type has [`.underline`, `.circle`, `.none`].
public var addition: Addition = .underline
/// TabView adjust width or not. Defaults to `true`.
public var needsAdjustItemViewWidth: Bool = true
/// Convert the text color of ItemView to selected text color by scroll rate of ContentScrollView. Defaults to `true`.
public var needsConvertTextColorRatio: Bool = true
/// TabView enable safeAreaLayout. Defaults to `true`.
public var isSafeAreaEnabled: Bool = true
/// ItemView options
public var itemView = ItemView()
/// AdditionView options
public var additionView = AdditionView()
public init() { }
}
public struct ContentScrollView {
/// ContentScrollView backgroundColor. Defaults to `.clear`.
public var backgroundColor: UIColor = .clear
/// ContentScrollView clipsToBounds. Defaults to `true`.
public var clipsToBounds: Bool = true
/// ContentScrollView scroll enabled. Defaults to `true`.
public var isScrollEnabled: Bool = true
/// ContentScrollView enable safeAreaLayout. Defaults to `true`.
public var isSafeAreaEnabled: Bool = true
}
/// TabView and ContentScrollView Enable safeAreaLayout. Defaults to `true`.
public var isSafeAreaEnabled: Bool = true {
didSet {
tabView.isSafeAreaEnabled = isSafeAreaEnabled
contentScrollView.isSafeAreaEnabled = isSafeAreaEnabled
}
}
/// TabView options
public var tabView = TabView()
/// ContentScrollView options
public var contentScrollView = ContentScrollView()
public init() { }
}
// MARK: - SwipeMenuViewDelegate
public protocol SwipeMenuViewDelegate: class {
/// Called before setup self.
func swipeMenuView(_ swipeMenuView: SwipeMenuView, viewWillSetupAt currentIndex: Int)
/// Called after setup self.
func swipeMenuView(_ swipeMenuView: SwipeMenuView, viewDidSetupAt currentIndex: Int)
/// Called before swiping the page.
func swipeMenuView(_ swipeMenuView: SwipeMenuView, willChangeIndexFrom fromIndex: Int, to toIndex: Int)
/// Called after swiping the page.
func swipeMenuView(_ swipeMenuView: SwipeMenuView, didChangeIndexFrom fromIndex: Int, to toIndex: Int)
}
extension SwipeMenuViewDelegate {
public func swipeMenuView(_ swipeMenuView: SwipeMenuView, viewWillSetupAt currentIndex: Int) { }
public func swipeMenuView(_ swipeMenuView: SwipeMenuView, viewDidSetupAt currentIndex: Int) { }
public func swipeMenuView(_ swipeMenuView: SwipeMenuView, willChangeIndexFrom fromIndex: Int, to toIndex: Int) { }
public func swipeMenuView(_ swipeMenuView: SwipeMenuView, didChangeIndexFrom fromIndex: Int, to toIndex: Int) { }
}
// MARK: - SwipeMenuViewDataSource
public protocol SwipeMenuViewDataSource: class {
/// Return the number of pages in `SwipeMenuView`.
func numberOfPages(in swipeMenuView: SwipeMenuView) -> Int
/// Return strings to be displayed at the tab in `SwipeMenuView`.
func swipeMenuView(_ swipeMenuView: SwipeMenuView, titleForPageAt index: Int) -> String
/// Return a ViewController to be displayed at the page in `SwipeMenuView`.
func swipeMenuView(_ swipeMenuView: SwipeMenuView, viewControllerForPageAt index: Int) -> UIViewController
}
// MARK: - SwipeMenuView
open class SwipeMenuView: UIView {
/// An object conforms `SwipeMenuViewDelegate`. Provide views to populate the `SwipeMenuView`.
open weak var delegate: SwipeMenuViewDelegate?
/// An object conforms `SwipeMenuViewDataSource`. Provide views and respond to `SwipeMenuView` events.
open weak var dataSource: SwipeMenuViewDataSource?
open fileprivate(set) var tabView: TabView? {
didSet {
guard let tabView = tabView else { return }
tabView.dataSource = self
tabView.tabViewDelegate = self
addSubview(tabView)
layout(tabView: tabView)
}
}
open fileprivate(set) var contentScrollView: ContentScrollView? {
didSet {
guard let contentScrollView = contentScrollView else { return }
contentScrollView.delegate = self
contentScrollView.dataSource = self
addSubview(contentScrollView)
layout(contentScrollView: contentScrollView)
}
}
public var options: SwipeMenuViewOptions
fileprivate var isLayoutingSubviews: Bool = false
fileprivate var pageCount: Int {
return dataSource?.numberOfPages(in: self) ?? 0
}
fileprivate var isJumping: Bool = false
fileprivate var isPortrait: Bool = true
/// The index of the front page in `SwipeMenuView` (read only).
open private(set) var currentIndex: Int = 0
private var jumpingToIndex: Int?
public init(frame: CGRect, options: SwipeMenuViewOptions? = nil) {
if let options = options {
self.options = options
} else {
self.options = .init()
}
super.init(frame: frame)
}
public required init?(coder aDecoder: NSCoder) {
self.options = .init()
super.init(coder: aDecoder)
}
open override func layoutSubviews() {
isLayoutingSubviews = true
super.layoutSubviews()
if !isJumping {
reloadData(isOrientationChange: true)
}
}
open override func didMoveToSuperview() {
super.didMoveToSuperview()
setup()
}
/// Reloads all `SwipeMenuView` item views with the dataSource and refreshes the display.
public func reloadData(options: SwipeMenuViewOptions? = nil, default defaultIndex: Int? = nil, isOrientationChange: Bool = false) {
if let options = options {
self.options = options
}
isLayoutingSubviews = isOrientationChange
if !isLayoutingSubviews {
reset()
setup(default: defaultIndex ?? currentIndex)
}
jump(to: defaultIndex ?? currentIndex, animated: false)
isLayoutingSubviews = false
}
/// Jump to the selected page.
public func jump(to index: Int, animated: Bool) {
guard let tabView = tabView, let contentScrollView = contentScrollView else { return }
if currentIndex != index {
delegate?.swipeMenuView(self, willChangeIndexFrom: currentIndex, to: index)
}
jumpingToIndex = index
tabView.jump(to: index)
contentScrollView.jump(to: index, animated: animated)
}
/// Notify changing orientaion to `SwipeMenuView` before it.
public func willChangeOrientation() {
isLayoutingSubviews = true
setNeedsLayout()
}
fileprivate func update(from fromIndex: Int, to toIndex: Int) {
if !isLayoutingSubviews {
delegate?.swipeMenuView(self, willChangeIndexFrom: fromIndex, to: toIndex)
}
tabView?.update(toIndex)
contentScrollView?.update(toIndex)
if !isJumping {
// delay setting currentIndex until end scroll when jumping
currentIndex = toIndex
}
if !isJumping && !isLayoutingSubviews {
delegate?.swipeMenuView(self, didChangeIndexFrom: fromIndex, to: toIndex)
}
}
// MARK: - Setup
private func setup(default defaultIndex: Int = 0) {
delegate?.swipeMenuView(self, viewWillSetupAt: defaultIndex)
backgroundColor = .clear
tabView = TabView(frame: CGRect(x: 0, y: 0, width: frame.width, height: options.tabView.height), options: options.tabView)
tabView?.clipsToBounds = options.tabView.clipsToBounds
contentScrollView = ContentScrollView(frame: CGRect(x: 0, y: options.tabView.height, width: frame.width, height: frame.height - options.tabView.height), default: defaultIndex, options: options.contentScrollView)
contentScrollView?.clipsToBounds = options.contentScrollView.clipsToBounds
tabView?.update(defaultIndex)
contentScrollView?.update(defaultIndex)
currentIndex = defaultIndex
delegate?.swipeMenuView(self, viewDidSetupAt: defaultIndex)
}
private func layout(tabView: TabView) {
tabView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
tabView.topAnchor.constraint(equalTo: self.topAnchor),
tabView.leadingAnchor.constraint(equalTo: self.leadingAnchor),
tabView.trailingAnchor.constraint(equalTo: self.trailingAnchor),
tabView.heightAnchor.constraint(equalToConstant: options.tabView.height)
])
}
private func layout(contentScrollView: ContentScrollView) {
contentScrollView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
contentScrollView.topAnchor.constraint(equalTo: self.topAnchor, constant: options.tabView.height),
contentScrollView.leadingAnchor.constraint(equalTo: self.leadingAnchor),
contentScrollView.trailingAnchor.constraint(equalTo: self.trailingAnchor),
contentScrollView.bottomAnchor.constraint(equalTo: self.bottomAnchor)
])
}
private func reset() {
if !isLayoutingSubviews {
currentIndex = 0
}
if let tabView = tabView, let contentScrollView = contentScrollView {
tabView.removeFromSuperview()
contentScrollView.removeFromSuperview()
tabView.reset()
contentScrollView.reset()
}
}
}
// MARK: - TabViewDelegate, TabViewDataSource
extension SwipeMenuView: TabViewDelegate, TabViewDataSource {
public func tabView(_ tabView: TabView, didSelectTabAt index: Int) {
guard let contentScrollView = contentScrollView,
currentIndex != index else { return }
isJumping = true
jumpingToIndex = index
contentScrollView.jump(to: index, animated: true)
update(from: currentIndex, to: index)
}
public func numberOfItems(in menuView: TabView) -> Int {
return dataSource?.numberOfPages(in: self) ?? 0
}
public func tabView(_ tabView: TabView, titleForItemAt index: Int) -> String? {
return dataSource?.swipeMenuView(self, titleForPageAt: index)
}
}
// MARK: - UIScrollViewDelegate
extension SwipeMenuView: UIScrollViewDelegate {
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
if isJumping || isLayoutingSubviews { return }
// update currentIndex
if scrollView.contentOffset.x >= frame.width * CGFloat(currentIndex + 1) {
update(from: currentIndex, to: currentIndex + 1)
} else if scrollView.contentOffset.x <= frame.width * CGFloat(currentIndex - 1) {
update(from: currentIndex, to: currentIndex - 1)
}
updateTabViewAddition(by: scrollView)
}
public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
if isJumping || isLayoutingSubviews {
if let toIndex = jumpingToIndex {
delegate?.swipeMenuView(self, didChangeIndexFrom: currentIndex, to: toIndex)
currentIndex = toIndex
jumpingToIndex = nil
}
isJumping = false
isLayoutingSubviews = false
return
}
updateTabViewAddition(by: scrollView)
}
/// update addition in tab view
private func updateTabViewAddition(by scrollView: UIScrollView) {
moveAdditionView(scrollView: scrollView)
}
/// update underbar position
private func moveAdditionView(scrollView: UIScrollView) {
if let tabView = tabView, let contentScrollView = contentScrollView {
let ratio = scrollView.contentOffset.x.truncatingRemainder(dividingBy: contentScrollView.frame.width) / contentScrollView.frame.width
switch scrollView.contentOffset.x {
case let offset where offset >= frame.width * CGFloat(currentIndex):
tabView.moveAdditionView(index: currentIndex, ratio: ratio, direction: .forward)
case let offset where offset < frame.width * CGFloat(currentIndex):
tabView.moveAdditionView(index: currentIndex, ratio: ratio, direction: .reverse)
default:
break
}
}
}
}
// MARK: - ContentScrollViewDataSource
extension SwipeMenuView: ContentScrollViewDataSource {
public func numberOfPages(in contentScrollView: ContentScrollView) -> Int {
return dataSource?.numberOfPages(in: self) ?? 0
}
public func contentScrollView(_ contentScrollView: ContentScrollView, viewForPageAt index: Int) -> UIView? {
return dataSource?.swipeMenuView(self, viewControllerForPageAt: index).view
}
}
| 34.226981 | 219 | 0.650275 |
1e838e8e0a9ea145099400cc2451e74a64945623 | 2,236 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import LanguageServerProtocol
import Basic
import enum Utility.Platform
/// A simple BuildSystem suitable as a fallback when accurate settings are unknown.
public final class FallbackBuildSystem: BuildSystem {
/// The path to the SDK.
lazy var sdkpath: AbsolutePath? = {
if case .darwin? = Platform.currentPlatform,
let str = try? Process.checkNonZeroExit(
args: "/usr/bin/xcrun", "--show-sdk-path", "--sdk", "macosx"),
let path = try? AbsolutePath(validating: str.spm_chomp())
{
return path
}
return nil
}()
public var indexStorePath: AbsolutePath? { return nil }
public var indexDatabasePath: AbsolutePath? { return nil }
public func settings(for url: URL, _ language: Language) -> FileBuildSettings? {
guard let path = try? AbsolutePath(validating: url.path) else {
return nil
}
switch language {
case .swift:
return settingsSwift(path)
case .c, .cpp, .objective_c, .objective_cpp:
return settingsClang(path, language)
default:
return nil
}
}
func settingsSwift(_ path: AbsolutePath) -> FileBuildSettings {
var args: [String] = []
if let sdkpath = sdkpath {
args += [
"-sdk",
sdkpath.asString,
]
}
args.append(path.asString)
return FileBuildSettings(preferredToolchain: nil, compilerArguments: args)
}
func settingsClang(_ path: AbsolutePath, _ language: Language) -> FileBuildSettings {
var args: [String] = []
if let sdkpath = sdkpath {
args += [
"-isysroot",
sdkpath.asString,
]
}
args.append(path.asString)
return FileBuildSettings(preferredToolchain: nil, compilerArguments: args)
}
}
| 29.813333 | 87 | 0.621199 |
724e069c572c7151a7535291d44ab827ffa99739 | 960 | //
// File.swift
//
//
// Created by Christophe Bronner on 2020-10-11.
//
//MARK: - Command Group
public struct Group {
//MARK: Properties
internal let name: String
internal let summary: String?
internal private(set) var commands: [Command] = []
//MARK: Initialization
public init(_ name: String, description: String = "") {
self.name = name
let tmp = sanitize(description)
summary = tmp.isEmpty ? nil : tmp
}
//MARK: Methods
public func with(command: Command) -> Group {
var tmp = self
tmp.add(command: command)
return tmp
}
internal func command(for keyword: String) -> Command? {
commands.first { $0.is(keyword) }
}
//MARK: Operators
public static func +=(lhs: inout Group, rhs: Command) {
lhs.add(command: rhs)
}
//MARK: Utilities
private mutating func add(command: Command) {
assert(!commands.contains(command), "Cannot have duplicate commands in Group")
commands.append(command)
}
}
| 18.113208 | 80 | 0.664583 |
33a86b176bb980aad2250e2a7c8b9b56238c3823 | 2,595 | //
// RemoteImage.swift
// Politifi
//
// Created by Ethan Hanlon on 1/18/21.
// Shows an image from URL. Do not allow users to insert their own URLs, as this is a potential security risk.
// Only use in rare cases where you don't want any caching. TODO: Elaborate
import SwiftUI
struct RemoteImage: View {
let resizable: Bool
var body: some View {
if resizable {
selectImage()
.resizable()
} else {
selectImage()
}
}
private enum loadState {
case loading, success, failure
}
private class Loader: ObservableObject {
var data = Data()
var state = loadState.loading
init(url: String) {
guard let parsedURL = URL(string: url) else {
print("Failed to grab image at: \(url)")
return
}
URLSession.shared.dataTask(with: parsedURL) { data, response, error in
if let data = data, data.count > 0 {
self.data = data
self.state = .success
} else {
self.state = .failure
}
DispatchQueue.main.async {
self.objectWillChange.send()
}
}.resume()
}
}
@ObservedObject private var loader: Loader
var loading: Image
var failure: Image
init(url: String, loading: Image = Image(systemName: "person.circle.fill"), resizable: Bool = true, failure: Image = Image(systemName: "multiply.circle")) {
_loader = ObservedObject(wrappedValue: Loader(url: url))
self.resizable = resizable
self.loading = loading
self.failure = failure
}
private func selectImage() -> Image {
switch loader.state {
case.loading:
return loading
case.failure:
return failure
default:
if let image = UIImage(data: loader.data) {
return Image(uiImage: image)
} else {
return failure
}
}
}
}
struct RemoteImage_Previews: PreviewProvider {
static var previews: some View {
Group {
//Turn on live preview to see the image load
// RemoteImage(url: "https://i.pinimg.com/originals/8e/06/5c/8e065c7a30d4724aeed6e5f9484b54ad.jpg")
// .previewLayout(.sizeThatFits)
// RemoteImage(url: "http://invalid")
// .previewLayout(.sizeThatFits)
}
}
}
| 29.157303 | 160 | 0.534489 |
e6bfb3ba5740f0f9589d71ce553e85ead3e2eddf | 2,418 | //
// SubscriptionManager.swift
// ACHNBrowserUI
//
// Created by Thomas Ricouard on 02/05/2020.
// Copyright © 2020 Thomas Ricouard. All rights reserved.
//
import Foundation
import SwiftUI
import Purchases
public class SubscriptionManager: ObservableObject {
public static let shared = SubscriptionManager()
public enum SubscriptionStatus {
case subscribed, notSubscribed
}
@Published public var monthlySubscription: Purchases.Package?
@Published public var yearlySubscription: Purchases.Package?
@Published public var lifetime: Purchases.Package?
@Published public var inPaymentProgress = false
@Published public var paymentStatus: SKPaymentTransactionState?
@Published public var subscriptionStatus: SubscriptionStatus = AppUserDefaults.shared.isSubscribed ? .subscribed : .notSubscribed
init() {
Purchases.configure(withAPIKey: "glVAIPplNhAuvgOlCcUcrEaaCQwLRzQs")
Purchases.shared.offerings { (offerings, error) in
self.monthlySubscription = offerings?.current?.monthly
self.lifetime = offerings?.current?.lifetime
self.yearlySubscription = offerings?.current?.annual
}
refreshSubscription()
}
public func purchase(source: String, product: Purchases.Package) {
guard !inPaymentProgress else { return }
inPaymentProgress = true
Purchases.shared.setAttributes(["source": source,
"number_of_launch": "\(AppUserDefaults.shared.numberOfLaunch)"])
Purchases.shared.purchasePackage(product) { (_, info, _, _) in
self.processInfo(info: info)
}
}
public func refreshSubscription() {
Purchases.shared.purchaserInfo { (info, _) in
self.processInfo(info: info)
}
}
public func restorePurchase() {
Purchases.shared.restoreTransactions { (info, _) in
self.processInfo(info: info)
}
}
private func processInfo(info: Purchases.PurchaserInfo?) {
if info?.entitlements.all["AC+"]?.isActive == true {
subscriptionStatus = .subscribed
AppUserDefaults.shared.isSubscribed = true
} else {
AppUserDefaults.shared.isSubscribed = false
subscriptionStatus = .notSubscribed
}
inPaymentProgress = false
}
}
| 34.056338 | 133 | 0.655914 |
6992fec58610fb98c73057e4073164a98e89bcbb | 10,690 | //
// Copyright (c) 2018 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//
// 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 AVFoundation
import UIKit
import FirebaseMLVision
/// Defines UI-related utilitiy methods for vision detection.
public class UIUtilities {
// MARK: - Public
public static func addCircle( atPoint point: CGPoint, to view: UIView, color: UIColor, radius: CGFloat )
{
let divisor: CGFloat = 2.0
let xCoord = point.x - radius / divisor
let yCoord = point.y - radius / divisor
let circleRect = CGRect(x: xCoord, y: yCoord, width: radius, height: radius)
let circleView = UIView(frame: circleRect)
circleView.layer.cornerRadius = radius / divisor
circleView.alpha = Constants.circleViewAlpha
circleView.backgroundColor = color
view.addSubview(circleView)
}
public static func addRectangle(_ rectangle: CGRect, to view: UIView, color: UIColor)
{
let rectangleView = UIView(frame: rectangle)
rectangleView.layer.cornerRadius = Constants.rectangleViewCornerRadius
rectangleView.alpha = Constants.rectangleViewAlpha
rectangleView.backgroundColor = color
view.addSubview(rectangleView)
}
public static func fillColorOnShape(withPoints pointsArray: [CGPoint], to view: UIView, color: UIColor, makeupType: String)
{
let path = UIBezierPath()
path.lineCapStyle = .round
for i in 0 ..< pointsArray.count
{
let point = pointsArray[i] // else { return }
// print("pointttttttttt", point.x, point.y)
if i == 0
{
path.move(to: CGPoint(x: point.x, y: point.y))
}
else
{
path.addLine(to: CGPoint(x: point.x, y: point.y))
}
if i == pointsArray.count - 1
{
path.close()
}
}
let shapeLayer = CAShapeLayer()
shapeLayer.path = path.cgPath
shapeLayer.strokeColor = color.cgColor
shapeLayer.fillColor = color.cgColor
if makeupType == "EyeShadow"
{
shapeLayer.shadowPath = path.cgPath
shapeLayer.shadowColor = color.cgColor
shapeLayer.shadowOffset = CGSize(width: 1, height: 2)
shapeLayer.shadowOpacity = 0.8
shapeLayer.shadowRadius = 10
shapeLayer.strokeColor = UIColor(red: 255/255, green: 255/255, blue: 255/255, alpha: 0.0).cgColor
shapeLayer.fillColor = UIColor(red: 255/255, green: 255/255, blue: 255/255, alpha: 0.0).cgColor
}
if makeupType != "Blush"
{
view.layer.addSublayer(shapeLayer)
}
if makeupType == "Blush"
{
let point1 = pointsArray[0]
let point2 = pointsArray[1]
let point3 = pointsArray[2]
let xPoint = ( point1.x + point2.x + point3.x)/3
let yPoint = ( point1.y + point2.y + point3.y)/3
let totalDistance = CGPointDistance(from: point1, to: point2)
print("pointt is :", xPoint, yPoint, totalDistance)
let cx = (point1.x + point2.x + point3.x) / 3
let cy = (point1.y + point2.y + point3.y) / 3
let a = lineDistance(point1: pointsArray[0], point2: pointsArray[1])
let b = lineDistance(point1: pointsArray[1], point2: pointsArray[2])
let c = lineDistance(point1: pointsArray[2], point2: pointsArray[0])
let p = (a + b + c)/2
let area = b / 2 * (point2.y - point1.y)
var r = (2 * area) / p
r=r/2;
print("Radius is :", r)
if (r>0) {
let shape = UIBezierPath(arcCenter: CGPoint(x: cx, y: cy), radius: r-15, startAngle: CGFloat(0), endAngle: CGFloat.pi * 2, clockwise: true)
let shapeLayer = CAShapeLayer()
shapeLayer.path = shape.cgPath
shapeLayer.shadowPath = shape.cgPath
shapeLayer.shadowColor = color.cgColor
shapeLayer.shadowOffset = CGSize(width: 1, height: 2)
shapeLayer.shadowOpacity = 0.8
shapeLayer.shadowRadius = 10
shapeLayer.fillColor = UIColor(red: 255/255, green: 255/255, blue: 255/255, alpha: 0.0).cgColor
view.layer.addSublayer(shapeLayer)
}
}
}
public static func lineDistance(point1: CGPoint, point2: CGPoint) -> CGFloat
{
var xs = 0.0
var ys = 0.0
xs = Double(point2.x - point1.x)
xs = xs * xs;
ys = Double(point2.y - point1.y)
ys = ys * ys;
return CGFloat(sqrt(xs + ys));
}
public static func CGPointDistanceSquared(from: CGPoint, to: CGPoint) -> CGFloat {
return (from.x - to.x) * (from.x - to.x) + (from.y - to.y) * (from.y - to.y)
}
public static func CGPointDistance(from: CGPoint, to: CGPoint) -> CGFloat {
return sqrt(CGPointDistanceSquared(from: from, to: to))
}
public static func createRoundedTriangle(width: CGFloat, height: CGFloat, radius: CGFloat) -> CGPath {
let point1 = CGPoint(x: -width / 2, y: height / 2)
let point2 = CGPoint(x: 0, y: -height / 2)
let point3 = CGPoint(x: width / 2, y: height / 2)
let path = CGMutablePath()
path.move(to: CGPoint(x: 0, y: height / 2))
path.addArc(tangent1End: point1, tangent2End: point2, radius: radius)
path.addArc(tangent1End: point2, tangent2End: point3, radius: radius)
path.addArc(tangent1End: point3, tangent2End: point1, radius: radius)
path.closeSubpath()
return path
}
public static func drawLineAboveEye(withPoints pointsArray: [CGPoint], to view: UIView, color: UIColor)
{
let path = UIBezierPath()
for i in 0 ..< pointsArray.count
{
let point = pointsArray[i] // else { return }
// print("pointttttttttt", point.x, point.y)
if i == 0
{
path.move(to: CGPoint(x: point.x, y: point.y))
}
else
{
path.addLine(to: CGPoint(x: point.x, y: point.y))
}
if i == pointsArray.count - 1
{
// path.close()
}
}
let shapeLayer = CAShapeLayer()
shapeLayer.path = path.cgPath
shapeLayer.strokeColor = color.cgColor
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.lineWidth = 2
view.layer.addSublayer(shapeLayer)
}
public static func addShape(withPoints points: [NSValue]?, to view: UIView, color: UIColor)
{
guard let points = points else { return }
let path = UIBezierPath()
for (index, value) in points.enumerated()
{
let point = value.cgPointValue
if index == 0 {
path.move(to: point)
} else {
path.addLine(to: point)
}
if index == points.count - 1 {
path.close()
}
}
let shapeLayer = CAShapeLayer()
shapeLayer.path = path.cgPath
shapeLayer.fillColor = color.cgColor
let rect = CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height)
let shapeView = UIView(frame: rect)
shapeView.alpha = Constants.shapeViewAlpha
shapeView.layer.addSublayer(shapeLayer)
view.addSubview(shapeView)
}
public static func imageOrientation(
fromDevicePosition devicePosition: AVCaptureDevice.Position = .back
) -> UIImage.Orientation {
var deviceOrientation = UIDevice.current.orientation
if deviceOrientation == .faceDown || deviceOrientation == .faceUp ||
deviceOrientation == .unknown {
deviceOrientation = currentUIOrientation()
}
switch deviceOrientation {
case .portrait:
return devicePosition == .front ? .leftMirrored : .right
case .landscapeLeft:
return devicePosition == .front ? .downMirrored : .up
case .portraitUpsideDown:
return devicePosition == .front ? .rightMirrored : .left
case .landscapeRight:
return devicePosition == .front ? .upMirrored : .down
case .faceDown, .faceUp, .unknown:
return .up
@unknown default:
return .up
}
}
public static func visionImageOrientation(
from imageOrientation: UIImage.Orientation
) -> VisionDetectorImageOrientation {
switch imageOrientation {
case .up:
return .topLeft
case .down:
return .bottomRight
case .left:
return .leftBottom
case .right:
return .rightTop
case .upMirrored:
return .topRight
case .downMirrored:
return .bottomLeft
case .leftMirrored:
return .leftTop
case .rightMirrored:
return .rightBottom
@unknown default:
return .topLeft
}
}
// MARK: - Private
private static func currentUIOrientation() -> UIDeviceOrientation {
let deviceOrientation = { () -> UIDeviceOrientation in
switch UIApplication.shared.statusBarOrientation {
case .landscapeLeft:
return .landscapeRight
case .landscapeRight:
return .landscapeLeft
case .portraitUpsideDown:
return .portraitUpsideDown
case .portrait, .unknown:
return .portrait
@unknown default:
return .portrait
}
}
guard Thread.isMainThread else {
var currentOrientation: UIDeviceOrientation = .portrait
DispatchQueue.main.sync {
currentOrientation = deviceOrientation()
}
return currentOrientation
}
return deviceOrientation()
}
}
// MARK: - Constants
private enum Constants {
static let circleViewAlpha: CGFloat = 0.7
static let rectangleViewAlpha: CGFloat = 0.3
static let shapeViewAlpha: CGFloat = 0.3
static let rectangleViewCornerRadius: CGFloat = 10.0
}
| 32.691131 | 155 | 0.58681 |
72457756554ea49f1e3b002eeae1d3792de341d9 | 2,085 | //
// Adapter+HUD.swift
// HttpUtils
//
// Created by season on 2019/6/18.
// Copyright © 2019 season. All rights reserved.
//
import Foundation
public protocol HUDProtocol {
var waitMessage: String? { set get }
var successMessage: String? { set get }
var errorMessage: String? { set get }
func showWait()
func showNetworkStatus(status: NetworkType)
func showError(error: Error?)
func showMessage(message: String)
func clear()
}
extension Adapter {
public struct HUD: HUDProtocol {
/// 默认
public static let `default` = HUD()
/// 等待的文字描述
public var waitMessage: String?
/// 成功的文字描述
public var successMessage: String?
/// 错误的文字描述
public var errorMessage: String?
/// 初始化方法
public init(waitMessage: String? = nil, successMessage: String? = nil, errorMessage: String? = nil) {
self.waitMessage = waitMessage
self.successMessage = successMessage
self.errorMessage = errorMessage
}
/// 等待界面
public func showWait() {
Hud.showWait(message: waitMessage, autoClear: false)
}
/// 展示网络状态
///
/// - Parameter status: 网络状态
public func showNetworkStatus(status: NetworkType) {
Hud.showMessage(message: status.description)
}
/// 展示错误
///
/// - Parameter error: Error
public func showError(error: Error? = nil) {
if let errorMessage = errorMessage {
Hud.showMessage(message: errorMessage)
}else {
Hud.showMessage(message: error.debugDescription)
}
}
/// 展示信息
///
/// - Parameter message: 信息
public func showMessage(message: String) {
Hud.showMessage(message: message)
}
/// 清除
public func clear() {
Hud.clear()
}
}
}
| 23.693182 | 109 | 0.526619 |
33f1cf9eeba9505dbb5144b1f5425fce4a70b3bc | 957 | //
// ColorPaletteExtractorTests.swift
// ColorPaletteExtractorTests
//
// Created by Maria Eduarda Porto on 12/04/21.
//
import XCTest
@testable import ColorPaletteExtractor
class ColorPaletteExtractorTests: 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.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 28.147059 | 111 | 0.683386 |
262e1402709778de22ab99fe740222e8e677eefd | 13,332 | //
// UnkeyedDecodingContainer+AdvancedCodingHelpers.swift
// AdvancedCodableHelpers
//
// Created by Tyler Anger on 2019-11-25.
//
import Foundation
import Nillable
import SwiftClassCollections
public extension UnkeyedDecodingContainer {
/// Dynamically decode a given type.
/// - Parameters:
/// - decodingFunc: The decoding function to call providing the decoder
/// - decoder: The decoder used within the custom decoding function
mutating func decode<T>(decodingFunc: (_ decoder: Decoder) throws -> T) throws -> T {
return try decodingFunc(try self.superDecoder())
}
/// Dynamically decode a given type if present.
/// - Parameters:
/// - decodingFunc: The decoding function to call providing the decoder
/// - decoder: The decoder used within the custom decoding function
mutating func decodeIfPresent<T>(decodingFunc: (_ decoder: Decoder) throws -> T) throws -> T? {
guard !self.isAtEnd && !((try? self.decodeNil()) ?? false) else { return nil }
return try decode(decodingFunc: decodingFunc)
}
/// Dynamically decode a given type if present.
/// - Parameters:
/// - defaultValue: The default value to use if object not present
/// - decodingFunc: The decoding function to call providing the decoder
/// - decoder: The decoder used within the custom decoding function
mutating func decodeIfPresent<T>(withDefaultValue defaultValue: @autoclosure () -> T,
decodingFunc: (_ decoder: Decoder) throws -> T) throws -> T {
return (try self.decodeIfPresent(decodingFunc: decodingFunc)) ?? defaultValue()
}
/// Dynamically decode an array of a given type.
/// - Parameters:
/// - decodingFunc: The decoding function to call providing the decoder
/// - decoder: The decoder used within the custom decoding function
mutating func decodeArray<T>(decodingFunc: (_ decoder: Decoder) throws -> T) throws -> [T] {
var container = try self.nestedUnkeyedContainer()
var rtn: [T] = []
while !container.isAtEnd {
//let obj = try decodingFunc(WrappedUnkeyedSingleValueDecoder(container))
let obj = try decodingFunc(try container.superDecoder())
rtn.append(obj)
}
return rtn
}
/// Dynamically decode an array of a given type if present
/// - Parameters:
/// - decodingFunc: The decoding function to call providing the decoder
/// - decoder: The decoder used within the custom decoding function
mutating func decodeArrayIfPresent<T>(decodingFunc: (_ decoder: Decoder) throws -> T) throws -> [T]? {
guard !self.isAtEnd && !((try? self.decodeNil()) ?? false) else { return nil }
return try self.decodeArray(decodingFunc: decodingFunc)
}
/// Dynamically decode an array of a given type if present
/// - Parameters:
/// - defaultValue: The default value to use if object not present
/// - decodingFunc: The decoding function to call providing the decoder
/// - decoder: The decoder used within the custom decoding function
mutating func decodeArrayIfPresent<T>(withDefaultValue defaultValue: @autoclosure () -> [T],
decodingFunc: (_ decoder: Decoder) throws -> T) throws -> [T] {
return (try self.decodeArrayIfPresent(decodingFunc: decodingFunc)) ?? defaultValue()
}
/// Dynamically decode an array of a given type.
/// - Parameters:
/// - decodingFunc: The decoding function to call providing the decoder
/// - decoder: The decoder used within the custom decoding function
@available(*, deprecated, renamed: "decodeArray")
mutating func decode<T>(decodingFunc: (_ decoder: Decoder) throws -> T) throws -> [T] {
return try self.decodeArray(decodingFunc: decodingFunc)
}
/// Dynamically decode an array of a given type if present
/// - Parameters:
/// - decodingFunc: The decoding function to call providing the decoder
/// - decoder: The decoder used within the custom decoding function
@available(*, deprecated, renamed: "decodeIfPresent")
mutating func decodeIfPresent<T>(decodingFunc: (_ decoder: Decoder) throws -> T) throws -> [T]? {
return try self.decodeArrayIfPresent(decodingFunc: decodingFunc)
}
/// Dynamically decode an array of a given type if present
/// - Parameters:
/// - defaultValue: The default value to use if object not present
/// - decodingFunc: The decoding function to call providing the decoder
/// - decoder: The decoder used within the custom decoding function
@available(*, deprecated, renamed: "decodeIfPresent")
mutating func decodeIfPresent<T>(withDefaultValue defaultValue: @autoclosure () -> [T],
decodingFunc: (_ decoder: Decoder) throws -> T) throws -> [T] {
return try self.decodeArrayIfPresent(withDefaultValue: defaultValue,
decodingFunc: decodingFunc)
}
}
public extension UnkeyedDecodingContainer {
/// Decode a Dictionary type based on return from the given container
///
/// - Parameters:
/// - excludingKeys: Any keys to exclude from the top level
/// - customDecoding: Function to try and do custom decoding of complex objects or nil if no custom decoded required
/// - Returns: Return a dictionary type based on return from the given container
mutating func decodeAnyDictionary<D>(excludingKeys: [D.Key] = [],
customDecoding: (_ decoder: Decoder) throws -> Any? = { _ in return nil }) throws -> D where D: ReEncapsulatableDictionary, D.Key: DictionaryKeyCodable, D.Value == Any {
let container = try self.nestedContainer(keyedBy: CodableKey.self)
return try container.decodeAndRemapDictionary(excludingKeys: excludingKeys.map {
return $0.dynamicCodingKey
},
customDecoding: customDecoding)
}
/// Decodes the whole Unkeyed container as the array
///
/// Decoding sequence tries as follows:
/// Int, UInt, Float, String, Double, Bool, Date, Data, Complex Object, Array
///
/// - Parameters:
/// - customDecoding: a method for custom decoding of complex objects
/// - Returns: Returns an array of decoded objects
mutating func decodeAnyArray(customDecoding: (_ decoder: Decoder) throws -> Any? = { _ in return nil }) throws -> Array<Any> {
var rtn: Array<Any> = Array<Any>()
while !self.isAtEnd {
var customValue: Any? = nil
do {
customValue = try customDecoding(WrappedUnkeyedDecoder(self,
codingPathModifier: .appending(CodableKey(index: self.currentIndex))))
if customValue != nil {
// This causes use to goto the next element in the array
// since using WrappedUnkeyedDecoder our array and does not update
// the current index when it executes
_ = try? self.superDecoder()
}
//let sup = try self.superDecoder()
//customValue = try customDecoding(sup)
//customValue = try customDecoding(WrappedUnkeyedSingleValueDecoder(self))
} catch { }
if let v = customValue {
rtn.append(v)
} else if let v = try? self.decodeNil(), v {
rtn.append(AnyNil) //If array was an optional array. We should add the nil in.
} else if let v = try? self.decode(Int.self) {
rtn.append(v)
} else if let v = try? self.decode(UInt.self) {
rtn.append(v)
} else if let v = try? self.decode(Float.self) {
rtn.append(v)
} else if let v = try? self.decode(String.self) {
rtn.append(v)
} else if let v = try? self.decode(Double.self) {
rtn.append(v)
} else if let v = try? self.decode(Bool.self) {
rtn.append(v)
} else if let v = try? self.decode(Date.self) {
rtn.append(v)
} else if let v = try? self.decode(Data.self) {
rtn.append(v)
} else if let v = try? self.nestedContainer(keyedBy: CodableKey.self) {
rtn.append(try v.decodeToAnyDictionary(customDecoding: customDecoding))
} else if var v = try? self.nestedUnkeyedContainer() {
rtn.append(try v.decodeAnyArray(customDecoding: customDecoding))
} else {
throw DecodingError.typeMismatch(Any.self,
DecodingError.Context(codingPath: self.codingPath.appending(index: self.currentIndex),
debugDescription: "Unsupported type"))
}
}
return rtn
}
}
public extension UnkeyedDecodingContainer {
/// Provides an easy method of decoding an optional/single value/array object into an array
///
/// The following rules apply when decoding:
/// 1. Tries to decode as a single value object and reutrns as a 1 element array
/// 2. Tries to decode as an array of objects and returns it
///
/// - Parameters:
/// - customDecoding: Custom decoding of object type
/// - Returns: Returns an array of elements that decoded or nil if no key found
mutating func decodeFromSingleOrArray<Element>(customDecoding: (_ decoder: Decoder) throws -> Element) throws -> [Element] {
let decoder = try self.superDecoder()
//if let v = try? customDecoding(WrappedPreKeyedDecoder(self, preKey: key)) { return [v] }
if let v = try? customDecoding(decoder) {
return [v]
} else {
var container = try decoder.unkeyedContainer()
var rtn: [Element] = []
while !container.isAtEnd {
let decoder = try container.superDecoder()
//let v = try container.decode(Element.self)
let v = try customDecoding(decoder)
rtn.append(v)
}
return rtn
}
}
/// Provides an easy method of decoding an optional/single value/array object into an array, or nil if no decoding options were available
///
/// The following rules apply when decoding:
/// 1. Tries to decode as a single value object and reutrns as a 1 element array
/// 2. Tries to decode as an array of objects and returns it
/// 3. returns nil
///
/// - Parameters:
/// - customDecoding: Custom decoding of object type
/// - Returns: Returns an array of elements that decoded or nil if no key found
mutating func decodeFromSingleOrArrayIfPresent<Element>(customDecoding: (_ decoder: Decoder) throws -> Element) throws -> [Element]? {
guard self.notAtEndAndNotNil() else { return nil }
return try self.decodeFromSingleOrArray(customDecoding: customDecoding)
}
/// Provides an easy method of decoding an optional/single value/array object into an array, or defaultValue if no decoding options were available
///
/// The following rules apply when decoding:
/// 1. Tries to decode as a single value object and reutrns as a 1 element array
/// 2. Tries to decode as an array of objects and returns it
/// 3. returns default value
///
/// - Parameters:
/// - defaultValue: The value to return if object not present
/// - customDecoding: Custom decoding of object type
/// - Returns: Returns an array of elements that decoded or nil if no key found
mutating func decodeFromSingleOrArrayIfPresent<Element>(withDefaultValue defaultValue: @autoclosure () -> [Element],
customDecoding: (_ decoder: Decoder) throws -> Element) throws -> [Element] {
return (try self.decodeFromSingleOrArrayIfPresent(customDecoding: customDecoding)) ?? defaultValue()
}
/// Provides an easy method of decoding an optional/single value/array object into an array, or an empty array if no decoding options were available
///
/// The following rules apply when decoding:
/// 1. Tries to decode as a single value object and reutrns as a 1 element array
/// 2. Tries to decode as an array of objects and returns it
/// 3. returns empty array
///
/// - Parameters:
/// - customDecoding: Custom decoding of object type
/// - Returns: Returns an array of elements that decoded or an empty array if no key found
mutating func decodeFromSingleOrArrayIfPresentWithEmptyDefault<Element>(customDecoding: (_ decoder: Decoder) throws -> Element) throws -> [Element] {
return try self.decodeFromSingleOrArrayIfPresent(withDefaultValue: [],
customDecoding: customDecoding)
}
}
| 51.08046 | 207 | 0.616262 |
9ceeef82b7f9254ad391f31dd786e27e0b3ef5ad | 319 | //
// CreateCollectionResponse.swift
// Monotone
//
// Created by Xueliang Chen on 2020/12/11.
//
import Foundation
import ObjectMapper
class CreateCollectionResponse: BaseResponse{
public var collection: Collection?
override func mapping(map: Map) {
collection = Collection(map: map)
}
}
| 17.722222 | 45 | 0.69906 |
aca3c96e47892733281661413a8bfc950d72e17f | 651 | //
// RelationshipsEndpoint.swift
// ConceptOffice
//
// Created by Kirill Averyanov on 28/05/2017.
// Copyright © 2017 Den Ree. All rights reserved.
//
import Alamofire
enum InstagramRelationshipRouter: AnyInstagramNetworkRouter {
// MARK: - Requests
case getFollows
case getFollowedBy
case getRequestedBy
case getRelationship(userId: String)
case postRelationship(PostRelationshipParameter)
// MARK: - Parameters
struct PostRelationshipParameter {
let userId: String
let action: Action
// MARK: Nested
enum Action: String {
case follow
case unfollow
case approve
case ignore
}
}
}
| 21 | 61 | 0.708141 |
141c1283041a9cd6e5d4d03bd045c72a2a4b67f1 | 13,931 | // RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment --check-prefix=CHECK --check-prefix=CHECK-%target-vendor
// REQUIRES: OS=macosx || OS=ios || OS=tvos || OS=watchos || OS=linux-gnu
// UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
// CHECK: @"$s4main9Ancestor1[[UNIQUE_ID_1:[A-Za-z_0-9]+]]LLCyADySSGGMf" =
// CHECK: @"$s4main5Value[[UNIQUE_ID_1]]LLCyAA9Ancestor1ACLLCySSGGMf" = linkonce_odr hidden
// CHECK-apple-SAME: global
// CHECK-unknown-SMAE: constant
// CHECK-SAME: <{
// CHECK-SAME: void (
// CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]LLC*
// CHECK-SAME: )*,
// CHECK-SAME: i8**,
// : [[INT]],
// CHECK-SAME: %swift.type*,
// CHECK-apple-SAME: %swift.opaque*,
// CHECK-apple-SAME: %swift.opaque*,
// CHECK-apple-SAME: [[INT]],
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: i16,
// CHECK-SAME: i16,
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: void (
// CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]LLC*
// CHECK-SAME: )*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]LLC* (
// CHECK-SAME: %swift.opaque*,
// CHECK-SAME: %swift.type*
// CHECK-SAME: )*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: [[INT]]
// CHECK-SAME:}> <{
// CHECK-SAME: void (
// CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]LLC*
// CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]LLCfD
// CHECK-SAME: $sBoWV
// CHECK-apple-SAME: $s4main5Value[[UNIQUE_ID_1]]LLCyAA9Ancestor1ACLLCySSGGMM
// CHECK-unknown-SAME: [[INT]] 0,
// : %swift.type* getelementptr inbounds (
// : %swift.full_heapmetadata,
// : %swift.full_heapmetadata* bitcast (
// : <{
// : void (
// : %T4main9Ancestor1[[UNIQUE_ID_1]]LLC*
// : )*,
// : i8**,
// : [[INT]],
// : %objc_class*,
// : %swift.type*,
// : %swift.opaque*,
// : %swift.opaque*,
// : [[INT]],
// : i32,
// : i32,
// : i32,
// : i16,
// : i16,
// : i32,
// : i32,
// : %swift.type_descriptor*,
// : i8*,
// : %swift.type*,
// : [[INT]],
// : %T4main9Ancestor1[[UNIQUE_ID_1]]LLC* (
// : %swift.opaque*,
// : %swift.type*
// : )*
// : }>* @"$s4main9Ancestor1[[UNIQUE_ID_1]]LLCyADySSGGMf" to %swift.full_heapmetadata*
// : ),
// : i32 0,
// : i32 2
// : ),
// CHECK-apple-SAME: %swift.opaque* @_objc_empty_cache,
// CHECK-apple-SAME: %swift.opaque* null,
// CHECK-apple-SAME: [[INT]] add (
// CHECK-apple-SAME: [[INT]] ptrtoint (
// CHECK-apple-SAME: {
// CHECK-apple-SAME: i32,
// CHECK-apple-SAME: i32,
// CHECK-apple-SAME: i32,
// : i32,
// CHECK-apple-SAME: i8*,
// CHECK-apple-SAME: i8*,
// CHECK-apple-SAME: i8*,
// : i8*,
// CHECK-apple-SAME: {
// CHECK-apple-SAME: i32,
// CHECK-apple-SAME: i32,
// CHECK-apple-SAME: [
// CHECK-apple-SAME: 1 x {
// CHECK-apple-SAME: [[INT]]*,
// CHECK-apple-SAME: i8*,
// CHECK-apple-SAME: i8*,
// CHECK-apple-SAME: i32,
// CHECK-apple-SAME: i32
// CHECK-apple-SAME: }
// CHECK-apple-SAME: ]
// CHECK-apple-SAME: }*,
// CHECK-apple-SAME: i8*,
// CHECK-apple-SAME: i8*
// CHECK-apple-SAME: }* @_DATA__TtC4mainP[[UNIQUE_ID_1]]5Value to [[INT]]
// CHECK-apple-SAME: ),
// CHECK-apple-SAME: [[INT]] 2
// CHECK-apple-SAME: ),
// CHECK-SAME: i32 26,
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 {{(32|16)}},
// CHECK-SAME: i16 {{(7|3)}},
// CHECK-SAME: i16 0,
// CHECK-apple-SAME: i32 {{(136|80)}},
// CHECK-unknown-SAME: i32 112,
// CHECK-apple-SAME: i32 {{(16|8)}},
// : %swift.type_descriptor* bitcast (
// : <{
// : i32,
// : i32,
// : i32,
// : i32,
// : i32,
// : i32,
// : i32,
// : i32,
// : i32,
// : i32,
// : i32,
// : i32,
// : i32,
// : i16,
// : i16,
// : i16,
// : i16,
// : i8,
// : i8,
// : i8,
// : i8,
// : i32,
// : %swift.method_override_descriptor
// : }>* @"$s4main5Value[[UNIQUE_ID_1]]LLCMn" to %swift.type_descriptor*
// : ),
// CHECK-SAME: void (
// CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]LLC*
// CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]LLCfE
// CHECK-SAME: %swift.type* getelementptr inbounds (
// CHECK-SAME: %swift.full_heapmetadata,
// CHECK-SAME: %swift.full_heapmetadata* bitcast (
// CHECK-SAME: <{
// CHECK-SAME: void (
// CHECK-SAME: %T4main9Ancestor1[[UNIQUE_ID_1]]LLC*
// CHECK-SAME: )*,
// CHECK-SAME: i8**,
// : [[INT]],
// CHECK-apple-SAME: %objc_class*,
// CHECK-unknown-SAME: %swift.type*,
// CHECK-apple-SAME: %swift.opaque*,
// CHECK-apple-SAME: %swift.opaque*,
// CHECK-apple-SAME: [[INT]],
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: i16,
// CHECK-SAME: i16,
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: i8*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %T4main9Ancestor1[[UNIQUE_ID_1]]LLC* (
// CHECK-SAME: %swift.opaque*,
// CHECK-SAME: %swift.type*
// CHECK-SAME: )*
// CHECK-SAME: }>* @"$s4main9Ancestor1[[UNIQUE_ID_1]]LLCySSGMf" to %swift.full_heapmetadata*
// CHECK-SAME: ),
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 2
// CHECK-SAME: ),
// CHECK-SAME: [[INT]] {{16|8}},
// CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]LLC* (
// CHECK-SAME: %swift.opaque*,
// CHECK-SAME: %swift.type*
// CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]LLC5firstADyxGx_tcfC
// CHECK-SAME: %swift.type* getelementptr inbounds (
// CHECK-SAME: %swift.full_heapmetadata,
// CHECK-SAME: %swift.full_heapmetadata* bitcast (
// CHECK-SAME: <{
// CHECK-SAME: void (
// CHECK-SAME: %T4main9Ancestor1[[UNIQUE_ID_1]]LLC*
// CHECK-SAME: )*,
// CHECK-SAME: i8**,
// : [[INT]],
// CHECK-apple-SAME: %objc_class*,
// CHECK-unknown-SAME: %swift.type*,
// CHECK-apple-SAME: %swift.opaque*,
// CHECK-apple-SAME: %swift.opaque*,
// CHECK-apple-SAME: [[INT]],
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: i16,
// CHECK-SAME: i16,
// CHECK-SAME: i32,
// CHECK-SAME: i32,
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: i8*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %T4main9Ancestor1[[UNIQUE_ID_1]]LLC* (
// CHECK-SAME: %swift.opaque*,
// CHECK-SAME: %swift.type*
// CHECK-SAME: )*
// CHECK-SAME: }>* @"$s4main9Ancestor1[[UNIQUE_ID_1]]LLCySSGMf" to %swift.full_heapmetadata*
// CHECK-SAME: ),
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 2
// CHECK-SAME: ),
// CHECK-SAME: [[INT]] {{24|12}}
// CHECK-SAME:}>,
// CHECK-SAME:align [[ALIGNMENT]]
fileprivate class Ancestor1<First> {
let first_Ancestor1: First
init(first: First) {
self.first_Ancestor1 = first
}
}
fileprivate class Value<First> : Ancestor1<First> {
let first_Value: First
override init(first: First) {
self.first_Value = first
super.init(first: first)
}
}
@inline(never)
func consume<T>(_ t: T) {
withExtendedLifetime(t) { t in
}
}
func doit() {
consume( Value(first: Ancestor1(first: "13")) )
}
doit()
// CHECK-LABEL: define hidden swiftcc void @"$s4main4doityyF"()
// CHECK: call swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]LLCyAA9Ancestor1ACLLCySSGGMb"
// CHECK: }
// CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main9Ancestor1[[UNIQUE_ID_1]]LLCySSGMb"
// CHECK: ; Function Attrs: noinline nounwind readnone
// CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]LLCyAA9Ancestor1ACLLCySSGGMb"([[INT]] {{%[0-9]+}}) {{#[0-9]+}} {
// CHECK-NEXT: entry:
// CHECK-unknown: [[ARGUMENT_CLASS_METADATA:%[0-9]+]] = call swiftcc %swift.metadata_response @"$s4main9Ancestor1[[UNIQUE_ID_1]]LLCySSGMb"([[INT]] 0)
// CHECK-unknown: [[SUPER_CLASS_METADATA:%[0-9]+]] = call swiftcc %swift.metadata_response @"$s4main9Ancestor1[[UNIQUE_ID_1]]LLCyADySSGGMb"([[INT]] 0)
// CHECK-unknown: ret
// CHECK-apple: [[THIS_CLASS_METADATA:%[0-9]+]] = call %objc_class* @objc_opt_self(
// : %objc_class* bitcast (
// : %swift.type* getelementptr inbounds (
// : %swift.full_heapmetadata,
// : %swift.full_heapmetadata* bitcast (
// : <{
// : void (
// : %T4main5Value[[UNIQUE_ID_1]]LLC*
// : )*,
// : i8**,
// : [[INT]],
// : %swift.type*,
// : %swift.opaque*,
// : %swift.opaque*,
// : [[INT]],
// : i32,
// : i32,
// : i32,
// : i16,
// : i16,
// : i32,
// : i32,
// : %swift.type_descriptor*,
// : void (
// : %T4main5Value[[UNIQUE_ID_1]]LLC*
// : )*,
// : %swift.type*,
// : [[INT]],
// : %T4main5Value[[UNIQUE_ID_1]]LLC* (
// : %swift.opaque*,
// : %swift.type*
// : )*,
// : %swift.type*,
// : [[INT]]
// CHECK-apple: }>* @"$s4main5Value[[UNIQUE_ID_1]]LLCyAA9Ancestor1ACLLCySSGGMf"
// : to %swift.full_heapmetadata*
// : ),
// : i32 0,
// : i32 2
// : ) to %objc_class*
// : )
// CHECK-apple: )
// CHECK-apple: [[THIS_TYPE_METADATA:%[0-9]+]] = bitcast %objc_class* [[THIS_CLASS_METADATA]] to %swift.type*
// CHECK-apple: [[ARGUMENT_CLASS_METADATA:%[0-9]+]] = call swiftcc %swift.metadata_response @"$s4main9Ancestor1[[UNIQUE_ID_1]]LLCySSGMb"([[INT]] 0)
// CHECK-apple: [[SUPER_CLASS_METADATA:%[0-9]+]] = call swiftcc %swift.metadata_response @"$s4main9Ancestor1[[UNIQUE_ID_1]]LLCyADySSGGMb"([[INT]] 0)
// CHECK-apple: [[RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response undef, %swift.type* [[THIS_TYPE_METADATA]], 0
// CHECK-apple: [[COMPLETE_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response [[RESPONSE]], [[INT]] 0, 1
// CHECK-apple: ret %swift.metadata_response [[COMPLETE_RESPONSE]]
// CHECK: }
// CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main9Ancestor133_51697B6EAB71ECF43599389041BB2421LLCyADySSGGMb"([[INT]] {{%[0-9]+}})
| 43.130031 | 214 | 0.430551 |
e056516f4d89b73df5adcea6ea2668098e2d13f4 | 523 | import UIKit
@IBDesignable public class DesignableImageView: SpringImageView {
@IBInspectable public var borderColor: UIColor = UIColor.clear {
didSet {
layer.borderColor = borderColor.cgColor
}
}
@IBInspectable public var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
@IBInspectable public var cornerRadius: CGFloat = 0 {
didSet {
layer.cornerRadius = cornerRadius
}
}
}
| 21.791667 | 68 | 0.594646 |
ac05d8ecd9b5e004cb12fa0ef14bc98bcb06599f | 1,231 | //
// ACTIRecord.swift
// GameEstate
//
// Created by Sky Morey on 5/28/18.
// Copyright © 2018 Sky Morey. All rights reserved.
//
public class ACTIRecord: Record, IHaveEDID, IHaveMODL {
public override var description: String { return "ACTI: \(EDID)" }
public var EDID: STRVField = STRVField_empty // Editor ID
public var MODL: MODLGroup? = nil // Model Name
public var FULL: STRVField! // Item Name
public var SCRI: FMIDField<SCPTRecord>? = nil // Script (Optional)
// TES4
public var SNAM: FMIDField<SOUNRecord>? = nil // Sound (Optional)
override func createField(_ r: BinaryReader, for format: GameFormatId, type: String, dataSize: Int) -> Bool {
switch type {
case "EDID",
"NAME": EDID = r.readSTRV(dataSize)
case "MODL": MODL = MODLGroup(r, dataSize)
case "MODB": MODL!.MODBField(r, dataSize)
case "MODT": MODL!.MODTField(r, dataSize)
case "FULL",
"FNAM": FULL = r.readSTRV(dataSize)
case "SCRI": SCRI = FMIDField<SCPTRecord>(r, dataSize)
case "SNAM": SNAM = FMIDField<SOUNRecord>(r, dataSize)
default: return false
}
return true
}
}
| 36.205882 | 114 | 0.606824 |
871d676b44074d06cc5d66823002809f0b7ca79b | 17,155 | import AppKit
import Foundation
private class IconColorsFileVector: NSBox {
public var box1Fill = #colorLiteral(red: 0.933333333333, green: 0.933333333333, blue: 0.933333333333, alpha: 1)
public var box1Stroke = #colorLiteral(red: 0.549019607843, green: 0.549019607843, blue: 0.549019607843, alpha: 1)
public var box2Fill = #colorLiteral(red: 0.933333333333, green: 0.933333333333, blue: 0.933333333333, alpha: 1)
public var box2Stroke = #colorLiteral(red: 0.549019607843, green: 0.549019607843, blue: 0.549019607843, alpha: 1)
public var box3Fill = #colorLiteral(red: 0.933333333333, green: 0.933333333333, blue: 0.933333333333, alpha: 1)
public var box3Stroke = #colorLiteral(red: 0.549019607843, green: 0.549019607843, blue: 0.549019607843, alpha: 1)
public var box4Fill = #colorLiteral(red: 0.933333333333, green: 0.933333333333, blue: 0.933333333333, alpha: 1)
public var box4Stroke = #colorLiteral(red: 0.549019607843, green: 0.549019607843, blue: 0.549019607843, alpha: 1)
public var foldFill = #colorLiteral(red: 0.933333333333, green: 0.933333333333, blue: 0.933333333333, alpha: 1)
public var foldStroke = #colorLiteral(red: 0.549019607843, green: 0.549019607843, blue: 0.549019607843, alpha: 1)
public var outlineFill = #colorLiteral(red: 0.847058823529, green: 0.847058823529, blue: 0.847058823529, alpha: 1)
public var outlineStroke = #colorLiteral(red: 0.549019607843, green: 0.549019607843, blue: 0.549019607843, alpha: 1)
override var isFlipped: Bool {
return true
}
var resizingMode = CGSize.ResizingMode.scaleAspectFill {
didSet {
if resizingMode != oldValue {
needsDisplay = true
}
}
}
override func draw(_ dirtyRect: CGRect) {
super.draw(dirtyRect)
let viewBox = CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: 24, height: 24))
let croppedRect = viewBox.size.resized(within: bounds.size, usingResizingMode: resizingMode)
let scale = croppedRect.width / viewBox.width
func transform(point: CGPoint) -> CGPoint {
return CGPoint(x: point.x * scale + croppedRect.minX, y: point.y * scale + croppedRect.minY)
}
let outline = NSBezierPath()
outline.move(to: transform(point: CGPoint(x: 5.5, y: 2.5)))
outline.line(to: transform(point: CGPoint(x: 12.6715729, y: 2.5)))
outline.curve(
to: transform(point: CGPoint(x: 14.0857864, y: 3.08578644)),
controlPoint1: transform(point: CGPoint(x: 13.2020059, y: 2.5)),
controlPoint2: transform(point: CGPoint(x: 13.7107137, y: 2.71071368)))
outline.line(to: transform(point: CGPoint(x: 17.9142136, y: 6.91421356)))
outline.curve(
to: transform(point: CGPoint(x: 18.5, y: 8.32842712)),
controlPoint1: transform(point: CGPoint(x: 18.2892863, y: 7.28928632)),
controlPoint2: transform(point: CGPoint(x: 18.5, y: 7.79799415)))
outline.line(to: transform(point: CGPoint(x: 18.5, y: 20.5)))
outline.curve(
to: transform(point: CGPoint(x: 17.5, y: 21.5)),
controlPoint1: transform(point: CGPoint(x: 18.5, y: 21.0522847)),
controlPoint2: transform(point: CGPoint(x: 18.0522847, y: 21.5)))
outline.line(to: transform(point: CGPoint(x: 5.5, y: 21.5)))
outline.curve(
to: transform(point: CGPoint(x: 4.5, y: 20.5)),
controlPoint1: transform(point: CGPoint(x: 4.94771525, y: 21.5)),
controlPoint2: transform(point: CGPoint(x: 4.5, y: 21.0522847)))
outline.line(to: transform(point: CGPoint(x: 4.5, y: 3.5)))
outline.curve(
to: transform(point: CGPoint(x: 5.5, y: 2.5)),
controlPoint1: transform(point: CGPoint(x: 4.5, y: 2.94771525)),
controlPoint2: transform(point: CGPoint(x: 4.94771525, y: 2.5)))
outline.close()
outlineFill.setFill()
outlineStroke.setStroke()
outline.fill()
outline.lineWidth = 1 * scale
outline.lineCapStyle = .buttLineCapStyle
outline.stroke()
let highlight = NSBezierPath()
highlight.move(to: transform(point: CGPoint(x: 5.5, y: 20.5)))
highlight.line(to: transform(point: CGPoint(x: 17.5, y: 20.5)))
#colorLiteral(red: 1, green: 1, blue: 1, alpha: 0.2).setStroke()
highlight.lineWidth = 1 * scale
highlight.lineCapStyle = .squareLineCapStyle
highlight.stroke()
let fold = NSBezierPath()
fold.move(to: transform(point: CGPoint(x: 17.0857864, y: 8.5)))
fold.line(to: transform(point: CGPoint(x: 13.5, y: 8.5)))
fold.curve(
to: transform(point: CGPoint(x: 12.5, y: 7.5)),
controlPoint1: transform(point: CGPoint(x: 12.9477153, y: 8.5)),
controlPoint2: transform(point: CGPoint(x: 12.5, y: 8.05228475)))
fold.line(to: transform(point: CGPoint(x: 12.5, y: 3.91421356)))
fold.curve(
to: transform(point: CGPoint(x: 13.5, y: 2.91421356)),
controlPoint1: transform(point: CGPoint(x: 12.5, y: 3.36192881)),
controlPoint2: transform(point: CGPoint(x: 12.9477153, y: 2.91421356)))
fold.curve(
to: transform(point: CGPoint(x: 14.2071068, y: 3.20710678)),
controlPoint1: transform(point: CGPoint(x: 13.7652165, y: 2.91421356)),
controlPoint2: transform(point: CGPoint(x: 14.0195704, y: 3.0195704)))
fold.line(to: transform(point: CGPoint(x: 17.7928932, y: 6.79289322)))
fold.curve(
to: transform(point: CGPoint(x: 17.7928932, y: 8.20710678)),
controlPoint1: transform(point: CGPoint(x: 18.1834175, y: 7.18341751)),
controlPoint2: transform(point: CGPoint(x: 18.1834175, y: 7.81658249)))
fold.curve(
to: transform(point: CGPoint(x: 17.0857864, y: 8.5)),
controlPoint1: transform(point: CGPoint(x: 17.6053568, y: 8.39464316)),
controlPoint2: transform(point: CGPoint(x: 17.3510029, y: 8.5)))
fold.close()
foldFill.setFill()
foldStroke.setStroke()
fold.fill()
fold.lineWidth = 1 * scale
fold.lineCapStyle = .buttLineCapStyle
fold.stroke()
let box1 = NSBezierPath()
box1.move(to: transform(point: CGPoint(x: 8.5, y: 10.5)))
box1.line(to: transform(point: CGPoint(x: 9.5, y: 10.5)))
box1.curve(
to: transform(point: CGPoint(x: 10.5, y: 11.5)),
controlPoint1: transform(point: CGPoint(x: 10.0522847498, y: 10.5)),
controlPoint2: transform(point: CGPoint(x: 10.5, y: 10.9477152502)))
box1.line(to: transform(point: CGPoint(x: 10.5, y: 12.5)))
box1.curve(
to: transform(point: CGPoint(x: 9.5, y: 13.5)),
controlPoint1: transform(point: CGPoint(x: 10.5, y: 13.0522847498)),
controlPoint2: transform(point: CGPoint(x: 10.0522847498, y: 13.5)))
box1.line(to: transform(point: CGPoint(x: 8.5, y: 13.5)))
box1.curve(
to: transform(point: CGPoint(x: 7.5, y: 12.5)),
controlPoint1: transform(point: CGPoint(x: 7.94771525017, y: 13.5)),
controlPoint2: transform(point: CGPoint(x: 7.5, y: 13.0522847498)))
box1.line(to: transform(point: CGPoint(x: 7.5, y: 11.5)))
box1.curve(
to: transform(point: CGPoint(x: 8.5, y: 10.5)),
controlPoint1: transform(point: CGPoint(x: 7.5, y: 10.9477152502)),
controlPoint2: transform(point: CGPoint(x: 7.94771525017, y: 10.5)))
box1.close()
box1Fill.setFill()
box1Stroke.setStroke()
box1.fill()
box1.lineWidth = 1 * scale
box1.lineCapStyle = .buttLineCapStyle
box1.stroke()
let box2 = NSBezierPath()
box2.move(to: transform(point: CGPoint(x: 13.5, y: 10.5)))
box2.line(to: transform(point: CGPoint(x: 14.5, y: 10.5)))
box2.curve(
to: transform(point: CGPoint(x: 15.5, y: 11.5)),
controlPoint1: transform(point: CGPoint(x: 15.0522847498, y: 10.5)),
controlPoint2: transform(point: CGPoint(x: 15.5, y: 10.9477152502)))
box2.line(to: transform(point: CGPoint(x: 15.5, y: 12.5)))
box2.curve(
to: transform(point: CGPoint(x: 14.5, y: 13.5)),
controlPoint1: transform(point: CGPoint(x: 15.5, y: 13.0522847498)),
controlPoint2: transform(point: CGPoint(x: 15.0522847498, y: 13.5)))
box2.line(to: transform(point: CGPoint(x: 13.5, y: 13.5)))
box2.curve(
to: transform(point: CGPoint(x: 12.5, y: 12.5)),
controlPoint1: transform(point: CGPoint(x: 12.9477152502, y: 13.5)),
controlPoint2: transform(point: CGPoint(x: 12.5, y: 13.0522847498)))
box2.line(to: transform(point: CGPoint(x: 12.5, y: 11.5)))
box2.curve(
to: transform(point: CGPoint(x: 13.5, y: 10.5)),
controlPoint1: transform(point: CGPoint(x: 12.5, y: 10.9477152502)),
controlPoint2: transform(point: CGPoint(x: 12.9477152502, y: 10.5)))
box2.close()
box2Fill.setFill()
box2Stroke.setStroke()
box2.fill()
box2.lineWidth = 1 * scale
box2.lineCapStyle = .buttLineCapStyle
box2.stroke()
let box3 = NSBezierPath()
box3.move(to: transform(point: CGPoint(x: 8.5, y: 15.5)))
box3.line(to: transform(point: CGPoint(x: 9.5, y: 15.5)))
box3.curve(
to: transform(point: CGPoint(x: 10.5, y: 16.5)),
controlPoint1: transform(point: CGPoint(x: 10.0522847498, y: 15.5)),
controlPoint2: transform(point: CGPoint(x: 10.5, y: 15.9477152502)))
box3.line(to: transform(point: CGPoint(x: 10.5, y: 17.5)))
box3.curve(
to: transform(point: CGPoint(x: 9.5, y: 18.5)),
controlPoint1: transform(point: CGPoint(x: 10.5, y: 18.0522847498)),
controlPoint2: transform(point: CGPoint(x: 10.0522847498, y: 18.5)))
box3.line(to: transform(point: CGPoint(x: 8.5, y: 18.5)))
box3.curve(
to: transform(point: CGPoint(x: 7.5, y: 17.5)),
controlPoint1: transform(point: CGPoint(x: 7.94771525017, y: 18.5)),
controlPoint2: transform(point: CGPoint(x: 7.5, y: 18.0522847498)))
box3.line(to: transform(point: CGPoint(x: 7.5, y: 16.5)))
box3.curve(
to: transform(point: CGPoint(x: 8.5, y: 15.5)),
controlPoint1: transform(point: CGPoint(x: 7.5, y: 15.9477152502)),
controlPoint2: transform(point: CGPoint(x: 7.94771525017, y: 15.5)))
box3.close()
box3Fill.setFill()
box3Stroke.setStroke()
box3.fill()
box3.lineWidth = 1 * scale
box3.lineCapStyle = .buttLineCapStyle
box3.stroke()
let box4 = NSBezierPath()
box4.move(to: transform(point: CGPoint(x: 13.5, y: 15.5)))
box4.line(to: transform(point: CGPoint(x: 14.5, y: 15.5)))
box4.curve(
to: transform(point: CGPoint(x: 15.5, y: 16.5)),
controlPoint1: transform(point: CGPoint(x: 15.0522847498, y: 15.5)),
controlPoint2: transform(point: CGPoint(x: 15.5, y: 15.9477152502)))
box4.line(to: transform(point: CGPoint(x: 15.5, y: 17.5)))
box4.curve(
to: transform(point: CGPoint(x: 14.5, y: 18.5)),
controlPoint1: transform(point: CGPoint(x: 15.5, y: 18.0522847498)),
controlPoint2: transform(point: CGPoint(x: 15.0522847498, y: 18.5)))
box4.line(to: transform(point: CGPoint(x: 13.5, y: 18.5)))
box4.curve(
to: transform(point: CGPoint(x: 12.5, y: 17.5)),
controlPoint1: transform(point: CGPoint(x: 12.9477152502, y: 18.5)),
controlPoint2: transform(point: CGPoint(x: 12.5, y: 18.0522847498)))
box4.line(to: transform(point: CGPoint(x: 12.5, y: 16.5)))
box4.curve(
to: transform(point: CGPoint(x: 13.5, y: 15.5)),
controlPoint1: transform(point: CGPoint(x: 12.5, y: 15.9477152502)),
controlPoint2: transform(point: CGPoint(x: 12.9477152502, y: 15.5)))
box4.close()
box4Fill.setFill()
box4Stroke.setStroke()
box4.fill()
box4.lineWidth = 1 * scale
box4.lineCapStyle = .buttLineCapStyle
box4.stroke()
}
}
// MARK: - ColorsFileIcon
public class ColorsFileIcon: NSBox {
// MARK: Lifecycle
public init(_ parameters: Parameters) {
self.parameters = parameters
super.init(frame: .zero)
setUpViews()
setUpConstraints()
update()
}
public convenience init(selected: Bool) {
self.init(Parameters(selected: selected))
}
public convenience init() {
self.init(Parameters())
}
public required init?(coder aDecoder: NSCoder) {
self.parameters = Parameters()
super.init(coder: aDecoder)
setUpViews()
setUpConstraints()
update()
}
// MARK: Public
public var selected: Bool {
get { return parameters.selected }
set {
if parameters.selected != newValue {
parameters.selected = newValue
}
}
}
public var parameters: Parameters {
didSet {
if parameters != oldValue {
update()
}
}
}
// MARK: Private
private var vectorGraphicView = IconColorsFileVector()
private func setUpViews() {
boxType = .custom
borderType = .noBorder
contentViewMargins = .zero
vectorGraphicView.boxType = .custom
vectorGraphicView.borderType = .noBorder
vectorGraphicView.contentViewMargins = .zero
addSubview(vectorGraphicView)
}
private func setUpConstraints() {
translatesAutoresizingMaskIntoConstraints = false
vectorGraphicView.translatesAutoresizingMaskIntoConstraints = false
let vectorGraphicViewHeightAnchorParentConstraint = vectorGraphicView
.heightAnchor
.constraint(lessThanOrEqualTo: heightAnchor)
let vectorGraphicViewLeadingAnchorConstraint = vectorGraphicView.leadingAnchor.constraint(equalTo: leadingAnchor)
let vectorGraphicViewCenterYAnchorConstraint = vectorGraphicView.centerYAnchor.constraint(equalTo: centerYAnchor)
let vectorGraphicViewHeightAnchorConstraint = vectorGraphicView.heightAnchor.constraint(equalToConstant: 24)
let vectorGraphicViewWidthAnchorConstraint = vectorGraphicView.widthAnchor.constraint(equalToConstant: 24)
vectorGraphicViewHeightAnchorParentConstraint.priority = NSLayoutConstraint.Priority.defaultLow
NSLayoutConstraint.activate([
vectorGraphicViewHeightAnchorParentConstraint,
vectorGraphicViewLeadingAnchorConstraint,
vectorGraphicViewCenterYAnchorConstraint,
vectorGraphicViewHeightAnchorConstraint,
vectorGraphicViewWidthAnchorConstraint
])
}
private func update() {
vectorGraphicView.box1Fill = #colorLiteral(red: 0.933333333333, green: 0.933333333333, blue: 0.933333333333, alpha: 1)
vectorGraphicView.box1Stroke = #colorLiteral(red: 0.549019607843, green: 0.549019607843, blue: 0.549019607843, alpha: 1)
vectorGraphicView.box2Fill = #colorLiteral(red: 0.933333333333, green: 0.933333333333, blue: 0.933333333333, alpha: 1)
vectorGraphicView.box2Stroke = #colorLiteral(red: 0.549019607843, green: 0.549019607843, blue: 0.549019607843, alpha: 1)
vectorGraphicView.box3Fill = #colorLiteral(red: 0.933333333333, green: 0.933333333333, blue: 0.933333333333, alpha: 1)
vectorGraphicView.box3Stroke = #colorLiteral(red: 0.549019607843, green: 0.549019607843, blue: 0.549019607843, alpha: 1)
vectorGraphicView.box4Fill = #colorLiteral(red: 0.933333333333, green: 0.933333333333, blue: 0.933333333333, alpha: 1)
vectorGraphicView.box4Stroke = #colorLiteral(red: 0.549019607843, green: 0.549019607843, blue: 0.549019607843, alpha: 1)
vectorGraphicView.foldFill = #colorLiteral(red: 0.933333333333, green: 0.933333333333, blue: 0.933333333333, alpha: 1)
vectorGraphicView.foldStroke = #colorLiteral(red: 0.549019607843, green: 0.549019607843, blue: 0.549019607843, alpha: 1)
vectorGraphicView.outlineFill = #colorLiteral(red: 0.847058823529, green: 0.847058823529, blue: 0.847058823529, alpha: 1)
vectorGraphicView.outlineStroke = #colorLiteral(red: 0.549019607843, green: 0.549019607843, blue: 0.549019607843, alpha: 1)
if selected {
vectorGraphicView.outlineStroke = Colors.selectedIconStroke
vectorGraphicView.outlineFill = Colors.selectedIcon
vectorGraphicView.foldStroke = Colors.selectedIconStroke
vectorGraphicView.foldFill = Colors.selectedIcon
vectorGraphicView.box1Stroke = Colors.selectedIconStroke
vectorGraphicView.box2Stroke = Colors.selectedIconStroke
vectorGraphicView.box3Stroke = Colors.selectedIconStroke
vectorGraphicView.box4Stroke = Colors.selectedIconStroke
vectorGraphicView.box1Fill = Colors.selectedIcon
vectorGraphicView.box2Fill = Colors.selectedIcon
vectorGraphicView.box3Fill = Colors.selectedIcon
vectorGraphicView.box4Fill = Colors.selectedIcon
}
vectorGraphicView.needsDisplay = true
}
}
// MARK: - Parameters
extension ColorsFileIcon {
public struct Parameters: Equatable {
public var selected: Bool
public init(selected: Bool) {
self.selected = selected
}
public init() {
self.init(selected: false)
}
public static func ==(lhs: Parameters, rhs: Parameters) -> Bool {
return lhs.selected == rhs.selected
}
}
}
// MARK: - Model
extension ColorsFileIcon {
public struct Model: LonaViewModel, Equatable {
public var id: String?
public var parameters: Parameters
public var type: String {
return "ColorsFileIcon"
}
public init(id: String? = nil, parameters: Parameters) {
self.id = id
self.parameters = parameters
}
public init(_ parameters: Parameters) {
self.parameters = parameters
}
public init(selected: Bool) {
self.init(Parameters(selected: selected))
}
public init() {
self.init(selected: false)
}
}
}
| 42.462871 | 127 | 0.683358 |
38ef95806588b86ea9e9dab82005873f927eef86 | 144 | //
// ButtonStyles.swift
// CurvedRectangleShapeDemo
//
// Created by CypherPoet on 2/14/21.
// ✌️
//
import Foundation
enum ButtonStyles {}
| 11.076923 | 36 | 0.6875 |
1df910ec8efe260311f175a77f32efc501ae9ee5 | 2,099 | //
// UIColor+Extensions.swift
// JMForm
//
// Created by Jakob Mikkelsen on 25/07/2020.
// Copyright © 2020 Codement. All rights reserved.
//
import UIKit
extension UIColor {
convenience init(red: Int, green: Int, blue: Int) {
assert(red >= 0 && red <= 255, "Invalid red component")
assert(green >= 0 && green <= 255, "Invalid green component")
assert(blue >= 0 && blue <= 255, "Invalid blue component")
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
}
convenience init(hex: Int) {
self.init(hex: hex, a: 1.0)
}
convenience init(hex: Int, a: CGFloat) {
self.init(r: (hex >> 16) & 0xff, g: (hex >> 8) & 0xff, b: hex & 0xff, a: a)
}
convenience init(r: Int, g: Int, b: Int) {
self.init(r: r, g: g, b: b, a: 1.0)
}
convenience init(r: Int, g: Int, b: Int, a: CGFloat) {
self.init(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: a)
}
convenience public init?(hexString: String?) {
guard var hexString = hexString else { return nil }
if hexString.contains("#") {
hexString.removeFirst()
}
guard let hex = hexString.hex else {
self.init(hex: 000000)
return
}
self.init(hex: hex)
}
convenience init?(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let hexString = try container.decode(String.self)
self.init(hexString: hexString)
}
public func toHexString() -> String {
var r:CGFloat = 0
var g:CGFloat = 0
var b:CGFloat = 0
var a:CGFloat = 0
getRed(&r, green: &g, blue: &b, alpha: &a)
let rgb:Int = (Int)(r*255)<<16 | (Int)(g*255)<<8 | (Int)(b*255)<<0
return String(format:"#%06x", rgb)
}
}
extension String {
var hex: Int? {
return Int(self, radix: 16)
}
}
| 27.618421 | 116 | 0.533111 |
e8efd9c2d1fd2280dadeb8da8c13e10d04061c43 | 437 | //
// ModelLayoutItem.swift
// FastAdapter
//
// Created by Fabian Terhorst on 19.07.18.
// Copyright © 2018 everHome. All rights reserved.
//
open class ModelLayoutItem<Model>: AbstractModelLayoutItem {
public var model: Model {
get {
return _model as! Model
}
set {
_model = newValue
}
}
public init(model: Model) {
super.init(model: model)
}
}
| 19 | 60 | 0.569794 |
4ac3216f761ca2653ca1e42882ab35c1768dac71 | 1,215 | //
// ShareSheetVIew.swift
// artbum
//
// Created by shreyas gupta on 01/08/20.
// Copyright © 2020 shreyas gupta. All rights reserved.
//
import SwiftUI
import UIKit
struct ShareSheetView: UIViewControllerRepresentable{
typealias Callback = (_ activityType: UIActivity.ActivityType?, _ completed: Bool, _ returnedItems: [Any]?, _ error: Error?) -> Void
let activityItems: [Any]
let applicationActivities: [UIActivity]? = nil
let excludedActivityTypes: [UIActivity.ActivityType]? = [.assignToContact, .print]
let callback: Callback? = nil
func makeUIViewController(context: Context) -> some UIViewController {
let controller = UIActivityViewController(activityItems: activityItems, applicationActivities: applicationActivities)
controller.excludedActivityTypes = excludedActivityTypes
controller.completionWithItemsHandler = callback
return controller
}
func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {
//TO-DO
}
}
struct ShareSheetVIew_Previews: PreviewProvider {
static var previews: some View {
ShareSheetView(activityItems: ["A String" as NSString])
}
}
| 31.973684 | 136 | 0.72428 |
5b42399b930a2940a85d611dcf4d48bde6ca77df | 221 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
var b {
struct c<T where g: AnyObject
if true {
[c{
| 24.555556 | 87 | 0.746606 |
752b4900a0da6d9071427dd237292f82774d2aea | 114 | import XCTest
import NavKitTests
var tests = [XCTestCaseEntry]()
tests += NavKitTests.allTests()
XCTMain(tests)
| 14.25 | 31 | 0.77193 |
11b6b7c4b2b83233fe284211cd2e40d6ef2ac7f8 | 54,698 | //
// JKBCrypt.swift
// JKBCrypt
//
// Created by Joe Kramer on 6/19/2015.
// Copyright (c) 2015 Joe Kramer. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ----------------------------------------------------------------------
//
// This Swift port is based on the Objective-C port by Jay Fuerstenberg.
// https://github.com/jayfuerstenberg/JFCommon
//
// ----------------------------------------------------------------------
//
// The Objective-C port is based on the original Java implementation by Damien Miller
// found here: http://www.mindrot.org/projects/jBCrypt/
// In accordance with the Damien Miller's request, his original copyright covering
// his Java implementation is included here:
//
// Copyright (c) 2006 Damien Miller <[email protected]>
//
// Permission to use, copy, modify, and distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
import Foundation
// MARK: - Class Extensions
extension String {
subscript (i: Int) -> Character {
return self[self.startIndex.advancedBy(i)]
}
subscript (i: Int) -> String {
return String(self[i] as Character)
}
subscript (r: Range<Int>) -> String {
return substringWithRange(startIndex.advancedBy(r.startIndex) ..< startIndex.advancedBy(r.endIndex))
}
}
extension Character {
func utf16Value() -> UInt16 {
for s in String(self).utf16 {
return s
}
return 0
}
}
// BCrypt parameters
let GENSALT_DEFAULT_LOG2_ROUNDS : Int = 10
let BCRYPT_SALT_LEN : Int = 16
// Blowfish parameters
let BLOWFISH_NUM_ROUNDS : Int = 16
// Initial contents of key schedule
let P_orig : [Int32] = [
Int32(bitPattern: 0x243f6a88), Int32(bitPattern: 0x85a308d3), Int32(bitPattern: 0x13198a2e), Int32(bitPattern: 0x03707344),
Int32(bitPattern: 0xa4093822), Int32(bitPattern: 0x299f31d0), Int32(bitPattern: 0x082efa98), Int32(bitPattern: 0xec4e6c89),
Int32(bitPattern: 0x452821e6), Int32(bitPattern: 0x38d01377), Int32(bitPattern: 0xbe5466cf), Int32(bitPattern: 0x34e90c6c),
Int32(bitPattern: 0xc0ac29b7), Int32(bitPattern: 0xc97c50dd), Int32(bitPattern: 0x3f84d5b5), Int32(bitPattern: 0xb5470917),
Int32(bitPattern: 0x9216d5d9), Int32(bitPattern: 0x8979fb1b)
]
let S_orig : [Int32] = [
Int32(bitPattern: 0xd1310ba6), Int32(bitPattern: 0x98dfb5ac), Int32(bitPattern: 0x2ffd72db), Int32(bitPattern: 0xd01adfb7),
Int32(bitPattern: 0xb8e1afed), Int32(bitPattern: 0x6a267e96), Int32(bitPattern: 0xba7c9045), Int32(bitPattern: 0xf12c7f99),
Int32(bitPattern: 0x24a19947), Int32(bitPattern: 0xb3916cf7), Int32(bitPattern: 0x0801f2e2), Int32(bitPattern: 0x858efc16),
Int32(bitPattern: 0x636920d8), Int32(bitPattern: 0x71574e69), Int32(bitPattern: 0xa458fea3), Int32(bitPattern: 0xf4933d7e),
Int32(bitPattern: 0x0d95748f), Int32(bitPattern: 0x728eb658), Int32(bitPattern: 0x718bcd58), Int32(bitPattern: 0x82154aee),
Int32(bitPattern: 0x7b54a41d), Int32(bitPattern: 0xc25a59b5), Int32(bitPattern: 0x9c30d539), Int32(bitPattern: 0x2af26013),
Int32(bitPattern: 0xc5d1b023), Int32(bitPattern: 0x286085f0), Int32(bitPattern: 0xca417918), Int32(bitPattern: 0xb8db38ef),
Int32(bitPattern: 0x8e79dcb0), Int32(bitPattern: 0x603a180e), Int32(bitPattern: 0x6c9e0e8b), Int32(bitPattern: 0xb01e8a3e),
Int32(bitPattern: 0xd71577c1), Int32(bitPattern: 0xbd314b27), Int32(bitPattern: 0x78af2fda), Int32(bitPattern: 0x55605c60),
Int32(bitPattern: 0xe65525f3), Int32(bitPattern: 0xaa55ab94), Int32(bitPattern: 0x57489862), Int32(bitPattern: 0x63e81440),
Int32(bitPattern: 0x55ca396a), Int32(bitPattern: 0x2aab10b6), Int32(bitPattern: 0xb4cc5c34), Int32(bitPattern: 0x1141e8ce),
Int32(bitPattern: 0xa15486af), Int32(bitPattern: 0x7c72e993), Int32(bitPattern: 0xb3ee1411), Int32(bitPattern: 0x636fbc2a),
Int32(bitPattern: 0x2ba9c55d), Int32(bitPattern: 0x741831f6), Int32(bitPattern: 0xce5c3e16), Int32(bitPattern: 0x9b87931e),
Int32(bitPattern: 0xafd6ba33), Int32(bitPattern: 0x6c24cf5c), Int32(bitPattern: 0x7a325381), Int32(bitPattern: 0x28958677),
Int32(bitPattern: 0x3b8f4898), Int32(bitPattern: 0x6b4bb9af), Int32(bitPattern: 0xc4bfe81b), Int32(bitPattern: 0x66282193),
Int32(bitPattern: 0x61d809cc), Int32(bitPattern: 0xfb21a991), Int32(bitPattern: 0x487cac60), Int32(bitPattern: 0x5dec8032),
Int32(bitPattern: 0xef845d5d), Int32(bitPattern: 0xe98575b1), Int32(bitPattern: 0xdc262302), Int32(bitPattern: 0xeb651b88),
Int32(bitPattern: 0x23893e81), Int32(bitPattern: 0xd396acc5), Int32(bitPattern: 0x0f6d6ff3), Int32(bitPattern: 0x83f44239),
Int32(bitPattern: 0x2e0b4482), Int32(bitPattern: 0xa4842004), Int32(bitPattern: 0x69c8f04a), Int32(bitPattern: 0x9e1f9b5e),
Int32(bitPattern: 0x21c66842), Int32(bitPattern: 0xf6e96c9a), Int32(bitPattern: 0x670c9c61), Int32(bitPattern: 0xabd388f0),
Int32(bitPattern: 0x6a51a0d2), Int32(bitPattern: 0xd8542f68), Int32(bitPattern: 0x960fa728), Int32(bitPattern: 0xab5133a3),
Int32(bitPattern: 0x6eef0b6c), Int32(bitPattern: 0x137a3be4), Int32(bitPattern: 0xba3bf050), Int32(bitPattern: 0x7efb2a98),
Int32(bitPattern: 0xa1f1651d), Int32(bitPattern: 0x39af0176), Int32(bitPattern: 0x66ca593e), Int32(bitPattern: 0x82430e88),
Int32(bitPattern: 0x8cee8619), Int32(bitPattern: 0x456f9fb4), Int32(bitPattern: 0x7d84a5c3), Int32(bitPattern: 0x3b8b5ebe),
Int32(bitPattern: 0xe06f75d8), Int32(bitPattern: 0x85c12073), Int32(bitPattern: 0x401a449f), Int32(bitPattern: 0x56c16aa6),
Int32(bitPattern: 0x4ed3aa62), Int32(bitPattern: 0x363f7706), Int32(bitPattern: 0x1bfedf72), Int32(bitPattern: 0x429b023d),
Int32(bitPattern: 0x37d0d724), Int32(bitPattern: 0xd00a1248), Int32(bitPattern: 0xdb0fead3), Int32(bitPattern: 0x49f1c09b),
Int32(bitPattern: 0x075372c9), Int32(bitPattern: 0x80991b7b), Int32(bitPattern: 0x25d479d8), Int32(bitPattern: 0xf6e8def7),
Int32(bitPattern: 0xe3fe501a), Int32(bitPattern: 0xb6794c3b), Int32(bitPattern: 0x976ce0bd), Int32(bitPattern: 0x04c006ba),
Int32(bitPattern: 0xc1a94fb6), Int32(bitPattern: 0x409f60c4), Int32(bitPattern: 0x5e5c9ec2), Int32(bitPattern: 0x196a2463),
Int32(bitPattern: 0x68fb6faf), Int32(bitPattern: 0x3e6c53b5), Int32(bitPattern: 0x1339b2eb), Int32(bitPattern: 0x3b52ec6f),
Int32(bitPattern: 0x6dfc511f), Int32(bitPattern: 0x9b30952c), Int32(bitPattern: 0xcc814544), Int32(bitPattern: 0xaf5ebd09),
Int32(bitPattern: 0xbee3d004), Int32(bitPattern: 0xde334afd), Int32(bitPattern: 0x660f2807), Int32(bitPattern: 0x192e4bb3),
Int32(bitPattern: 0xc0cba857), Int32(bitPattern: 0x45c8740f), Int32(bitPattern: 0xd20b5f39), Int32(bitPattern: 0xb9d3fbdb),
Int32(bitPattern: 0x5579c0bd), Int32(bitPattern: 0x1a60320a), Int32(bitPattern: 0xd6a100c6), Int32(bitPattern: 0x402c7279),
Int32(bitPattern: 0x679f25fe), Int32(bitPattern: 0xfb1fa3cc), Int32(bitPattern: 0x8ea5e9f8), Int32(bitPattern: 0xdb3222f8),
Int32(bitPattern: 0x3c7516df), Int32(bitPattern: 0xfd616b15), Int32(bitPattern: 0x2f501ec8), Int32(bitPattern: 0xad0552ab),
Int32(bitPattern: 0x323db5fa), Int32(bitPattern: 0xfd238760), Int32(bitPattern: 0x53317b48), Int32(bitPattern: 0x3e00df82),
Int32(bitPattern: 0x9e5c57bb), Int32(bitPattern: 0xca6f8ca0), Int32(bitPattern: 0x1a87562e), Int32(bitPattern: 0xdf1769db),
Int32(bitPattern: 0xd542a8f6), Int32(bitPattern: 0x287effc3), Int32(bitPattern: 0xac6732c6), Int32(bitPattern: 0x8c4f5573),
Int32(bitPattern: 0x695b27b0), Int32(bitPattern: 0xbbca58c8), Int32(bitPattern: 0xe1ffa35d), Int32(bitPattern: 0xb8f011a0),
Int32(bitPattern: 0x10fa3d98), Int32(bitPattern: 0xfd2183b8), Int32(bitPattern: 0x4afcb56c), Int32(bitPattern: 0x2dd1d35b),
Int32(bitPattern: 0x9a53e479), Int32(bitPattern: 0xb6f84565), Int32(bitPattern: 0xd28e49bc), Int32(bitPattern: 0x4bfb9790),
Int32(bitPattern: 0xe1ddf2da), Int32(bitPattern: 0xa4cb7e33), Int32(bitPattern: 0x62fb1341), Int32(bitPattern: 0xcee4c6e8),
Int32(bitPattern: 0xef20cada), Int32(bitPattern: 0x36774c01), Int32(bitPattern: 0xd07e9efe), Int32(bitPattern: 0x2bf11fb4),
Int32(bitPattern: 0x95dbda4d), Int32(bitPattern: 0xae909198), Int32(bitPattern: 0xeaad8e71), Int32(bitPattern: 0x6b93d5a0),
Int32(bitPattern: 0xd08ed1d0), Int32(bitPattern: 0xafc725e0), Int32(bitPattern: 0x8e3c5b2f), Int32(bitPattern: 0x8e7594b7),
Int32(bitPattern: 0x8ff6e2fb), Int32(bitPattern: 0xf2122b64), Int32(bitPattern: 0x8888b812), Int32(bitPattern: 0x900df01c),
Int32(bitPattern: 0x4fad5ea0), Int32(bitPattern: 0x688fc31c), Int32(bitPattern: 0xd1cff191), Int32(bitPattern: 0xb3a8c1ad),
Int32(bitPattern: 0x2f2f2218), Int32(bitPattern: 0xbe0e1777), Int32(bitPattern: 0xea752dfe), Int32(bitPattern: 0x8b021fa1),
Int32(bitPattern: 0xe5a0cc0f), Int32(bitPattern: 0xb56f74e8), Int32(bitPattern: 0x18acf3d6), Int32(bitPattern: 0xce89e299),
Int32(bitPattern: 0xb4a84fe0), Int32(bitPattern: 0xfd13e0b7), Int32(bitPattern: 0x7cc43b81), Int32(bitPattern: 0xd2ada8d9),
Int32(bitPattern: 0x165fa266), Int32(bitPattern: 0x80957705), Int32(bitPattern: 0x93cc7314), Int32(bitPattern: 0x211a1477),
Int32(bitPattern: 0xe6ad2065), Int32(bitPattern: 0x77b5fa86), Int32(bitPattern: 0xc75442f5), Int32(bitPattern: 0xfb9d35cf),
Int32(bitPattern: 0xebcdaf0c), Int32(bitPattern: 0x7b3e89a0), Int32(bitPattern: 0xd6411bd3), Int32(bitPattern: 0xae1e7e49),
Int32(bitPattern: 0x00250e2d), Int32(bitPattern: 0x2071b35e), Int32(bitPattern: 0x226800bb), Int32(bitPattern: 0x57b8e0af),
Int32(bitPattern: 0x2464369b), Int32(bitPattern: 0xf009b91e), Int32(bitPattern: 0x5563911d), Int32(bitPattern: 0x59dfa6aa),
Int32(bitPattern: 0x78c14389), Int32(bitPattern: 0xd95a537f), Int32(bitPattern: 0x207d5ba2), Int32(bitPattern: 0x02e5b9c5),
Int32(bitPattern: 0x83260376), Int32(bitPattern: 0x6295cfa9), Int32(bitPattern: 0x11c81968), Int32(bitPattern: 0x4e734a41),
Int32(bitPattern: 0xb3472dca), Int32(bitPattern: 0x7b14a94a), Int32(bitPattern: 0x1b510052), Int32(bitPattern: 0x9a532915),
Int32(bitPattern: 0xd60f573f), Int32(bitPattern: 0xbc9bc6e4), Int32(bitPattern: 0x2b60a476), Int32(bitPattern: 0x81e67400),
Int32(bitPattern: 0x08ba6fb5), Int32(bitPattern: 0x571be91f), Int32(bitPattern: 0xf296ec6b), Int32(bitPattern: 0x2a0dd915),
Int32(bitPattern: 0xb6636521), Int32(bitPattern: 0xe7b9f9b6), Int32(bitPattern: 0xff34052e), Int32(bitPattern: 0xc5855664),
Int32(bitPattern: 0x53b02d5d), Int32(bitPattern: 0xa99f8fa1), Int32(bitPattern: 0x08ba4799), Int32(bitPattern: 0x6e85076a),
Int32(bitPattern: 0x4b7a70e9), Int32(bitPattern: 0xb5b32944), Int32(bitPattern: 0xdb75092e), Int32(bitPattern: 0xc4192623),
Int32(bitPattern: 0xad6ea6b0), Int32(bitPattern: 0x49a7df7d), Int32(bitPattern: 0x9cee60b8), Int32(bitPattern: 0x8fedb266),
Int32(bitPattern: 0xecaa8c71), Int32(bitPattern: 0x699a17ff), Int32(bitPattern: 0x5664526c), Int32(bitPattern: 0xc2b19ee1),
Int32(bitPattern: 0x193602a5), Int32(bitPattern: 0x75094c29), Int32(bitPattern: 0xa0591340), Int32(bitPattern: 0xe4183a3e),
Int32(bitPattern: 0x3f54989a), Int32(bitPattern: 0x5b429d65), Int32(bitPattern: 0x6b8fe4d6), Int32(bitPattern: 0x99f73fd6),
Int32(bitPattern: 0xa1d29c07), Int32(bitPattern: 0xefe830f5), Int32(bitPattern: 0x4d2d38e6), Int32(bitPattern: 0xf0255dc1),
Int32(bitPattern: 0x4cdd2086), Int32(bitPattern: 0x8470eb26), Int32(bitPattern: 0x6382e9c6), Int32(bitPattern: 0x021ecc5e),
Int32(bitPattern: 0x09686b3f), Int32(bitPattern: 0x3ebaefc9), Int32(bitPattern: 0x3c971814), Int32(bitPattern: 0x6b6a70a1),
Int32(bitPattern: 0x687f3584), Int32(bitPattern: 0x52a0e286), Int32(bitPattern: 0xb79c5305), Int32(bitPattern: 0xaa500737),
Int32(bitPattern: 0x3e07841c), Int32(bitPattern: 0x7fdeae5c), Int32(bitPattern: 0x8e7d44ec), Int32(bitPattern: 0x5716f2b8),
Int32(bitPattern: 0xb03ada37), Int32(bitPattern: 0xf0500c0d), Int32(bitPattern: 0xf01c1f04), Int32(bitPattern: 0x0200b3ff),
Int32(bitPattern: 0xae0cf51a), Int32(bitPattern: 0x3cb574b2), Int32(bitPattern: 0x25837a58), Int32(bitPattern: 0xdc0921bd),
Int32(bitPattern: 0xd19113f9), Int32(bitPattern: 0x7ca92ff6), Int32(bitPattern: 0x94324773), Int32(bitPattern: 0x22f54701),
Int32(bitPattern: 0x3ae5e581), Int32(bitPattern: 0x37c2dadc), Int32(bitPattern: 0xc8b57634), Int32(bitPattern: 0x9af3dda7),
Int32(bitPattern: 0xa9446146), Int32(bitPattern: 0x0fd0030e), Int32(bitPattern: 0xecc8c73e), Int32(bitPattern: 0xa4751e41),
Int32(bitPattern: 0xe238cd99), Int32(bitPattern: 0x3bea0e2f), Int32(bitPattern: 0x3280bba1), Int32(bitPattern: 0x183eb331),
Int32(bitPattern: 0x4e548b38), Int32(bitPattern: 0x4f6db908), Int32(bitPattern: 0x6f420d03), Int32(bitPattern: 0xf60a04bf),
Int32(bitPattern: 0x2cb81290), Int32(bitPattern: 0x24977c79), Int32(bitPattern: 0x5679b072), Int32(bitPattern: 0xbcaf89af),
Int32(bitPattern: 0xde9a771f), Int32(bitPattern: 0xd9930810), Int32(bitPattern: 0xb38bae12), Int32(bitPattern: 0xdccf3f2e),
Int32(bitPattern: 0x5512721f), Int32(bitPattern: 0x2e6b7124), Int32(bitPattern: 0x501adde6), Int32(bitPattern: 0x9f84cd87),
Int32(bitPattern: 0x7a584718), Int32(bitPattern: 0x7408da17), Int32(bitPattern: 0xbc9f9abc), Int32(bitPattern: 0xe94b7d8c),
Int32(bitPattern: 0xec7aec3a), Int32(bitPattern: 0xdb851dfa), Int32(bitPattern: 0x63094366), Int32(bitPattern: 0xc464c3d2),
Int32(bitPattern: 0xef1c1847), Int32(bitPattern: 0x3215d908), Int32(bitPattern: 0xdd433b37), Int32(bitPattern: 0x24c2ba16),
Int32(bitPattern: 0x12a14d43), Int32(bitPattern: 0x2a65c451), Int32(bitPattern: 0x50940002), Int32(bitPattern: 0x133ae4dd),
Int32(bitPattern: 0x71dff89e), Int32(bitPattern: 0x10314e55), Int32(bitPattern: 0x81ac77d6), Int32(bitPattern: 0x5f11199b),
Int32(bitPattern: 0x043556f1), Int32(bitPattern: 0xd7a3c76b), Int32(bitPattern: 0x3c11183b), Int32(bitPattern: 0x5924a509),
Int32(bitPattern: 0xf28fe6ed), Int32(bitPattern: 0x97f1fbfa), Int32(bitPattern: 0x9ebabf2c), Int32(bitPattern: 0x1e153c6e),
Int32(bitPattern: 0x86e34570), Int32(bitPattern: 0xeae96fb1), Int32(bitPattern: 0x860e5e0a), Int32(bitPattern: 0x5a3e2ab3),
Int32(bitPattern: 0x771fe71c), Int32(bitPattern: 0x4e3d06fa), Int32(bitPattern: 0x2965dcb9), Int32(bitPattern: 0x99e71d0f),
Int32(bitPattern: 0x803e89d6), Int32(bitPattern: 0x5266c825), Int32(bitPattern: 0x2e4cc978), Int32(bitPattern: 0x9c10b36a),
Int32(bitPattern: 0xc6150eba), Int32(bitPattern: 0x94e2ea78), Int32(bitPattern: 0xa5fc3c53), Int32(bitPattern: 0x1e0a2df4),
Int32(bitPattern: 0xf2f74ea7), Int32(bitPattern: 0x361d2b3d), Int32(bitPattern: 0x1939260f), Int32(bitPattern: 0x19c27960),
Int32(bitPattern: 0x5223a708), Int32(bitPattern: 0xf71312b6), Int32(bitPattern: 0xebadfe6e), Int32(bitPattern: 0xeac31f66),
Int32(bitPattern: 0xe3bc4595), Int32(bitPattern: 0xa67bc883), Int32(bitPattern: 0xb17f37d1), Int32(bitPattern: 0x018cff28),
Int32(bitPattern: 0xc332ddef), Int32(bitPattern: 0xbe6c5aa5), Int32(bitPattern: 0x65582185), Int32(bitPattern: 0x68ab9802),
Int32(bitPattern: 0xeecea50f), Int32(bitPattern: 0xdb2f953b), Int32(bitPattern: 0x2aef7dad), Int32(bitPattern: 0x5b6e2f84),
Int32(bitPattern: 0x1521b628), Int32(bitPattern: 0x29076170), Int32(bitPattern: 0xecdd4775), Int32(bitPattern: 0x619f1510),
Int32(bitPattern: 0x13cca830), Int32(bitPattern: 0xeb61bd96), Int32(bitPattern: 0x0334fe1e), Int32(bitPattern: 0xaa0363cf),
Int32(bitPattern: 0xb5735c90), Int32(bitPattern: 0x4c70a239), Int32(bitPattern: 0xd59e9e0b), Int32(bitPattern: 0xcbaade14),
Int32(bitPattern: 0xeecc86bc), Int32(bitPattern: 0x60622ca7), Int32(bitPattern: 0x9cab5cab), Int32(bitPattern: 0xb2f3846e),
Int32(bitPattern: 0x648b1eaf), Int32(bitPattern: 0x19bdf0ca), Int32(bitPattern: 0xa02369b9), Int32(bitPattern: 0x655abb50),
Int32(bitPattern: 0x40685a32), Int32(bitPattern: 0x3c2ab4b3), Int32(bitPattern: 0x319ee9d5), Int32(bitPattern: 0xc021b8f7),
Int32(bitPattern: 0x9b540b19), Int32(bitPattern: 0x875fa099), Int32(bitPattern: 0x95f7997e), Int32(bitPattern: 0x623d7da8),
Int32(bitPattern: 0xf837889a), Int32(bitPattern: 0x97e32d77), Int32(bitPattern: 0x11ed935f), Int32(bitPattern: 0x16681281),
Int32(bitPattern: 0x0e358829), Int32(bitPattern: 0xc7e61fd6), Int32(bitPattern: 0x96dedfa1), Int32(bitPattern: 0x7858ba99),
Int32(bitPattern: 0x57f584a5), Int32(bitPattern: 0x1b227263), Int32(bitPattern: 0x9b83c3ff), Int32(bitPattern: 0x1ac24696),
Int32(bitPattern: 0xcdb30aeb), Int32(bitPattern: 0x532e3054), Int32(bitPattern: 0x8fd948e4), Int32(bitPattern: 0x6dbc3128),
Int32(bitPattern: 0x58ebf2ef), Int32(bitPattern: 0x34c6ffea), Int32(bitPattern: 0xfe28ed61), Int32(bitPattern: 0xee7c3c73),
Int32(bitPattern: 0x5d4a14d9), Int32(bitPattern: 0xe864b7e3), Int32(bitPattern: 0x42105d14), Int32(bitPattern: 0x203e13e0),
Int32(bitPattern: 0x45eee2b6), Int32(bitPattern: 0xa3aaabea), Int32(bitPattern: 0xdb6c4f15), Int32(bitPattern: 0xfacb4fd0),
Int32(bitPattern: 0xc742f442), Int32(bitPattern: 0xef6abbb5), Int32(bitPattern: 0x654f3b1d), Int32(bitPattern: 0x41cd2105),
Int32(bitPattern: 0xd81e799e), Int32(bitPattern: 0x86854dc7), Int32(bitPattern: 0xe44b476a), Int32(bitPattern: 0x3d816250),
Int32(bitPattern: 0xcf62a1f2), Int32(bitPattern: 0x5b8d2646), Int32(bitPattern: 0xfc8883a0), Int32(bitPattern: 0xc1c7b6a3),
Int32(bitPattern: 0x7f1524c3), Int32(bitPattern: 0x69cb7492), Int32(bitPattern: 0x47848a0b), Int32(bitPattern: 0x5692b285),
Int32(bitPattern: 0x095bbf00), Int32(bitPattern: 0xad19489d), Int32(bitPattern: 0x1462b174), Int32(bitPattern: 0x23820e00),
Int32(bitPattern: 0x58428d2a), Int32(bitPattern: 0x0c55f5ea), Int32(bitPattern: 0x1dadf43e), Int32(bitPattern: 0x233f7061),
Int32(bitPattern: 0x3372f092), Int32(bitPattern: 0x8d937e41), Int32(bitPattern: 0xd65fecf1), Int32(bitPattern: 0x6c223bdb),
Int32(bitPattern: 0x7cde3759), Int32(bitPattern: 0xcbee7460), Int32(bitPattern: 0x4085f2a7), Int32(bitPattern: 0xce77326e),
Int32(bitPattern: 0xa6078084), Int32(bitPattern: 0x19f8509e), Int32(bitPattern: 0xe8efd855), Int32(bitPattern: 0x61d99735),
Int32(bitPattern: 0xa969a7aa), Int32(bitPattern: 0xc50c06c2), Int32(bitPattern: 0x5a04abfc), Int32(bitPattern: 0x800bcadc),
Int32(bitPattern: 0x9e447a2e), Int32(bitPattern: 0xc3453484), Int32(bitPattern: 0xfdd56705), Int32(bitPattern: 0x0e1e9ec9),
Int32(bitPattern: 0xdb73dbd3), Int32(bitPattern: 0x105588cd), Int32(bitPattern: 0x675fda79), Int32(bitPattern: 0xe3674340),
Int32(bitPattern: 0xc5c43465), Int32(bitPattern: 0x713e38d8), Int32(bitPattern: 0x3d28f89e), Int32(bitPattern: 0xf16dff20),
Int32(bitPattern: 0x153e21e7), Int32(bitPattern: 0x8fb03d4a), Int32(bitPattern: 0xe6e39f2b), Int32(bitPattern: 0xdb83adf7),
Int32(bitPattern: 0xe93d5a68), Int32(bitPattern: 0x948140f7), Int32(bitPattern: 0xf64c261c), Int32(bitPattern: 0x94692934),
Int32(bitPattern: 0x411520f7), Int32(bitPattern: 0x7602d4f7), Int32(bitPattern: 0xbcf46b2e), Int32(bitPattern: 0xd4a20068),
Int32(bitPattern: 0xd4082471), Int32(bitPattern: 0x3320f46a), Int32(bitPattern: 0x43b7d4b7), Int32(bitPattern: 0x500061af),
Int32(bitPattern: 0x1e39f62e), Int32(bitPattern: 0x97244546), Int32(bitPattern: 0x14214f74), Int32(bitPattern: 0xbf8b8840),
Int32(bitPattern: 0x4d95fc1d), Int32(bitPattern: 0x96b591af), Int32(bitPattern: 0x70f4ddd3), Int32(bitPattern: 0x66a02f45),
Int32(bitPattern: 0xbfbc09ec), Int32(bitPattern: 0x03bd9785), Int32(bitPattern: 0x7fac6dd0), Int32(bitPattern: 0x31cb8504),
Int32(bitPattern: 0x96eb27b3), Int32(bitPattern: 0x55fd3941), Int32(bitPattern: 0xda2547e6), Int32(bitPattern: 0xabca0a9a),
Int32(bitPattern: 0x28507825), Int32(bitPattern: 0x530429f4), Int32(bitPattern: 0x0a2c86da), Int32(bitPattern: 0xe9b66dfb),
Int32(bitPattern: 0x68dc1462), Int32(bitPattern: 0xd7486900), Int32(bitPattern: 0x680ec0a4), Int32(bitPattern: 0x27a18dee),
Int32(bitPattern: 0x4f3ffea2), Int32(bitPattern: 0xe887ad8c), Int32(bitPattern: 0xb58ce006), Int32(bitPattern: 0x7af4d6b6),
Int32(bitPattern: 0xaace1e7c), Int32(bitPattern: 0xd3375fec), Int32(bitPattern: 0xce78a399), Int32(bitPattern: 0x406b2a42),
Int32(bitPattern: 0x20fe9e35), Int32(bitPattern: 0xd9f385b9), Int32(bitPattern: 0xee39d7ab), Int32(bitPattern: 0x3b124e8b),
Int32(bitPattern: 0x1dc9faf7), Int32(bitPattern: 0x4b6d1856), Int32(bitPattern: 0x26a36631), Int32(bitPattern: 0xeae397b2),
Int32(bitPattern: 0x3a6efa74), Int32(bitPattern: 0xdd5b4332), Int32(bitPattern: 0x6841e7f7), Int32(bitPattern: 0xca7820fb),
Int32(bitPattern: 0xfb0af54e), Int32(bitPattern: 0xd8feb397), Int32(bitPattern: 0x454056ac), Int32(bitPattern: 0xba489527),
Int32(bitPattern: 0x55533a3a), Int32(bitPattern: 0x20838d87), Int32(bitPattern: 0xfe6ba9b7), Int32(bitPattern: 0xd096954b),
Int32(bitPattern: 0x55a867bc), Int32(bitPattern: 0xa1159a58), Int32(bitPattern: 0xcca92963), Int32(bitPattern: 0x99e1db33),
Int32(bitPattern: 0xa62a4a56), Int32(bitPattern: 0x3f3125f9), Int32(bitPattern: 0x5ef47e1c), Int32(bitPattern: 0x9029317c),
Int32(bitPattern: 0xfdf8e802), Int32(bitPattern: 0x04272f70), Int32(bitPattern: 0x80bb155c), Int32(bitPattern: 0x05282ce3),
Int32(bitPattern: 0x95c11548), Int32(bitPattern: 0xe4c66d22), Int32(bitPattern: 0x48c1133f), Int32(bitPattern: 0xc70f86dc),
Int32(bitPattern: 0x07f9c9ee), Int32(bitPattern: 0x41041f0f), Int32(bitPattern: 0x404779a4), Int32(bitPattern: 0x5d886e17),
Int32(bitPattern: 0x325f51eb), Int32(bitPattern: 0xd59bc0d1), Int32(bitPattern: 0xf2bcc18f), Int32(bitPattern: 0x41113564),
Int32(bitPattern: 0x257b7834), Int32(bitPattern: 0x602a9c60), Int32(bitPattern: 0xdff8e8a3), Int32(bitPattern: 0x1f636c1b),
Int32(bitPattern: 0x0e12b4c2), Int32(bitPattern: 0x02e1329e), Int32(bitPattern: 0xaf664fd1), Int32(bitPattern: 0xcad18115),
Int32(bitPattern: 0x6b2395e0), Int32(bitPattern: 0x333e92e1), Int32(bitPattern: 0x3b240b62), Int32(bitPattern: 0xeebeb922),
Int32(bitPattern: 0x85b2a20e), Int32(bitPattern: 0xe6ba0d99), Int32(bitPattern: 0xde720c8c), Int32(bitPattern: 0x2da2f728),
Int32(bitPattern: 0xd0127845), Int32(bitPattern: 0x95b794fd), Int32(bitPattern: 0x647d0862), Int32(bitPattern: 0xe7ccf5f0),
Int32(bitPattern: 0x5449a36f), Int32(bitPattern: 0x877d48fa), Int32(bitPattern: 0xc39dfd27), Int32(bitPattern: 0xf33e8d1e),
Int32(bitPattern: 0x0a476341), Int32(bitPattern: 0x992eff74), Int32(bitPattern: 0x3a6f6eab), Int32(bitPattern: 0xf4f8fd37),
Int32(bitPattern: 0xa812dc60), Int32(bitPattern: 0xa1ebddf8), Int32(bitPattern: 0x991be14c), Int32(bitPattern: 0xdb6e6b0d),
Int32(bitPattern: 0xc67b5510), Int32(bitPattern: 0x6d672c37), Int32(bitPattern: 0x2765d43b), Int32(bitPattern: 0xdcd0e804),
Int32(bitPattern: 0xf1290dc7), Int32(bitPattern: 0xcc00ffa3), Int32(bitPattern: 0xb5390f92), Int32(bitPattern: 0x690fed0b),
Int32(bitPattern: 0x667b9ffb), Int32(bitPattern: 0xcedb7d9c), Int32(bitPattern: 0xa091cf0b), Int32(bitPattern: 0xd9155ea3),
Int32(bitPattern: 0xbb132f88), Int32(bitPattern: 0x515bad24), Int32(bitPattern: 0x7b9479bf), Int32(bitPattern: 0x763bd6eb),
Int32(bitPattern: 0x37392eb3), Int32(bitPattern: 0xcc115979), Int32(bitPattern: 0x8026e297), Int32(bitPattern: 0xf42e312d),
Int32(bitPattern: 0x6842ada7), Int32(bitPattern: 0xc66a2b3b), Int32(bitPattern: 0x12754ccc), Int32(bitPattern: 0x782ef11c),
Int32(bitPattern: 0x6a124237), Int32(bitPattern: 0xb79251e7), Int32(bitPattern: 0x06a1bbe6), Int32(bitPattern: 0x4bfb6350),
Int32(bitPattern: 0x1a6b1018), Int32(bitPattern: 0x11caedfa), Int32(bitPattern: 0x3d25bdd8), Int32(bitPattern: 0xe2e1c3c9),
Int32(bitPattern: 0x44421659), Int32(bitPattern: 0x0a121386), Int32(bitPattern: 0xd90cec6e), Int32(bitPattern: 0xd5abea2a),
Int32(bitPattern: 0x64af674e), Int32(bitPattern: 0xda86a85f), Int32(bitPattern: 0xbebfe988), Int32(bitPattern: 0x64e4c3fe),
Int32(bitPattern: 0x9dbc8057), Int32(bitPattern: 0xf0f7c086), Int32(bitPattern: 0x60787bf8), Int32(bitPattern: 0x6003604d),
Int32(bitPattern: 0xd1fd8346), Int32(bitPattern: 0xf6381fb0), Int32(bitPattern: 0x7745ae04), Int32(bitPattern: 0xd736fccc),
Int32(bitPattern: 0x83426b33), Int32(bitPattern: 0xf01eab71), Int32(bitPattern: 0xb0804187), Int32(bitPattern: 0x3c005e5f),
Int32(bitPattern: 0x77a057be), Int32(bitPattern: 0xbde8ae24), Int32(bitPattern: 0x55464299), Int32(bitPattern: 0xbf582e61),
Int32(bitPattern: 0x4e58f48f), Int32(bitPattern: 0xf2ddfda2), Int32(bitPattern: 0xf474ef38), Int32(bitPattern: 0x8789bdc2),
Int32(bitPattern: 0x5366f9c3), Int32(bitPattern: 0xc8b38e74), Int32(bitPattern: 0xb475f255), Int32(bitPattern: 0x46fcd9b9),
Int32(bitPattern: 0x7aeb2661), Int32(bitPattern: 0x8b1ddf84), Int32(bitPattern: 0x846a0e79), Int32(bitPattern: 0x915f95e2),
Int32(bitPattern: 0x466e598e), Int32(bitPattern: 0x20b45770), Int32(bitPattern: 0x8cd55591), Int32(bitPattern: 0xc902de4c),
Int32(bitPattern: 0xb90bace1), Int32(bitPattern: 0xbb8205d0), Int32(bitPattern: 0x11a86248), Int32(bitPattern: 0x7574a99e),
Int32(bitPattern: 0xb77f19b6), Int32(bitPattern: 0xe0a9dc09), Int32(bitPattern: 0x662d09a1), Int32(bitPattern: 0xc4324633),
Int32(bitPattern: 0xe85a1f02), Int32(bitPattern: 0x09f0be8c), Int32(bitPattern: 0x4a99a025), Int32(bitPattern: 0x1d6efe10),
Int32(bitPattern: 0x1ab93d1d), Int32(bitPattern: 0x0ba5a4df), Int32(bitPattern: 0xa186f20f), Int32(bitPattern: 0x2868f169),
Int32(bitPattern: 0xdcb7da83), Int32(bitPattern: 0x573906fe), Int32(bitPattern: 0xa1e2ce9b), Int32(bitPattern: 0x4fcd7f52),
Int32(bitPattern: 0x50115e01), Int32(bitPattern: 0xa70683fa), Int32(bitPattern: 0xa002b5c4), Int32(bitPattern: 0x0de6d027),
Int32(bitPattern: 0x9af88c27), Int32(bitPattern: 0x773f8641), Int32(bitPattern: 0xc3604c06), Int32(bitPattern: 0x61a806b5),
Int32(bitPattern: 0xf0177a28), Int32(bitPattern: 0xc0f586e0), Int32(bitPattern: 0x006058aa), Int32(bitPattern: 0x30dc7d62),
Int32(bitPattern: 0x11e69ed7), Int32(bitPattern: 0x2338ea63), Int32(bitPattern: 0x53c2dd94), Int32(bitPattern: 0xc2c21634),
Int32(bitPattern: 0xbbcbee56), Int32(bitPattern: 0x90bcb6de), Int32(bitPattern: 0xebfc7da1), Int32(bitPattern: 0xce591d76),
Int32(bitPattern: 0x6f05e409), Int32(bitPattern: 0x4b7c0188), Int32(bitPattern: 0x39720a3d), Int32(bitPattern: 0x7c927c24),
Int32(bitPattern: 0x86e3725f), Int32(bitPattern: 0x724d9db9), Int32(bitPattern: 0x1ac15bb4), Int32(bitPattern: 0xd39eb8fc),
Int32(bitPattern: 0xed545578), Int32(bitPattern: 0x08fca5b5), Int32(bitPattern: 0xd83d7cd3), Int32(bitPattern: 0x4dad0fc4),
Int32(bitPattern: 0x1e50ef5e), Int32(bitPattern: 0xb161e6f8), Int32(bitPattern: 0xa28514d9), Int32(bitPattern: 0x6c51133c),
Int32(bitPattern: 0x6fd5c7e7), Int32(bitPattern: 0x56e14ec4), Int32(bitPattern: 0x362abfce), Int32(bitPattern: 0xddc6c837),
Int32(bitPattern: 0xd79a3234), Int32(bitPattern: 0x92638212), Int32(bitPattern: 0x670efa8e), Int32(bitPattern: 0x406000e0),
Int32(bitPattern: 0x3a39ce37), Int32(bitPattern: 0xd3faf5cf), Int32(bitPattern: 0xabc27737), Int32(bitPattern: 0x5ac52d1b),
Int32(bitPattern: 0x5cb0679e), Int32(bitPattern: 0x4fa33742), Int32(bitPattern: 0xd3822740), Int32(bitPattern: 0x99bc9bbe),
Int32(bitPattern: 0xd5118e9d), Int32(bitPattern: 0xbf0f7315), Int32(bitPattern: 0xd62d1c7e), Int32(bitPattern: 0xc700c47b),
Int32(bitPattern: 0xb78c1b6b), Int32(bitPattern: 0x21a19045), Int32(bitPattern: 0xb26eb1be), Int32(bitPattern: 0x6a366eb4),
Int32(bitPattern: 0x5748ab2f), Int32(bitPattern: 0xbc946e79), Int32(bitPattern: 0xc6a376d2), Int32(bitPattern: 0x6549c2c8),
Int32(bitPattern: 0x530ff8ee), Int32(bitPattern: 0x468dde7d), Int32(bitPattern: 0xd5730a1d), Int32(bitPattern: 0x4cd04dc6),
Int32(bitPattern: 0x2939bbdb), Int32(bitPattern: 0xa9ba4650), Int32(bitPattern: 0xac9526e8), Int32(bitPattern: 0xbe5ee304),
Int32(bitPattern: 0xa1fad5f0), Int32(bitPattern: 0x6a2d519a), Int32(bitPattern: 0x63ef8ce2), Int32(bitPattern: 0x9a86ee22),
Int32(bitPattern: 0xc089c2b8), Int32(bitPattern: 0x43242ef6), Int32(bitPattern: 0xa51e03aa), Int32(bitPattern: 0x9cf2d0a4),
Int32(bitPattern: 0x83c061ba), Int32(bitPattern: 0x9be96a4d), Int32(bitPattern: 0x8fe51550), Int32(bitPattern: 0xba645bd6),
Int32(bitPattern: 0x2826a2f9), Int32(bitPattern: 0xa73a3ae1), Int32(bitPattern: 0x4ba99586), Int32(bitPattern: 0xef5562e9),
Int32(bitPattern: 0xc72fefd3), Int32(bitPattern: 0xf752f7da), Int32(bitPattern: 0x3f046f69), Int32(bitPattern: 0x77fa0a59),
Int32(bitPattern: 0x80e4a915), Int32(bitPattern: 0x87b08601), Int32(bitPattern: 0x9b09e6ad), Int32(bitPattern: 0x3b3ee593),
Int32(bitPattern: 0xe990fd5a), Int32(bitPattern: 0x9e34d797), Int32(bitPattern: 0x2cf0b7d9), Int32(bitPattern: 0x022b8b51),
Int32(bitPattern: 0x96d5ac3a), Int32(bitPattern: 0x017da67d), Int32(bitPattern: 0xd1cf3ed6), Int32(bitPattern: 0x7c7d2d28),
Int32(bitPattern: 0x1f9f25cf), Int32(bitPattern: 0xadf2b89b), Int32(bitPattern: 0x5ad6b472), Int32(bitPattern: 0x5a88f54c),
Int32(bitPattern: 0xe029ac71), Int32(bitPattern: 0xe019a5e6), Int32(bitPattern: 0x47b0acfd), Int32(bitPattern: 0xed93fa9b),
Int32(bitPattern: 0xe8d3c48d), Int32(bitPattern: 0x283b57cc), Int32(bitPattern: 0xf8d56629), Int32(bitPattern: 0x79132e28),
Int32(bitPattern: 0x785f0191), Int32(bitPattern: 0xed756055), Int32(bitPattern: 0xf7960e44), Int32(bitPattern: 0xe3d35e8c),
Int32(bitPattern: 0x15056dd4), Int32(bitPattern: 0x88f46dba), Int32(bitPattern: 0x03a16125), Int32(bitPattern: 0x0564f0bd),
Int32(bitPattern: 0xc3eb9e15), Int32(bitPattern: 0x3c9057a2), Int32(bitPattern: 0x97271aec), Int32(bitPattern: 0xa93a072a),
Int32(bitPattern: 0x1b3f6d9b), Int32(bitPattern: 0x1e6321f5), Int32(bitPattern: 0xf59c66fb), Int32(bitPattern: 0x26dcf319),
Int32(bitPattern: 0x7533d928), Int32(bitPattern: 0xb155fdf5), Int32(bitPattern: 0x03563482), Int32(bitPattern: 0x8aba3cbb),
Int32(bitPattern: 0x28517711), Int32(bitPattern: 0xc20ad9f8), Int32(bitPattern: 0xabcc5167), Int32(bitPattern: 0xccad925f),
Int32(bitPattern: 0x4de81751), Int32(bitPattern: 0x3830dc8e), Int32(bitPattern: 0x379d5862), Int32(bitPattern: 0x9320f991),
Int32(bitPattern: 0xea7a90c2), Int32(bitPattern: 0xfb3e7bce), Int32(bitPattern: 0x5121ce64), Int32(bitPattern: 0x774fbe32),
Int32(bitPattern: 0xa8b6e37e), Int32(bitPattern: 0xc3293d46), Int32(bitPattern: 0x48de5369), Int32(bitPattern: 0x6413e680),
Int32(bitPattern: 0xa2ae0810), Int32(bitPattern: 0xdd6db224), Int32(bitPattern: 0x69852dfd), Int32(bitPattern: 0x09072166),
Int32(bitPattern: 0xb39a460a), Int32(bitPattern: 0x6445c0dd), Int32(bitPattern: 0x586cdecf), Int32(bitPattern: 0x1c20c8ae),
Int32(bitPattern: 0x5bbef7dd), Int32(bitPattern: 0x1b588d40), Int32(bitPattern: 0xccd2017f), Int32(bitPattern: 0x6bb4e3bb),
Int32(bitPattern: 0xdda26a7e), Int32(bitPattern: 0x3a59ff45), Int32(bitPattern: 0x3e350a44), Int32(bitPattern: 0xbcb4cdd5),
Int32(bitPattern: 0x72eacea8), Int32(bitPattern: 0xfa6484bb), Int32(bitPattern: 0x8d6612ae), Int32(bitPattern: 0xbf3c6f47),
Int32(bitPattern: 0xd29be463), Int32(bitPattern: 0x542f5d9e), Int32(bitPattern: 0xaec2771b), Int32(bitPattern: 0xf64e6370),
Int32(bitPattern: 0x740e0d8d), Int32(bitPattern: 0xe75b1357), Int32(bitPattern: 0xf8721671), Int32(bitPattern: 0xaf537d5d),
Int32(bitPattern: 0x4040cb08), Int32(bitPattern: 0x4eb4e2cc), Int32(bitPattern: 0x34d2466a), Int32(bitPattern: 0x0115af84),
Int32(bitPattern: 0xe1b00428), Int32(bitPattern: 0x95983a1d), Int32(bitPattern: 0x06b89fb4), Int32(bitPattern: 0xce6ea048),
Int32(bitPattern: 0x6f3f3b82), Int32(bitPattern: 0x3520ab82), Int32(bitPattern: 0x011a1d4b), Int32(bitPattern: 0x277227f8),
Int32(bitPattern: 0x611560b1), Int32(bitPattern: 0xe7933fdc), Int32(bitPattern: 0xbb3a792b), Int32(bitPattern: 0x344525bd),
Int32(bitPattern: 0xa08839e1), Int32(bitPattern: 0x51ce794b), Int32(bitPattern: 0x2f32c9b7), Int32(bitPattern: 0xa01fbac9),
Int32(bitPattern: 0xe01cc87e), Int32(bitPattern: 0xbcc7d1f6), Int32(bitPattern: 0xcf0111c3), Int32(bitPattern: 0xa1e8aac7),
Int32(bitPattern: 0x1a908749), Int32(bitPattern: 0xd44fbd9a), Int32(bitPattern: 0xd0dadecb), Int32(bitPattern: 0xd50ada38),
Int32(bitPattern: 0x0339c32a), Int32(bitPattern: 0xc6913667), Int32(bitPattern: 0x8df9317c), Int32(bitPattern: 0xe0b12b4f),
Int32(bitPattern: 0xf79e59b7), Int32(bitPattern: 0x43f5bb3a), Int32(bitPattern: 0xf2d519ff), Int32(bitPattern: 0x27d9459c),
Int32(bitPattern: 0xbf97222c), Int32(bitPattern: 0x15e6fc2a), Int32(bitPattern: 0x0f91fc71), Int32(bitPattern: 0x9b941525),
Int32(bitPattern: 0xfae59361), Int32(bitPattern: 0xceb69ceb), Int32(bitPattern: 0xc2a86459), Int32(bitPattern: 0x12baa8d1),
Int32(bitPattern: 0xb6c1075e), Int32(bitPattern: 0xe3056a0c), Int32(bitPattern: 0x10d25065), Int32(bitPattern: 0xcb03a442),
Int32(bitPattern: 0xe0ec6e0e), Int32(bitPattern: 0x1698db3b), Int32(bitPattern: 0x4c98a0be), Int32(bitPattern: 0x3278e964),
Int32(bitPattern: 0x9f1f9532), Int32(bitPattern: 0xe0d392df), Int32(bitPattern: 0xd3a0342b), Int32(bitPattern: 0x8971f21e),
Int32(bitPattern: 0x1b0a7441), Int32(bitPattern: 0x4ba3348c), Int32(bitPattern: 0xc5be7120), Int32(bitPattern: 0xc37632d8),
Int32(bitPattern: 0xdf359f8d), Int32(bitPattern: 0x9b992f2e), Int32(bitPattern: 0xe60b6f47), Int32(bitPattern: 0x0fe3f11d),
Int32(bitPattern: 0xe54cda54), Int32(bitPattern: 0x1edad891), Int32(bitPattern: 0xce6279cf), Int32(bitPattern: 0xcd3e7e6f),
Int32(bitPattern: 0x1618b166), Int32(bitPattern: 0xfd2c1d05), Int32(bitPattern: 0x848fd2c5), Int32(bitPattern: 0xf6fb2299),
Int32(bitPattern: 0xf523f357), Int32(bitPattern: 0xa6327623), Int32(bitPattern: 0x93a83531), Int32(bitPattern: 0x56cccd02),
Int32(bitPattern: 0xacf08162), Int32(bitPattern: 0x5a75ebb5), Int32(bitPattern: 0x6e163697), Int32(bitPattern: 0x88d273cc),
Int32(bitPattern: 0xde966292), Int32(bitPattern: 0x81b949d0), Int32(bitPattern: 0x4c50901b), Int32(bitPattern: 0x71c65614),
Int32(bitPattern: 0xe6c6c7bd), Int32(bitPattern: 0x327a140a), Int32(bitPattern: 0x45e1d006), Int32(bitPattern: 0xc3f27b9a),
Int32(bitPattern: 0xc9aa53fd), Int32(bitPattern: 0x62a80f00), Int32(bitPattern: 0xbb25bfe2), Int32(bitPattern: 0x35bdd2f6),
Int32(bitPattern: 0x71126905), Int32(bitPattern: 0xb2040222), Int32(bitPattern: 0xb6cbcf7c), Int32(bitPattern: 0xcd769c2b),
Int32(bitPattern: 0x53113ec0), Int32(bitPattern: 0x1640e3d3), Int32(bitPattern: 0x38abbd60), Int32(bitPattern: 0x2547adf0),
Int32(bitPattern: 0xba38209c), Int32(bitPattern: 0xf746ce76), Int32(bitPattern: 0x77afa1c5), Int32(bitPattern: 0x20756060),
Int32(bitPattern: 0x85cbfe4e), Int32(bitPattern: 0x8ae88dd8), Int32(bitPattern: 0x7aaaf9b0), Int32(bitPattern: 0x4cf9aa7e),
Int32(bitPattern: 0x1948c25c), Int32(bitPattern: 0x02fb8a8c), Int32(bitPattern: 0x01c36ae4), Int32(bitPattern: 0xd6ebe1f9),
Int32(bitPattern: 0x90d4f869), Int32(bitPattern: 0xa65cdea0), Int32(bitPattern: 0x3f09252d), Int32(bitPattern: 0xc208e69f),
Int32(bitPattern: 0xb74e6132), Int32(bitPattern: 0xce77e25b), Int32(bitPattern: 0x578fdfe3), Int32(bitPattern: 0x3ac372e6)
]
// bcrypt IV: "OrpheanBeholderScryDoubt"
let bf_crypt_ciphertext : [Int32] = [
0x4f727068, 0x65616e42, 0x65686f6c, 0x64657253, 0x63727944, 0x6f756274
]
// Table for Base64 encoding
let base64_code : [Character] = [
".", "/", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K",
"L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X",
"Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
"l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x",
"y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"
]
// Table for Base64 decoding
let index_64 : [Int8] = [
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, 0, 1, 54, 55,
56, 57, 58, 59, 60, 61, 62, 63, -1, -1,
-1, -1, -1, -1, -1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, -1, -1, -1, -1, -1, -1, 28, 29, 30,
31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50,
51, 52, 53, -1, -1, -1, -1, -1
]
// MARK: -
class JKBCrypt: NSObject {
// MARK: Property List
private var p : UnsafeMutablePointer<Int32> // [Int32]
private var s : UnsafeMutablePointer<Int32> // [Int32]
// MARK: - Override Methods
override init() {
self.p = nil
self.s = nil
}
// MARK: - Public Class Methods
/**
Generates a salt with the provided number of rounds.
:param: numberOfRounds The number of rounds to apply.
The work factor increases exponentially as the `numberOfRounds` increases.
:returns: String The generated salt
*/
class func generateSaltWithNumberOfRounds(rounds: UInt) -> String {
let randomData : NSData = JKBCryptRandom.generateRandomSignedDataOfLength(BCRYPT_SALT_LEN)
var salt : String
salt = "$2a$" + ((rounds < 10) ? "0" : "") + "\(rounds)" + "$"
salt += JKBCrypt.encodeData(randomData, ofLength: UInt(randomData.length))
return salt
}
/**
Generates a salt with a defaulted set of 10 rounds.
:returns: String The generated salt.
*/
class func generateSalt() -> String {
return JKBCrypt.generateSaltWithNumberOfRounds(10)
}
/**
Hashes the provided password with the provided salt.
:param: password The password to hash.
:param: salt The salt to use in the hash.
The `salt` must be 16 characters in length. Also, the `salt` must be properly formatted
with accepted version, revision, and salt rounds. If any of this is not true, nil is
returned.
:returns: String? The hashed password.
*/
class func hashPassword(password: String, withSalt salt: String) -> String? {
var bCrypt : JKBCrypt
var realSalt : String
var minor : Character = "\000"[0]
var off : Int = 0
// If the salt length is too short, it is invalid
if salt.characters.count < BCRYPT_SALT_LEN {
return nil
}
// If the salt does not start with "$2", it is an invalid version
if salt[0] != "$" || salt[1] != "2" {
return nil
}
if salt[2] == "$" {
off = 3
}
else {
off = 4
minor = salt[2]
if minor != "a" || salt[3] != "$" {
// Invalid salt revision.
return nil
}
}
// Extract number of rounds
if salt[(Int)(off+2)] > "$" {
// Missing salt rounds
return nil
}
var range : Range = off ..< off+2
let extactedRounds = Int(salt[range])
if extactedRounds == nil {
// Invalid number of rounds
return nil
}
let rounds : Int = extactedRounds!
range = off + 3 ..< off + 25
realSalt = salt[range]
var passwordPreEncoding : String = password
if minor >= "a" {
passwordPreEncoding += "\0"
}
let passwordData : NSData? = (passwordPreEncoding as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let saltData : NSData? = JKBCrypt.decode_base64(realSalt, ofMaxLength: BCRYPT_SALT_LEN)
if passwordData != nil && saltData != nil {
bCrypt = JKBCrypt()
if let hashedData = bCrypt.hashPassword(passwordData!, withSalt: saltData!, numberOfRounds: rounds) {
var hashedPassword : String = "$2" + ((minor >= "a") ? String(minor) : "") + "$"
hashedPassword += ((rounds < 10) ? "0" : "") + "\(rounds)" + "$"
let saltString = JKBCrypt.encodeData(saltData!, ofLength: UInt(saltData!.length))
let hashedString = JKBCrypt.encodeData(hashedData, ofLength: 23)
return hashedPassword + saltString + hashedString
}
}
return nil
}
/**
Hashes the provided password with the provided hash and compares if the two hashes are equal.
:param: password The password to hash.
:param: hash The hash to use in generating and comparing the password.
The `hash` must be properly formatted with accepted version, revision, and salt rounds. If
any of this is not true, nil is returned.
:returns: Bool? TRUE if the password hash matches the given hash; FALSE if the two do not
match; nil if hash is improperly formatted.
*/
class func verifyPassword(password: String, matchesHash hash: String) -> Bool? {
if let hashedPassword = JKBCrypt.hashPassword(password, withSalt: hash) {
return hashedPassword == hash
}
else {
return nil
}
}
// MARK: - Private Class Methods
/**
Encodes an NSData composed of signed chararacters and returns slightly modified
Base64 encoded string.
:param: data The data to be encoded. Passing nil will result in nil being returned.
:param: length The length. Must be greater than 0 and no longer than the length of data.
:returns: String A Base64 encoded string.
*/
class private func encodeData(data: NSData, ofLength length: UInt) -> String {
if data.length == 0 || length == 0 {
// Invalid data so return nil.
return String()
}
var len : Int = Int(length)
if len > data.length {
len = data.length
}
var offset : Int = 0
var c1 : UInt8
var c2 : UInt8
var result : String = String()
var dataArray : [UInt8] = [UInt8](count: len, repeatedValue: 0)
data.getBytes(&dataArray, length:len)
while offset < len {
c1 = dataArray[offset++] & 0xff
result.append(base64_code[Int((c1 >> 2) & 0x3f)])
c1 = (c1 & 0x03) << 4
if offset >= len {
result.append(base64_code[Int(c1 & 0x3f)])
break
}
c2 = dataArray[offset++] & 0xff
c1 |= (c2 >> 4) & 0x0f
result.append(base64_code[Int(c1 & 0x3f)])
c1 = (c2 & 0x0f) << 2
if offset >= len {
result.append(base64_code[Int(c1 & 0x3f)])
break
}
c2 = dataArray[offset++] & 0xff
c1 |= (c2 >> 6) & 0x03
result.append(base64_code[Int(c1 & 0x3f)])
result.append(base64_code[Int(c2 & 0x3f)])
}
return result
}
/**
Returns the Base64 encoded signed character of the provided unicode character.
:param: x The 16-bit unicode character whose Base64 counterpart, if any, will be returned.
:returns: Int8 The Base64 encoded signed character or -1 if none exists.
*/
class private func char64of(x: Character) -> Int8 {
let xAsInt : Int32 = Int32(x.utf16Value())
if xAsInt < 0 || xAsInt > 128 - 1 {
// The character would go out of bounds of the pre-calculated array so return -1.
return -1
}
// Return the matching Base64 encoded character.
return index_64[Int(xAsInt)]
}
/**
Decodes the provided Base64 encoded string to an NSData composed of signed characters.
:param: s The Base64 encoded string. If this is nil, nil will be returned.
:param: maxolen The maximum number of characters to decode. If this is not greater than 0 nil will be returned.
:returns: NSData? An NSData or nil if the arguments are invalid.
*/
class private func decode_base64(s: String, ofMaxLength maxolen: Int) -> NSData? {
var off : Int = 0
let slen : Int = s.characters.count
var olen : Int = 0
var result : [Int8] = [Int8](count: maxolen, repeatedValue: 0)
var c1 : Int8
var c2 : Int8
var c3 : Int8
var c4 : Int8
var o : Int8
if maxolen <= 0 {
// Invalid number of characters.
return nil
}
while off < slen - 1 && olen < maxolen {
c1 = JKBCrypt.char64of(s[off++])
c2 = JKBCrypt.char64of(s[off++])
if c1 == -1 || c2 == -1 {
break
}
o = c1 << 2
o |= (c2 & 0x30) >> 4
result[olen] = o
if ++olen >= maxolen || off >= slen {
break
}
c3 = JKBCrypt.char64of(s[Int(off++)])
if c3 == -1 {
break
}
o = (c2 & 0x0f) << 4
o |= (c3 & 0x3c) >> 2
result[olen] = o
if ++olen >= maxolen || off >= slen {
break
}
c4 = JKBCrypt.char64of(s[off++])
o = (c3 & 0x03) << 6
o |= c4
result[olen] = o
++olen
}
return NSData(bytes: result, length: olen)
}
/**
Cyclically extracts a word of key material from the provided NSData.
:param: d The NSData from which the word will be extracted.
:param: offp The "pointer" (as a one-entry array) to the current offset into data.
:returns: UInt32 The next word of material from the data.
*/
// class private func streamToWord(data: NSData, inout off offp: Int32) -> Int32 {
class private func streamToWordWithData(data: UnsafeMutablePointer<Int8>, ofLength length: Int, inout off offp: Int32) -> Int32 {
// var dataLength : Int = data.length
// var dataArray : [Int8] = [Int8](count:d.length, repeatedValue: 0)
// data.getBytes(&dataArray, length:dataLength)
var word : Int32 = 0
var off : Int32 = offp
for _ in 0 ..< 4 {
word = (word << 8) | (Int32(data[Int(off)]) & 0xff)
off = (off + 1) % Int32(length)
}
offp = off
return word
}
// MARK: - Private Instance Methods
/**
Hashes the provided password with the salt for the number of rounds.
:param: password The password to hash.
:param: salt The salt to use in the hash.
:param: numberOfRounds The number of rounds to apply.
The salt must be 16 characters in length. The `numberOfRounds` must be between 4
and 31 inclusively. If any of this is not true, nil is returned.
:returns: NSData? The hashed password.
*/
private func hashPassword(password: NSData, withSalt salt: NSData, numberOfRounds: Int) -> NSData? {
var rounds : Int
var j : Int
let clen : Int = 6
var cdata : [Int32] = bf_crypt_ciphertext
if numberOfRounds < 4 || numberOfRounds > 31 {
// Invalid number of rounds
return nil
}
rounds = 1 << numberOfRounds
if salt.length != BCRYPT_SALT_LEN {
// Invalid salt length
return nil
}
self.initKey()
self.enhanceKeyScheduleWithData(salt, key: password)
for _ in 0 ..< rounds {
self.key(password)
self.key(salt)
}
for _ in 0 ..< 64 {
for j in 0 ..< (clen >> 1) {
self.encipher(&cdata, off: j << 1)
}
}
var result : [Int8] = [Int8](count:clen * 4, repeatedValue: 0)
j = 0
for i in 0..<clen {
result[j++] = Int8(truncatingBitPattern: (cdata[i] >> 24) & 0xff)
result[j++] = Int8(truncatingBitPattern: (cdata[i] >> 16) & 0xff)
result[j++] = Int8(truncatingBitPattern: (cdata[i] >> 8) & 0xff)
result[j++] = Int8(truncatingBitPattern: cdata[i] & 0xff)
}
deinitKey()
return NSData(bytes: result, length: result.count)
}
/**
Enciphers the provided array using the Blowfish algorithm.
:param: lr The left-right array containing two 32-bit half blocks.
:param: off The offset into the array.
:returns: <void>
*/
// private func encipher(inout lr: [Int32], off: Int) {
private func encipher(/*inout*/ lr: UnsafeMutablePointer<Int32>, off: Int) {
if off < 0 {
// Invalid offset.
return
}
var n : Int32
var l : Int32 = lr[off]
var r : Int32 = lr[off + 1]
l ^= p[0]
var i : Int = 0
while i <= BLOWFISH_NUM_ROUNDS - 2 {
// Feistel substitution on left word
n = s.advancedBy(Int((l >> 24) & 0xff)).memory
n = n &+ s.advancedBy(Int(0x100 | ((l >> 16) & 0xff))).memory
n ^= s.advancedBy(Int(0x200 | ((l >> 8) & 0xff))).memory
n = n &+ s.advancedBy(Int(0x300 | (l & 0xff))).memory
r ^= n ^ p.advancedBy(++i).memory
// Feistel substitution on right word
n = s.advancedBy(Int((r >> 24) & 0xff)).memory
n = n &+ s.advancedBy(Int(0x100 | ((r >> 16) & 0xff))).memory
n ^= s.advancedBy(Int(0x200 | ((r >> 8) & 0xff))).memory
n = n &+ s.advancedBy(Int(0x300 | (r & 0xff))).memory
l ^= n ^ p.advancedBy(++i).memory
}
lr[off] = r ^ p.advancedBy(BLOWFISH_NUM_ROUNDS + 1).memory
lr[off + 1] = l
}
/**
Initializes the blowfish key schedule.
:returns: <void>
*/
private func initKey() {
// p = P_orig
p = UnsafeMutablePointer<Int32>.alloc(P_orig.count)
p.initializeFrom(UnsafeMutablePointer<Int32>(P_orig), count: P_orig.count)
// s = S_orig
s = UnsafeMutablePointer<Int32>.alloc(S_orig.count)
s.initializeFrom(UnsafeMutablePointer<Int32>(S_orig), count: S_orig.count)
}
private func deinitKey() {
p.destroy()
p.dealloc(P_orig.count)
s.destroy()
s.dealloc(S_orig.count)
}
/**
Keys the receiver's blowfish cipher using the provided key.
:param: key The array containing the key.
:returns: <void>
*/
// private func key(key: NSData) {
private func key(key: NSData) {
var koffp : Int32 = 0
var lr : [Int32] = [0, 0]
// var lr : UnsafeMutablePointer<Int32> = UnsafeMutablePointer<Int32>.alloc(2)
// lr[0] = 0; lr[1] = 0
let plen : Int = 18
let slen : Int = 1024
let keyPointer : UnsafeMutablePointer<Int8> = UnsafeMutablePointer<Int8>(key.bytes)
let keyLength : Int = key.length
for i in 0 ..< plen {
p[i] = p[i] ^ JKBCrypt.streamToWordWithData(keyPointer, ofLength: keyLength, off: &koffp)
}
for i in 0 ..< plen {
self.encipher(&lr, off: 0)
p[i] = lr[0]
p[i + 1] = lr[1]
}
for i in 0 ..< slen {
self.encipher(&lr, off: 0)
s[i] = lr[0]
s[i + 1] = lr[1]
}
}
/**
Performs the "enhanced key schedule" step described by Provos and Mazieres
in "A Future-Adaptable Password Scheme"
http://www.openbsd.org/papers/bcrypt-paper.ps
:param: data The salt data.
:param: key The password data.
:returns: <void>
*/
private func enhanceKeyScheduleWithData(data: NSData, key: NSData) {
var koffp : Int32 = 0
var doffp : Int32 = 0
var lr : [Int32] = [0, 0]
// var lr : UnsafeMutablePointer<Int32> = UnsafeMutablePointer.alloc(2)
// lr[0] = 0; lr[1] = 0
let plen : Int = 18
let slen : Int = 1024
let keyPointer : UnsafeMutablePointer<Int8> = UnsafeMutablePointer<Int8>(key.bytes)
let keyLength : Int = key.length
let dataPointer : UnsafeMutablePointer<Int8> = UnsafeMutablePointer<Int8>(data.bytes)
let dataLength : Int = data.length
for i in 0 ..< plen {
p[i] = p[i] ^ JKBCrypt.streamToWordWithData(keyPointer, ofLength: keyLength, off:&koffp)
}
for var i in 0 ..< plen {
lr[0] ^= JKBCrypt.streamToWordWithData(dataPointer, ofLength: dataLength, off: &doffp)
lr[1] ^= JKBCrypt.streamToWordWithData(dataPointer, ofLength: dataLength, off: &doffp)
self.encipher(&lr, off: 0)
p[i] = lr[0]
p[i + 1] = lr[1]
i += 2
}
for var i in 0 ..< slen {
lr[0] ^= JKBCrypt.streamToWordWithData(dataPointer, ofLength: dataLength, off: &doffp)
lr[1] ^= JKBCrypt.streamToWordWithData(dataPointer, ofLength: dataLength, off: &doffp)
self.encipher(&lr, off: 0)
s[i] = lr[0]
s[i + 1] = lr[1]
i += 2
}
}
} | 60.910913 | 133 | 0.68465 |
e9074b0fcad5c2ede3bc7384a579159f8e7ace05 | 140 | import Foundation
struct Ean: Codable {
var ean: String
var name: String
var categoryId: String
var categoryName: String
}
| 15.555556 | 28 | 0.692857 |
db8a0bb63e198d6bbb8c42512b035cc585b8445d | 1,088 | //
// RandomNumberGenerator.swift
// WarCraft2
//
// Created by Keshav Tirumurti on 10/8/17.
// Copyright © 2017 UC Davis. All rights reserved.
//
import Foundation
class RandomNumberGenerator {
var DRandomSeedHigh: UInt32
var DRandomSeedLow: UInt32
init() {
DRandomSeedHigh = 0x0123_4567
DRandomSeedLow = 0x89AB_CDEF
}
// breaks the 64 int value into 2 32 bit numbers, and seeds
func Seed(seed: UInt64) {
Seed(high: UInt32(seed >> 32), low: UInt32(seed))
}
func Seed(high: UInt32, low: UInt32) {
// Added the 0 comparison to low and high because they can't be evaluated as Bool in Swift
if (high != low) && (low >= 0) && (high >= 0) {
DRandomSeedHigh = high
DRandomSeedLow = low
}
}
// Return a random
func Random() -> UInt32 {
DRandomSeedHigh = 36969 * (DRandomSeedHigh & 65535) + (DRandomSeedHigh >> 16)
DRandomSeedLow = 18000 * (DRandomSeedLow & 65535) + (DRandomSeedLow >> 16)
return (DRandomSeedHigh << 16) + DRandomSeedLow
}
}
| 27.2 | 98 | 0.615809 |
03e09b0f978a3e61607883dc206912ba3776ce1d | 7,635 | //
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
//
import XCTest
@testable import EmbeddedSocial
class SearchPresenterTests: XCTestCase {
var interactor: MockSearchInteractor!
var view: MockSearchView!
var peopleSearchModule: MockSearchPeopleModule!
var topicsSearchModule: MockSearchTopicsModule!
var sut: SearchPresenter!
override func setUp() {
super.setUp()
interactor = MockSearchInteractor()
view = MockSearchView()
peopleSearchModule = MockSearchPeopleModule()
topicsSearchModule = MockSearchTopicsModule()
sut = SearchPresenter()
sut.interactor = interactor
sut.view = view
sut.peopleSearchModule = peopleSearchModule
sut.topicsSearchModule = topicsSearchModule
}
override func tearDown() {
super.tearDown()
interactor = nil
view = nil
peopleSearchModule = nil
topicsSearchModule = nil
sut = nil
}
func testThatItSetsInitialState() {
// given
interactor.makeTopicsTabWithReturnValue = makeTopicsTab()
interactor.makePeopleTabWithReturnValue = makePeopleTab()
topicsSearchModule.layoutAsset = .iconAccept
// when
sut.viewIsReady()
// then
// people search module is initialized
XCTAssertEqual(peopleSearchModule.setupInitialStateCount, 1)
// search tabs are correctly set
XCTAssertTrue(interactor.makeTopicsTabWithCalled)
XCTAssertTrue(interactor.makePeopleTabWithCalled)
XCTAssertTrue(interactor.makeTopicsTabWithReceivedSearchTopicsModule === topicsSearchModule)
XCTAssertTrue(interactor.makePeopleTabWithReceivedSearchPeopleModule === peopleSearchModule)
// view is correctly initialized
XCTAssertTrue(view.setupInitialStateCalled)
XCTAssertTrue(view.setLayoutAssetCalled)
XCTAssertEqual(view.setLayoutAssetReceivedAsset, topicsSearchModule.layoutAsset)
XCTAssertEqual(interactor.makeTopicsTabWithReturnValue, view.setupInitialStateReceivedTab)
}
func testThatItSwitchesToPeopleTab() {
// given
let peopleTab = makePeopleTab()
let topicsTab = makeTopicsTab()
interactor.makeTopicsTabWithReturnValue = topicsTab
interactor.makePeopleTabWithReturnValue = peopleTab
// when
sut.viewIsReady()
sut.onPeople()
// then
XCTAssertTrue(view.switchTabsToFromCalled)
XCTAssertEqual(view.switchTabsToFromReceivedArguments?.tab, peopleTab)
XCTAssertEqual(view.switchTabsToFromReceivedArguments?.previousTab, topicsTab)
}
func testThatItSwitchesToTopicsTab() {
// given
let peopleTab = makePeopleTab()
let topicsTab = makeTopicsTab()
interactor.makeTopicsTabWithReturnValue = topicsTab
interactor.makePeopleTabWithReturnValue = peopleTab
// when
sut.viewIsReady()
sut.onPeople()
sut.onTopics()
// then
XCTAssertTrue(view.switchTabsToFromCalled)
XCTAssertEqual(view.switchTabsToFromReceivedArguments?.tab, topicsTab)
XCTAssertEqual(view.switchTabsToFromReceivedArguments?.previousTab, peopleTab)
}
func testThatItFlipsLayoutForTopicsTab() {
// given
let peopleTab = makePeopleTab()
let topicsTab = makeTopicsTab()
let asset = Asset.iconAccept
interactor.makeTopicsTabWithReturnValue = topicsTab
interactor.makePeopleTabWithReturnValue = peopleTab
topicsSearchModule.layoutAsset = asset
// when
sut.viewIsReady()
sut.onFlipTopicsLayout()
// then
XCTAssertTrue(topicsSearchModule.flipLayoutCalled)
XCTAssertTrue(view.setLayoutAssetCalled)
XCTAssertEqual(view.setLayoutAssetReceivedAsset, asset)
}
func testThatItShowsErrorWhenUserListFailsToLoad() {
// given
let error = APIError.unknown
// when
sut.didFailToLoadSearchQuery(error)
// then
XCTAssertTrue(view.showErrorCalled)
guard let shownError = view.showErrorReceivedError as? APIError, case .unknown = shownError else {
XCTFail("Error must be shown")
return
}
}
func testThatItUsesPeopleTabIfItWasSelectedBeforeViewHasBeenLoaded() {
// given
let peopleTab = makePeopleTab()
let topicsTab = makeTopicsTab()
interactor.makeTopicsTabWithReturnValue = topicsTab
interactor.makePeopleTabWithReturnValue = peopleTab
// when
sut.selectPeopleTab()
sut.viewIsReady()
// then
XCTAssertEqual(view.setupInitialStateReceivedTab, peopleTab)
}
func testThatItStartsSearchWithSelectedHashtag() {
let hashtag = UUID().uuidString
sut.didSelectHashtag(hashtag)
XCTAssertTrue(view.searchHashtagCalled)
XCTAssertEqual(view.searchHashtagReceivedHashtag, hashtag)
}
private func makePeopleTab() -> SearchTabInfo {
return SearchTabInfo(searchResultsController: UIViewController(),
searchResultsHandler: MockSearchResultsUpdating(),
backgroundView: nil,
tab: .people)
}
private func makeTopicsTab() -> SearchTabInfo {
return SearchTabInfo(searchResultsController: UIViewController(),
searchResultsHandler: MockSearchResultsUpdating(),
backgroundView: nil,
tab: .topics)
}
func testSearchHashtagBeforeViewIsReady() {
let topicsTab = makeTopicsTab()
interactor.makeTopicsTabWithReturnValue = topicsTab
interactor.makePeopleTabWithReturnValue = makePeopleTab()
sut.search(hashtag: "1")
sut.viewIsReady()
XCTAssertEqual(view.setupInitialStateReceivedTab, topicsTab)
XCTAssertTrue(view.searchHashtagCalled)
XCTAssertEqual(view.searchHashtagReceivedHashtag, "1")
}
func testSearchHashtagAfterViewIsReadyAndPeopleTabSelected() {
let topicsTab = makeTopicsTab()
let peopleTab = makePeopleTab()
interactor.makeTopicsTabWithReturnValue = topicsTab
interactor.makePeopleTabWithReturnValue = peopleTab
sut.selectPeopleTab()
sut.viewIsReady()
sut.search(hashtag: "1")
XCTAssertEqual(view.setupInitialStateReceivedTab, peopleTab)
XCTAssertTrue(view.switchTabsToFromCalled)
XCTAssertEqual(view.switchTabsToFromReceivedArguments?.previousTab, peopleTab)
XCTAssertEqual(view.switchTabsToFromReceivedArguments?.tab, topicsTab)
XCTAssertTrue(view.searchHashtagCalled)
XCTAssertEqual(view.searchHashtagReceivedHashtag, "1")
}
func testStartLoadingTopicsQuery() {
sut.didStartLoadingSearchTopicsQuery()
XCTAssertTrue(view.setTopicsLayoutFlipEnabledCalled)
XCTAssertEqual(view.setTopicsLayoutFlipEnabledReceivedIsEnabled, false)
}
func testFinishLoadingTopicsQuery() {
sut.didLoadSearchTopicsQuery()
XCTAssertTrue(view.setTopicsLayoutFlipEnabledCalled)
XCTAssertEqual(view.setTopicsLayoutFlipEnabledReceivedIsEnabled, true)
}
}
| 35.022936 | 106 | 0.6685 |
91407792a0a9111e5de5b8335173a432c670dbeb | 5,003 | /// Copyright (c) 2022 Razeware LLC
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
/// distribute, sublicense, create a derivative work, and/or sell copies of the
/// Software in any work that is designed, intended, or marketed for pedagogical or
/// instructional purposes related to programming, coding, application development,
/// or information technology. Permission for such use, copying, modification,
/// merger, publication, distribution, sublicensing, creation of derivative works,
/// or sale is expressly withheld.
///
/// This project and source code may use libraries or frameworks that are
/// released under various Open-Source licenses. Use of those libraries and
/// frameworks are governed by their own individual licenses.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
import MetalKit
struct FlockingPass {
var particleCount = 100
let clearScreenPSO = PipelineStates.createComputePSO(function: "clearScreen")
let boidsPSO = PipelineStates.createComputePSO(function: "boids")
var emitter: Emitter?
mutating func resize(view: MTKView, size: CGSize) {
emitter = Emitter(
particleCount: particleCount,
size: size)
}
func clearScreen(
commandEncoder: MTLComputeCommandEncoder,
texture: MTLTexture
) {
commandEncoder.setComputePipelineState(clearScreenPSO)
commandEncoder.setTexture(texture, index: 0)
let width = clearScreenPSO.threadExecutionWidth
let height = clearScreenPSO.maxTotalThreadsPerThreadgroup / width
var threadsPerGroup = MTLSize(
width: width, height: height, depth: 1)
var threadsPerGrid = MTLSize(
width: texture.width, height: texture.height, depth: 1)
#if os(iOS)
if Renderer.device.supportsFeatureSet(.iOS_GPUFamily4_v1) {
commandEncoder.dispatchThreads(
threadsPerGrid,
threadsPerThreadgroup: threadsPerGroup)
} else {
let width = (Float(texture.width) / Float(width)).rounded(.up)
let height = (Float(texture.height) / Float(height)).rounded(.up)
let groupsPerGrid = MTLSize(
width: Int(width), height: Int(height), depth: 1)
commandEncoder.dispatchThreadgroups(
groupsPerGrid,
threadsPerThreadgroup: threadsPerGroup)
}
#elseif os(macOS)
commandEncoder.dispatchThreads(
threadsPerGrid,
threadsPerThreadgroup: threadsPerGroup)
#endif
}
mutating func draw(in view: MTKView, commandBuffer: MTLCommandBuffer) {
guard let commandEncoder = commandBuffer.makeComputeCommandEncoder(),
let texture = view.currentDrawable?.texture,
let emitter = emitter
else { return }
clearScreen(
commandEncoder: commandEncoder,
texture: texture)
// render boids
commandEncoder.setComputePipelineState(boidsPSO)
let threadsPerGrid = MTLSize(
width: particleCount, height: 1, depth: 1)
let threadsPerGroup = MTLSize(width: 1, height: 1, depth: 1)
commandEncoder.setBuffer(
emitter.particleBuffer, offset: 0, index: 0)
commandEncoder.setBytes(
&particleCount,
length: MemoryLayout<Int>.stride,
index: 1)
#if os(iOS)
if Renderer.device.supportsFeatureSet(.iOS_GPUFamily4_v1) {
commandEncoder.dispatchThreads(
threadsPerGrid,
threadsPerThreadgroup: threadsPerGroup)
} else {
let threads = min(
boidsPSO.threadExecutionWidth,
particleCount)
let threadsPerThreadgroup = MTLSize(
width: threads, height: 1, depth: 1)
let groups = particleCount / threads + 1
let groupsPerGrid = MTLSize(
width: groups, height: 1, depth: 1)
commandEncoder.dispatchThreadgroups(
groupsPerGrid,
threadsPerThreadgroup: threadsPerThreadgroup)
}
#elseif os(macOS)
commandEncoder.dispatchThreads(
threadsPerGrid,
threadsPerThreadgroup: threadsPerGroup)
#endif
commandEncoder.endEncoding()
}
}
| 39.393701 | 83 | 0.719568 |
1a05d369710cad15b8ddc68667f98332a7739d91 | 344 | //
// FifthViewController.swift
// NavigationStackDemo
//
// Created by Alex K. on 29/02/16.
// Copyright © 2016 Alex K. All rights reserved.
//
import UIKit
class FifthViewController: UITableViewController {
@IBAction func backHandler(_ sender: AnyObject) {
let _ = navigationController?.popViewController(animated: true)
}
}
| 20.235294 | 67 | 0.72093 |
4bb20d2ab1073a5b74455b0fb23c88498072c4de | 110 | import UIKit
/// :nodoc:
public protocol EquatableRows {
func rowsEqual(object: EquatableRows) -> Bool
}
| 15.714286 | 49 | 0.718182 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.