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
|
---|---|---|---|---|---|
46cd0f03b773453872eaa7465a4873fcfa9459ed | 976 | //
// ShazamRow.swift
// ShazamKit-Demo
//
// Created by Aaryan Kothari on 09/06/21.
//
import SwiftUI
struct ShazamRow: View {
let media: SHMedia
var body: some View {
HStack {
AsyncImage(url: media.image) { image in
image.resizable()
.frame(width: 100, height: 100)
.clipShape(RoundedRectangle(cornerRadius: 7))
} placeholder: {
Color.secondary
.frame(width: 100, height: 100)
}
VStack(alignment:.leading,spacing:10) {
Text(media.name)
.font(.title3)
.bold()
Text(media.artist)
.font(.callout)
}
.padding()
}
}
}
struct ShazamRow_Previews: PreviewProvider {
static var previews: some View {
ShazamRow(media: SHMedia.data)
.previewLayout(.sizeThatFits)
}
}
| 24.4 | 65 | 0.492828 |
261327c21ad3dda189c1ea8b16b9aa4e9810aad0 | 475 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
import c
struct S<T where g:A{
class a{
let t:b)class b{var f=b{n C{}}
let t
| 33.928571 | 79 | 0.738947 |
3a3e92105925454f99f8c10cbf3b13990cda824c | 238 | public class Axis<T,U>{
public var scaleX: Float = 1
public var scaleY: Float = 1
public var series = [Series<T,U>]()
public init(){}
public enum Location {
case primaryAxis
case secondaryAxis
}
}
| 19.833333 | 39 | 0.596639 |
091e9324162752343cee2243ac30e37e871ac257 | 8,530 | //
// TwitterServiceClient.swift
// TwitterClient
//
// Created by Robert Xue on 11/8/15.
// Copyright © 2015 roboxue. All rights reserved.
//
import Foundation
import BDBOAuth1Manager
import Alamofire
import SwiftSpinner
import AlamofireImage
private let twitterConsumerKey = "K9ryTdR2ukcBMY3VKhacHRrJb"
private let twitterConsumerSecret = "R8r4Om9WRL9A4ouHJjJ1U2F6FaIkviK14N7ddFM1tpmLsyorA5"
private let twitterBaseUrl = NSURL(string: "https://api.twitter.com")!
let oauthTokenUserDefaultsKey = "oauth_token"
let oauthTokenSecretUserDefaultsKey = "oauth_token_secret"
let userIdDefaultKey = "user_id"
class TwitterServiceClient: BDBOAuth1RequestOperationManager {
private let downloader = ImageDownloader(configuration: ImageDownloader.defaultURLSessionConfiguration(), downloadPrioritization: .FIFO, maximumActiveDownloads: 5, imageCache: AutoPurgingImageCache())
private var _userIdentifier: Int?
private(set) var userIdentifier: Int! {
get {
let defaults = NSUserDefaults.standardUserDefaults()
let id = defaults.integerForKey(userIdDefaultKey)
if id != 0 {
_userIdentifier = id
}
return _userIdentifier
}
set {
_userIdentifier = newValue
if let id = newValue {
NSUserDefaults.standardUserDefaults().setInteger(id, forKey: userIdDefaultKey)
} else {
NSUserDefaults.standardUserDefaults().removeObjectForKey(userIdDefaultKey)
}
}
}
private var loginCompletion: ((User?, NSError?) -> Void)!
var currentUser: User? {
didSet {
userIdentifier = currentUser?.id
}
}
var oauthCredential: BDBOAuth1Credential? {
if let token = NSUserDefaults.standardUserDefaults().stringForKey(oauthTokenUserDefaultsKey), secret = NSUserDefaults.standardUserDefaults().stringForKey(oauthTokenSecretUserDefaultsKey) {
return BDBOAuth1Credential(token: token, secret: secret, expiration: nil)
} else {
return nil
}
}
func loginWithCompletion(completion: (User?, NSError?) -> Void) {
loginCompletion = completion
getRequestToken { (url, _) -> Void in
if let authURL = url {
UIApplication.sharedApplication().openURL(authURL)
}
}
}
func getAccessToken(url: NSURL) {
fetchAccessTokenWithPath("oauth/access_token", method: "POST", requestToken: BDBOAuth1Credential(queryString: url.query), success: { (credential) -> Void in
NSUserDefaults.standardUserDefaults().setObject(credential.token, forKey: oauthTokenUserDefaultsKey)
NSUserDefaults.standardUserDefaults().setObject(credential.secret, forKey: oauthTokenSecretUserDefaultsKey)
self.recoverUserSession()
let handler = { (user: User?, error: NSError?) -> Void in
if let user = user {
self.currentUser = user
}
}
self.verifyCredentials(handler)
}) { (error) -> Void in
self.handleError("get access token", error: error)
}
}
func recoverUserSession() {
self.requestSerializer.saveAccessToken(oauthCredential)
}
func updateStatus(tweet: String, replyTo: Int? = nil, completion: (Tweet?, NSError?) -> Void) {
var payload = ["status": tweet]
if let replyTo = replyTo {
payload["in_reply_to_status_id"] = String(replyTo)
}
POST("1.1/statuses/update.json", parameters: payload, success: { (operation, response) -> Void in
let tweet = Tweet(dictionary: response as! NSDictionary)
completion(tweet, nil)
}) { (operation, error) -> Void in
self.handleError("update status", error: error)
completion(nil, error)
}
}
func favorite(create: Bool, id: Int, completion: (Tweet?, NSError?) -> Void) {
let payload = ["id": String(id)]
let url = create ? "1.1/favorites/create.json" : "1.1/favorites/destroy.json"
POST(url, parameters: payload, success: { (operation, response) -> Void in
let tweet = Tweet(dictionary: response as! NSDictionary)
completion(tweet, nil)
}) { (operation, error) -> Void in
self.handleError(create ? "fav tweet" : "un-fav tweet", error: error)
completion(nil, error)
}
}
func retweet(id: Int, completion: (Tweet?, NSError?) -> Void) {
let url = "1.1/statuses/retweet/\(id).json"
POST(url, parameters: nil, success: { (operation, response) -> Void in
let tweet = Tweet(dictionary: response as! NSDictionary)
completion(tweet, nil)
}) { (operation, error) -> Void in
self.handleError("retweet", error: error)
completion(nil, error)
}
}
func showUser(id: Int, completion: (User?, NSError?) -> Void) {
GET("1.1/users/show.json", parameters: ["user_id": id], success: { (operation, response) -> Void in
let user = User(dictionary: response as! NSDictionary)
completion(user, nil)
}) { (operation, error) -> Void in
self.handleError("showUser", error: error)
completion(nil, error)
}
}
func logout() {
userIdentifier = nil
NSUserDefaults.standardUserDefaults().removeObjectForKey(oauthTokenUserDefaultsKey)
NSUserDefaults.standardUserDefaults().removeObjectForKey(oauthTokenSecretUserDefaultsKey)
requestSerializer.removeAccessToken()
}
func getTimeline(source: TwitterTimelineSource, since_id: Int? = nil, max_id: Int? = nil, completion: ([Tweet]?, NSError?) -> Void) {
var parameters = ["count": "20"]
if let max_id = max_id {
parameters["max_id"] = String(max_id)
}
if let since_id = since_id {
parameters["since_id"] = String(since_id)
}
GET(source.url, parameters: parameters, success: { (operation, response) -> Void in
let tweets = Tweet.tweets(response as! [NSDictionary])
completion(tweets, nil)
}) { (operation, error) -> Void in
completion(nil, error)
}
}
func fetchImage(URL: NSURL, completion: (UIImage?, NSError?) -> Void) {
downloader.downloadImage(URLRequest: NSURLRequest(URL: URL)) { (response) -> Void in
if let image = response.result.value {
completion(image, nil)
} else {
completion(nil, response.result.error!)
}
}
}
private func getRequestToken(completion: (NSURL?, NSError?) -> Void) {
fetchRequestTokenWithPath("oauth/request_token", method: "GET", callbackURL: NSURL(string: "rxtwitter://oauth"), scope: nil, success: { (requestToken) -> Void in
completion(NSURL(string: "https://api.twitter.com/oauth/authorize?oauth_token=\(requestToken.token)"), nil)
}) { (error) -> Void in
self.handleError("get request token", error: error)
completion(nil, error)
}
}
private func verifyCredentials(completion: (User?, NSError?) -> Void) {
self.GET("1.1/account/verify_credentials.json", parameters: nil, success: { (operation, response) -> Void in
let user = User(dictionary: response as! NSDictionary)
self.userIdentifier = user.id!
completion(user, nil)
}) { (operation, error) -> Void in
self.handleError("verify credential", error: error)
completion(nil, error)
}
}
private func handleError(operationName: String, error: NSError) {
debugPrint(error)
SwiftSpinner.show("Encountered exception during \(operationName)", animated: true).addTapHandler({ () -> () in
SwiftSpinner.hide()
}, subtitle: error.localizedFailureReason)
}
}
let TWApi = TwitterServiceClient(baseURL: twitterBaseUrl, consumerKey: twitterConsumerKey, consumerSecret: twitterConsumerSecret)
enum TwitterTimelineSource {
case Mentions
case Home
var url: String {
switch self {
case .Mentions:
return "1.1/statuses/mentions_timeline.json"
case .Home:
return "1.1/statuses/home_timeline.json"
}
}
} | 40.235849 | 204 | 0.616999 |
8f7641e6728c1cfcfe95103352777e511a6d959e | 3,361 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2021 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import SotoCore
/// Error enum for ElasticTranscoder
public struct ElasticTranscoderErrorType: AWSErrorType {
enum Code: String {
case accessDeniedException = "AccessDeniedException"
case incompatibleVersionException = "IncompatibleVersionException"
case internalServiceException = "InternalServiceException"
case limitExceededException = "LimitExceededException"
case resourceInUseException = "ResourceInUseException"
case resourceNotFoundException = "ResourceNotFoundException"
case validationException = "ValidationException"
}
private let error: Code
public let context: AWSErrorContext?
/// initialize ElasticTranscoder
public init?(errorCode: String, context: AWSErrorContext) {
guard let error = Code(rawValue: errorCode) else { return nil }
self.error = error
self.context = context
}
internal init(_ error: Code) {
self.error = error
self.context = nil
}
/// return error code string
public var errorCode: String { self.error.rawValue }
/// General authentication failure. The request was not signed correctly.
public static var accessDeniedException: Self { .init(.accessDeniedException) }
public static var incompatibleVersionException: Self { .init(.incompatibleVersionException) }
/// Elastic Transcoder encountered an unexpected exception while trying to fulfill the request.
public static var internalServiceException: Self { .init(.internalServiceException) }
/// Too many operations for a given AWS account. For example, the number of pipelines exceeds the maximum allowed.
public static var limitExceededException: Self { .init(.limitExceededException) }
/// The resource you are attempting to change is in use. For example, you are attempting to delete a pipeline that is currently in use.
public static var resourceInUseException: Self { .init(.resourceInUseException) }
/// The requested resource does not exist or is not available. For example, the pipeline to which you're trying to add a job doesn't exist or is still being created.
public static var resourceNotFoundException: Self { .init(.resourceNotFoundException) }
/// One or more required parameter values were not provided in the request.
public static var validationException: Self { .init(.validationException) }
}
extension ElasticTranscoderErrorType: Equatable {
public static func == (lhs: ElasticTranscoderErrorType, rhs: ElasticTranscoderErrorType) -> Bool {
lhs.error == rhs.error
}
}
extension ElasticTranscoderErrorType: CustomStringConvertible {
public var description: String {
return "\(self.error.rawValue): \(self.message ?? "")"
}
}
| 44.813333 | 169 | 0.700684 |
878e45657985b63b1c0273be9c78fbe7ed507fe2 | 368 | /// Errors working with the `Console` module.
public struct ConsoleError: Error {
/// See `Debuggable`.
public let identifier: String
/// See `Debuggable`.
public let reason: String
/// Creates a new `ConsoleError`
internal init(identifier: String, reason: String) {
self.identifier = identifier
self.reason = reason
}
}
| 23 | 55 | 0.644022 |
e66253c15993b53d56f2eb92bffac04a08f6b5fa | 615 | //
// Jelly-Animators
// Created by Sebastian Boldt on 17.11.16.
import UIKit
class DismissMeController: UIViewController {
var interactionAction: (() -> ())?
override func viewDidLoad() {
super.viewDidLoad()
modalPresentationCapturesStatusBarAppearance = true
}
@IBAction func actionButtonPressed(_ sender: Any) {
if let interactionAction = interactionAction {
interactionAction()
} else {
self.dismiss(animated: true, completion: nil)
}
}
override var prefersStatusBarHidden: Bool {
return true
}
}
| 23.653846 | 59 | 0.629268 |
bb81d8e11d24a9c91795bc7ed37e523251dc8b09 | 364 | //
// MyTestLib.swift
// MyTestLib
//
// Created by Ronny Antony on 08/06/21.
//
import Foundation
public final class MyTestLib {
let name = "MyTestLib"
public init() {
}
public func add(a: Int, b: Int) -> Int {
return a + b
}
public func sub(a: Int, b: Int) -> Int {
return a - b
}
}
| 13.481481 | 44 | 0.5 |
6a0ebcead3780556207e49d6ce9a0fdef23f0ce8 | 29,083 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import XCTest
@testable import NIOCore
@testable import NIOPosix
import NIOConcurrencyHelpers
extension System {
static var supportsIPv6: Bool {
do {
let ipv6Loopback = try SocketAddress.makeAddressResolvingHost("::1", port: 0)
return try System.enumerateDevices().filter { $0.address == ipv6Loopback }.first != nil
} catch {
return false
}
}
}
func withPipe(_ body: (NIOCore.NIOFileHandle, NIOCore.NIOFileHandle) throws -> [NIOCore.NIOFileHandle]) throws {
var fds: [Int32] = [-1, -1]
fds.withUnsafeMutableBufferPointer { ptr in
XCTAssertEqual(0, pipe(ptr.baseAddress!))
}
let readFH = NIOFileHandle(descriptor: fds[0])
let writeFH = NIOFileHandle(descriptor: fds[1])
var toClose: [NIOFileHandle] = [readFH, writeFH]
var error: Error? = nil
do {
toClose = try body(readFH, writeFH)
} catch let err {
error = err
}
try toClose.forEach { fh in
XCTAssertNoThrow(try fh.close())
}
if let error = error {
throw error
}
}
func withTemporaryDirectory<T>(_ body: (String) throws -> T) rethrows -> T {
let dir = createTemporaryDirectory()
defer {
try? FileManager.default.removeItem(atPath: dir)
}
return try body(dir)
}
/// This function creates a filename that can be used for a temporary UNIX domain socket path.
///
/// If the temporary directory is too long to store a UNIX domain socket path, it will `chdir` into the temporary
/// directory and return a short-enough path. The iOS simulator is known to have too long paths.
func withTemporaryUnixDomainSocketPathName<T>(directory: String = temporaryDirectory,
_ body: (String) throws -> T) throws -> T {
// this is racy but we're trying to create the shortest possible path so we can't add a directory...
let (fd, path) = openTemporaryFile()
try! Posix.close(descriptor: fd)
try! FileManager.default.removeItem(atPath: path)
let saveCurrentDirectory = FileManager.default.currentDirectoryPath
let restoreSavedCWD: Bool
let shortEnoughPath: String
do {
_ = try SocketAddress(unixDomainSocketPath: path)
// this seems to be short enough for a UDS
shortEnoughPath = path
restoreSavedCWD = false
} catch SocketAddressError.unixDomainSocketPathTooLong {
FileManager.default.changeCurrentDirectoryPath(URL(fileURLWithPath: path).deletingLastPathComponent().absoluteString)
shortEnoughPath = URL(fileURLWithPath: path).lastPathComponent
restoreSavedCWD = true
print("WARNING: Path '\(path)' could not be used as UNIX domain socket path, using chdir & '\(shortEnoughPath)'")
}
defer {
if FileManager.default.fileExists(atPath: path) {
try? FileManager.default.removeItem(atPath: path)
}
if restoreSavedCWD {
FileManager.default.changeCurrentDirectoryPath(saveCurrentDirectory)
}
}
return try body(shortEnoughPath)
}
func withTemporaryFile<T>(content: String? = nil, _ body: (NIOCore.NIOFileHandle, String) throws -> T) rethrows -> T {
let (fd, path) = openTemporaryFile()
let fileHandle = NIOFileHandle(descriptor: fd)
defer {
XCTAssertNoThrow(try fileHandle.close())
XCTAssertEqual(0, unlink(path))
}
if let content = content {
try Array(content.utf8).withUnsafeBufferPointer { ptr in
var toWrite = ptr.count
var start = ptr.baseAddress!
while toWrite > 0 {
let res = try Posix.write(descriptor: fd, pointer: start, size: toWrite)
switch res {
case .processed(let written):
toWrite -= written
start = start + written
case .wouldBlock:
XCTFail("unexpectedly got .wouldBlock from a file")
continue
}
}
XCTAssertEqual(0, lseek(fd, 0, SEEK_SET))
}
}
return try body(fileHandle, path)
}
var temporaryDirectory: String {
get {
#if targetEnvironment(simulator)
// Simulator temp directories are so long (and contain the user name) that they're not usable
// for UNIX Domain Socket paths (which are limited to 103 bytes).
return "/tmp"
#else
#if os(Linux)
return "/tmp"
#else
if #available(macOS 10.12, iOS 10, tvOS 10, watchOS 3, *) {
return FileManager.default.temporaryDirectory.path
} else {
return "/tmp"
}
#endif // os
#endif // targetEnvironment
}
}
func createTemporaryDirectory() -> String {
let template = "\(temporaryDirectory)/.NIOTests-temp-dir_XXXXXX"
var templateBytes = template.utf8 + [0]
let templateBytesCount = templateBytes.count
templateBytes.withUnsafeMutableBufferPointer { ptr in
ptr.baseAddress!.withMemoryRebound(to: Int8.self, capacity: templateBytesCount) { (ptr: UnsafeMutablePointer<Int8>) in
let ret = mkdtemp(ptr)
XCTAssertNotNil(ret)
}
}
templateBytes.removeLast()
return String(decoding: templateBytes, as: Unicode.UTF8.self)
}
func openTemporaryFile() -> (CInt, String) {
let template = "\(temporaryDirectory)/nio_XXXXXX"
var templateBytes = template.utf8 + [0]
let templateBytesCount = templateBytes.count
let fd = templateBytes.withUnsafeMutableBufferPointer { ptr in
ptr.baseAddress!.withMemoryRebound(to: Int8.self, capacity: templateBytesCount) { (ptr: UnsafeMutablePointer<Int8>) in
return mkstemp(ptr)
}
}
templateBytes.removeLast()
return (fd, String(decoding: templateBytes, as: Unicode.UTF8.self))
}
extension Channel {
func syncCloseAcceptingAlreadyClosed() throws {
do {
try self.close().wait()
} catch ChannelError.alreadyClosed {
/* we're happy with this one */
} catch let e {
throw e
}
}
}
final class ByteCountingHandler : ChannelInboundHandler, RemovableChannelHandler {
typealias InboundIn = ByteBuffer
private let numBytes: Int
private let promise: EventLoopPromise<ByteBuffer>
private var buffer: ByteBuffer!
init(numBytes: Int, promise: EventLoopPromise<ByteBuffer>) {
self.numBytes = numBytes
self.promise = promise
}
func handlerAdded(context: ChannelHandlerContext) {
buffer = context.channel.allocator.buffer(capacity: numBytes)
if self.numBytes == 0 {
self.promise.succeed(buffer)
}
}
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
var currentBuffer = self.unwrapInboundIn(data)
buffer.writeBuffer(¤tBuffer)
if buffer.readableBytes == numBytes {
promise.succeed(buffer)
}
}
func assertReceived(buffer: ByteBuffer) throws {
let received = try promise.futureResult.wait()
XCTAssertEqual(buffer, received)
}
}
final class NonAcceptingServerSocket: ServerSocket {
private var errors: [Int32]
init(errors: [Int32]) throws {
// Reverse so it's cheaper to remove errors.
self.errors = errors.reversed()
try super.init(protocolFamily: .inet, setNonBlocking: true)
}
override func accept(setNonBlocking: Bool) throws -> Socket? {
if let err = self.errors.last {
_ = self.errors.removeLast()
throw IOError(errnoCode: err, reason: "accept")
}
return nil
}
}
func assertSetGetOptionOnOpenAndClosed<Option: ChannelOption>(channel: Channel, option: Option, value: Option.Value) throws {
_ = try channel.setOption(option, value: value).wait()
_ = try channel.getOption(option).wait()
try channel.close().wait()
try channel.closeFuture.wait()
do {
_ = try channel.setOption(option, value: value).wait()
// We're okay with no error
} catch let err as ChannelError where err == .ioOnClosedChannel {
// as well as already closed channels.
}
do {
_ = try channel.getOption(option).wait()
// We're okay with no error
} catch let err as ChannelError where err == .ioOnClosedChannel {
// as well as already closed channels.
}
}
func assertNoThrowWithValue<T>(_ body: @autoclosure () throws -> T, defaultValue: T? = nil, message: String? = nil, file: StaticString = #file, line: UInt = #line) throws -> T {
do {
return try body()
} catch {
XCTFail("\(message.map { $0 + ": " } ?? "")unexpected error \(error) thrown", file: (file), line: line)
if let defaultValue = defaultValue {
return defaultValue
} else {
throw error
}
}
}
func resolverDebugInformation(eventLoop: EventLoop, host: String, previouslyReceivedResult: SocketAddress) throws -> String {
func printSocketAddress(_ socketAddress: SocketAddress) -> String {
switch socketAddress {
case .unixDomainSocket(_):
return "uds"
case .v4(let sa):
var addr = sa.address
return addr.addressDescription()
case .v6(let sa):
var addr = sa.address
return addr.addressDescription()
}
}
let res = GetaddrinfoResolver(loop: eventLoop, aiSocktype: .stream, aiProtocol: CInt(IPPROTO_TCP))
let ipv6Results = try assertNoThrowWithValue(res.initiateAAAAQuery(host: host, port: 0).wait()).map(printSocketAddress)
let ipv4Results = try assertNoThrowWithValue(res.initiateAQuery(host: host, port: 0).wait()).map(printSocketAddress)
return """
when trying to resolve '\(host)' we've got the following results:
- previous try: \(printSocketAddress(previouslyReceivedResult))
- all results:
IPv4: \(ipv4Results)
IPv6: \(ipv6Results)
"""
}
func assert(_ condition: @autoclosure () -> Bool, within time: TimeAmount, testInterval: TimeAmount? = nil, _ message: String = "condition not satisfied in time", file: StaticString = #file, line: UInt = #line) {
let testInterval = testInterval ?? TimeAmount.nanoseconds(time.nanoseconds / 5)
let endTime = NIODeadline.now() + time
repeat {
if condition() { return }
usleep(UInt32(testInterval.nanoseconds / 1000))
} while (NIODeadline.now() < endTime)
if !condition() {
XCTFail(message, file: (file), line: line)
}
}
func getBoolSocketOption(channel: Channel, level: NIOBSDSocket.OptionLevel, name: NIOBSDSocket.Option,
file: StaticString = #file, line: UInt = #line) throws -> Bool {
return try assertNoThrowWithValue(channel.getOption(ChannelOptions.Types.SocketOption(level: level, name: name)), file: (file), line: line).wait() != 0
}
func assertSuccess<Value>(_ result: Result<Value, Error>, file: StaticString = #file, line: UInt = #line) {
guard case .success = result else { return XCTFail("Expected result to be successful", file: (file), line: line) }
}
func assertFailure<Value>(_ result: Result<Value, Error>, file: StaticString = #file, line: UInt = #line) {
guard case .failure = result else { return XCTFail("Expected result to be a failure", file: (file), line: line) }
}
/// Fulfills the promise when the respective event is first received.
///
/// - note: Once this is used more widely and shows value, we might want to put it into `NIOTestUtils`.
final class FulfillOnFirstEventHandler: ChannelDuplexHandler {
typealias InboundIn = Any
typealias OutboundIn = Any
struct ExpectedEventMissing: Error {}
private let channelRegisteredPromise: EventLoopPromise<Void>?
private let channelUnregisteredPromise: EventLoopPromise<Void>?
private let channelActivePromise: EventLoopPromise<Void>?
private let channelInactivePromise: EventLoopPromise<Void>?
private let channelReadPromise: EventLoopPromise<Void>?
private let channelReadCompletePromise: EventLoopPromise<Void>?
private let channelWritabilityChangedPromise: EventLoopPromise<Void>?
private let userInboundEventTriggeredPromise: EventLoopPromise<Void>?
private let errorCaughtPromise: EventLoopPromise<Void>?
private let registerPromise: EventLoopPromise<Void>?
private let bindPromise: EventLoopPromise<Void>?
private let connectPromise: EventLoopPromise<Void>?
private let writePromise: EventLoopPromise<Void>?
private let flushPromise: EventLoopPromise<Void>?
private let readPromise: EventLoopPromise<Void>?
private let closePromise: EventLoopPromise<Void>?
private let triggerUserOutboundEventPromise: EventLoopPromise<Void>?
init(channelRegisteredPromise: EventLoopPromise<Void>? = nil,
channelUnregisteredPromise: EventLoopPromise<Void>? = nil,
channelActivePromise: EventLoopPromise<Void>? = nil,
channelInactivePromise: EventLoopPromise<Void>? = nil,
channelReadPromise: EventLoopPromise<Void>? = nil,
channelReadCompletePromise: EventLoopPromise<Void>? = nil,
channelWritabilityChangedPromise: EventLoopPromise<Void>? = nil,
userInboundEventTriggeredPromise: EventLoopPromise<Void>? = nil,
errorCaughtPromise: EventLoopPromise<Void>? = nil,
registerPromise: EventLoopPromise<Void>? = nil,
bindPromise: EventLoopPromise<Void>? = nil,
connectPromise: EventLoopPromise<Void>? = nil,
writePromise: EventLoopPromise<Void>? = nil,
flushPromise: EventLoopPromise<Void>? = nil,
readPromise: EventLoopPromise<Void>? = nil,
closePromise: EventLoopPromise<Void>? = nil,
triggerUserOutboundEventPromise: EventLoopPromise<Void>? = nil) {
self.channelRegisteredPromise = channelRegisteredPromise
self.channelUnregisteredPromise = channelUnregisteredPromise
self.channelActivePromise = channelActivePromise
self.channelInactivePromise = channelInactivePromise
self.channelReadPromise = channelReadPromise
self.channelReadCompletePromise = channelReadCompletePromise
self.channelWritabilityChangedPromise = channelWritabilityChangedPromise
self.userInboundEventTriggeredPromise = userInboundEventTriggeredPromise
self.errorCaughtPromise = errorCaughtPromise
self.registerPromise = registerPromise
self.bindPromise = bindPromise
self.connectPromise = connectPromise
self.writePromise = writePromise
self.flushPromise = flushPromise
self.readPromise = readPromise
self.closePromise = closePromise
self.triggerUserOutboundEventPromise = triggerUserOutboundEventPromise
}
func handlerRemoved(context: ChannelHandlerContext) {
self.channelRegisteredPromise?.fail(ExpectedEventMissing())
self.channelUnregisteredPromise?.fail(ExpectedEventMissing())
self.channelActivePromise?.fail(ExpectedEventMissing())
self.channelInactivePromise?.fail(ExpectedEventMissing())
self.channelReadPromise?.fail(ExpectedEventMissing())
self.channelReadCompletePromise?.fail(ExpectedEventMissing())
self.channelWritabilityChangedPromise?.fail(ExpectedEventMissing())
self.userInboundEventTriggeredPromise?.fail(ExpectedEventMissing())
self.errorCaughtPromise?.fail(ExpectedEventMissing())
self.registerPromise?.fail(ExpectedEventMissing())
self.bindPromise?.fail(ExpectedEventMissing())
self.connectPromise?.fail(ExpectedEventMissing())
self.writePromise?.fail(ExpectedEventMissing())
self.flushPromise?.fail(ExpectedEventMissing())
self.readPromise?.fail(ExpectedEventMissing())
self.closePromise?.fail(ExpectedEventMissing())
self.triggerUserOutboundEventPromise?.fail(ExpectedEventMissing())
}
func channelRegistered(context: ChannelHandlerContext) {
self.channelRegisteredPromise?.succeed(())
context.fireChannelRegistered()
}
func channelUnregistered(context: ChannelHandlerContext) {
self.channelUnregisteredPromise?.succeed(())
context.fireChannelUnregistered()
}
func channelActive(context: ChannelHandlerContext) {
self.channelActivePromise?.succeed(())
context.fireChannelActive()
}
func channelInactive(context: ChannelHandlerContext) {
self.channelInactivePromise?.succeed(())
context.fireChannelInactive()
}
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
self.channelReadPromise?.succeed(())
context.fireChannelRead(data)
}
func channelReadComplete(context: ChannelHandlerContext) {
self.channelReadCompletePromise?.succeed(())
context.fireChannelReadComplete()
}
func channelWritabilityChanged(context: ChannelHandlerContext) {
self.channelWritabilityChangedPromise?.succeed(())
context.fireChannelWritabilityChanged()
}
func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
self.userInboundEventTriggeredPromise?.succeed(())
context.fireUserInboundEventTriggered(event)
}
func errorCaught(context: ChannelHandlerContext, error: Error) {
self.errorCaughtPromise?.succeed(())
context.fireErrorCaught(error)
}
func register(context: ChannelHandlerContext, promise: EventLoopPromise<Void>?) {
self.registerPromise?.succeed(())
context.register(promise: promise)
}
func bind(context: ChannelHandlerContext, to: SocketAddress, promise: EventLoopPromise<Void>?) {
self.bindPromise?.succeed(())
context.bind(to: to, promise: promise)
}
func connect(context: ChannelHandlerContext, to: SocketAddress, promise: EventLoopPromise<Void>?) {
self.connectPromise?.succeed(())
context.connect(to: to, promise: promise)
}
func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) {
self.writePromise?.succeed(())
context.write(data, promise: promise)
}
func flush(context: ChannelHandlerContext) {
self.flushPromise?.succeed(())
context.flush()
}
func read(context: ChannelHandlerContext) {
self.readPromise?.succeed(())
context.read()
}
func close(context: ChannelHandlerContext, mode: CloseMode, promise: EventLoopPromise<Void>?) {
self.closePromise?.succeed(())
context.close(mode: mode, promise: promise)
}
func triggerUserOutboundEvent(context: ChannelHandlerContext, event: Any, promise: EventLoopPromise<Void>?) {
self.triggerUserOutboundEventPromise?.succeed(())
context.triggerUserOutboundEvent(event, promise: promise)
}
}
func forEachActiveChannelType<T>(file: StaticString = #file,
line: UInt = #line,
_ body: @escaping (Channel) throws -> T) throws -> [T] {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
let channelEL = group.next()
let lock = Lock()
var ret: [T] = []
_ = try forEachCrossConnectedStreamChannelPair(file: (file), line: line) { (chan1: Channel, chan2: Channel) throws -> Void in
var innerRet: [T] = [try body(chan1)]
if let parent = chan1.parent {
innerRet.append(try body(parent))
}
lock.withLock {
ret.append(contentsOf: innerRet)
}
}
// UDP
let udpChannel = DatagramBootstrap(group: channelEL)
.channelInitializer { channel in
XCTAssert(channel.eventLoop.inEventLoop)
return channelEL.makeSucceededFuture(())
}
.bind(host: "127.0.0.1", port: 0)
defer {
XCTAssertNoThrow(try udpChannel.wait().syncCloseAcceptingAlreadyClosed())
}
return try lock.withLock {
ret.append(try body(udpChannel.wait()))
return ret
}
}
func withTCPServerChannel<R>(bindTarget: SocketAddress? = nil,
group: EventLoopGroup,
file: StaticString = #file,
line: UInt = #line,
_ body: (Channel) throws -> R) throws -> R {
let server = try ServerBootstrap(group: group)
.serverChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
.bind(to: bindTarget ?? .init(ipAddress: "127.0.0.1", port: 0))
.wait()
do {
let result = try body(server)
try server.close().wait()
return result
} catch {
try? server.close().wait()
throw error
}
}
func withCrossConnectedSockAddrChannels<R>(bindTarget: SocketAddress,
forceSeparateEventLoops: Bool = false,
file: StaticString = #file,
line: UInt = #line,
_ body: (Channel, Channel) throws -> R) throws -> R {
let serverGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
defer {
XCTAssertNoThrow(try serverGroup.syncShutdownGracefully())
}
let clientGroup: MultiThreadedEventLoopGroup
if forceSeparateEventLoops {
clientGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
} else {
clientGroup = serverGroup
}
defer {
// this may fail if clientGroup === serverGroup
try? clientGroup.syncShutdownGracefully()
}
let serverChannelEL = serverGroup.next()
let clientChannelEL = clientGroup.next()
let tcpAcceptedChannel = serverChannelEL.makePromise(of: Channel.self)
let tcpServerChannel = try assertNoThrowWithValue(ServerBootstrap(group: serverChannelEL)
.childChannelInitializer { channel in
let accepted = channel.eventLoop.makePromise(of: Void.self)
accepted.futureResult.map {
channel
}.cascade(to: tcpAcceptedChannel)
return channel.pipeline.addHandler(FulfillOnFirstEventHandler(channelActivePromise: accepted))
}
.bind(to: bindTarget)
.wait(), file: (file), line: line)
defer {
XCTAssertNoThrow(try tcpServerChannel.syncCloseAcceptingAlreadyClosed())
}
let tcpClientChannel = try assertNoThrowWithValue(ClientBootstrap(group: clientChannelEL)
.channelInitializer { channel in
XCTAssert(channel.eventLoop.inEventLoop)
return channel.eventLoop.makeSucceededFuture(())
}
.connect(to: tcpServerChannel.localAddress!)
.wait())
defer {
XCTAssertNoThrow(try tcpClientChannel.syncCloseAcceptingAlreadyClosed())
}
return try body(try tcpAcceptedChannel.futureResult.wait(), tcpClientChannel)
}
func withCrossConnectedTCPChannels<R>(forceSeparateEventLoops: Bool = false,
file: StaticString = #file,
line: UInt = #line,
_ body: (Channel, Channel) throws -> R) throws -> R {
return try withCrossConnectedSockAddrChannels(bindTarget: .init(ipAddress: "127.0.0.1", port: 0),
forceSeparateEventLoops: forceSeparateEventLoops,
body)
}
func withCrossConnectedUnixDomainSocketChannels<R>(forceSeparateEventLoops: Bool = false,
file: StaticString = #file,
line: UInt = #line,
_ body: (Channel, Channel) throws -> R) throws -> R {
return try withTemporaryDirectory { tempDir in
let bindTarget = try SocketAddress(unixDomainSocketPath: tempDir + "/s")
return try withCrossConnectedSockAddrChannels(bindTarget: bindTarget,
forceSeparateEventLoops: forceSeparateEventLoops,
body)
}
}
func withCrossConnectedPipeChannels<R>(forceSeparateEventLoops: Bool = false,
file: StaticString = #file,
line: UInt = #line,
_ body: (Channel, Channel) throws -> R) throws -> R {
let channel1Group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
defer {
XCTAssertNoThrow(try channel1Group.syncShutdownGracefully(), file: (file), line: line)
}
let channel2Group: MultiThreadedEventLoopGroup
if forceSeparateEventLoops {
channel2Group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
} else {
channel2Group = channel1Group
}
defer {
// may fail if pipe1Group == pipe2Group
try? channel2Group.syncShutdownGracefully()
}
var result: R? = nil
XCTAssertNoThrow(try withPipe { pipe1Read, pipe1Write -> [NIOFileHandle] in
try withPipe { pipe2Read, pipe2Write -> [NIOFileHandle] in
try pipe1Read.withUnsafeFileDescriptor { pipe1Read in
try pipe1Write.withUnsafeFileDescriptor { pipe1Write in
try pipe2Read.withUnsafeFileDescriptor { pipe2Read in
try pipe2Write.withUnsafeFileDescriptor { pipe2Write in
let channel1 = try NIOPipeBootstrap(group: channel1Group)
.withPipes(inputDescriptor: pipe1Read, outputDescriptor: pipe2Write)
.wait()
defer {
XCTAssertNoThrow(try channel1.syncCloseAcceptingAlreadyClosed())
}
let channel2 = try NIOPipeBootstrap(group: channel2Group)
.withPipes(inputDescriptor: pipe2Read, outputDescriptor: pipe1Write)
.wait()
defer {
XCTAssertNoThrow(try channel2.syncCloseAcceptingAlreadyClosed())
}
result = try body(channel1, channel2)
}
}
}
}
XCTAssertNoThrow(try pipe1Read.takeDescriptorOwnership(), file: (file), line: line)
XCTAssertNoThrow(try pipe1Write.takeDescriptorOwnership(), file: (file), line: line)
XCTAssertNoThrow(try pipe2Read.takeDescriptorOwnership(), file: (file), line: line)
XCTAssertNoThrow(try pipe2Write.takeDescriptorOwnership(), file: (file), line: line)
return []
}
return [] // the channels are closing the pipes
}, file: (file), line: line)
return result!
}
func forEachCrossConnectedStreamChannelPair<R>(forceSeparateEventLoops: Bool = false,
file: StaticString = #file,
line: UInt = #line,
_ body: (Channel, Channel) throws -> R) throws -> [R] {
let r1 = try withCrossConnectedTCPChannels(forceSeparateEventLoops: forceSeparateEventLoops, body)
let r2 = try withCrossConnectedPipeChannels(forceSeparateEventLoops: forceSeparateEventLoops, body)
let r3 = try withCrossConnectedUnixDomainSocketChannels(forceSeparateEventLoops: forceSeparateEventLoops, body)
return [r1, r2, r3]
}
extension EventLoopFuture {
var isFulfilled: Bool {
if self.eventLoop.inEventLoop {
// Easy, we're on the EventLoop. Let's just use our knowledge that we run completed future callbacks
// immediately.
var fulfilled = false
self.whenComplete { _ in
fulfilled = true
}
return fulfilled
} else {
let lock = Lock()
let group = DispatchGroup()
var fulfilled = false // protected by lock
group.enter()
self.eventLoop.execute {
let isFulfilled = self.isFulfilled // This will now enter the above branch.
lock.withLock {
fulfilled = isFulfilled
}
group.leave()
}
group.wait() // this is very nasty but this is for tests only, so...
return lock.withLock { fulfilled }
}
}
}
| 40.732493 | 212 | 0.638792 |
e9f5a5a8b6dc24a7a8dfe0cd87dab6062ccfeb03 | 877 | // swift-tools-version:5.2
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "TreeSitter",
products: [
.library(name: "TreeSitter", targets: [ "TreeSitter" ]),
],
dependencies: [],
targets: [
// Our Public Swift wrapper that lives in Sources/TreeSitter
.target(name: "TreeSitter", dependencies: [ "tree_sitter" ]),
// The original C tree-sitter library that lives in ./lib
.target (
name: "tree_sitter",
path: "lib",
sources: [ "src/lib.c" ],
publicHeadersPath: "include/tree_sitter",
cSettings: [
.headerSearchPath("include"),
.headerSearchPath("src")
]
)
],
cLanguageStandard: .gnu99
)
| 25.794118 | 96 | 0.572406 |
76dc9131b06967c0d20f9bc05bd780627b019472 | 4,576 | //
// CLLocation.swift
// ZamzamCore
//
// Created by Basem Emara on 2/17/16.
// Copyright © 2016 Zamzam Inc. All rights reserved.
//
import CoreLocation.CLGeocoder
import CoreLocation.CLLocation
import Foundation
public extension CLLocationCoordinate2D {
/// Returns a location object.
var location: CLLocation {
CLLocation(latitude: latitude, longitude: longitude)
}
/// Returns the distance (measured in meters) from the receiver’s location to the specified location.
func distance(from coordinate: CLLocationCoordinate2D) -> CLLocationDistance {
location.distance(from: coordinate.location)
}
}
public extension Array where Element == CLLocationCoordinate2D {
/// Returns the closest coordinate to the specified location.
///
/// If the sequence has no elements, returns nil.
func closest(to coordinate: CLLocationCoordinate2D) -> CLLocationCoordinate2D? {
self.min { $0.distance(from: coordinate) < $1.distance(from: coordinate) }
}
/// Returns the farthest coordinate from the specified location.
///
/// If the sequence has no elements, returns nil.
func farthest(from coordinate: CLLocationCoordinate2D) -> CLLocationCoordinate2D? {
self.max { $0.distance(from: coordinate) < $1.distance(from: coordinate) }
}
}
public extension CLLocation {
struct LocationMeta: CustomStringConvertible {
public var coordinates: (latitude: Double, longitude: Double)?
public var locality: String?
public var country: String?
public var countryCode: String?
public var timeZone: TimeZone?
public var administrativeArea: String?
public var description: String {
if let l = locality, let c = (Locale.current.languageCode == "en" ? countryCode : country) {
return "\(l), \(c)"
} else if let l = locality {
return "\(l)"
} else if let c = country {
return "\(c)"
}
return ""
}
}
/// Retrieves location details for coordinates.
///
/// - Parameters:
/// - timeout: A timeout to exit and call completion handler. Default is 10 seconds.
/// - completion: Async callback with retrived location details.
func geocoder(timeout: TimeInterval = 10, completion: @escaping (LocationMeta?) -> Void) {
var hasCompleted = false
// Fallback on timeout since could take too long
// https://stackoverflow.com/a/34389742
let timer = Timer(timeInterval: timeout, repeats: false) { timer in
defer { timer.invalidate() }
guard !hasCompleted else { return }
hasCompleted = true
DispatchQueue.main.async {
completion(nil)
}
}
// Reverse geocode stored coordinates
CLGeocoder().reverseGeocodeLocation(self) { placemarks, error in
DispatchQueue.main.async {
// Destroy timeout mechanism
guard !hasCompleted else { return }
hasCompleted = true
timer.invalidate()
guard let mark = placemarks?.first, error == nil else {
return completion(nil)
}
completion(
LocationMeta(
coordinates: (self.coordinate.latitude, self.coordinate.longitude),
locality: mark.locality ?? mark.subAdministrativeArea,
country: mark.country,
countryCode: mark.isoCountryCode,
timeZone: mark.timeZone,
administrativeArea: mark.administrativeArea
)
)
}
}
// Start timer
RunLoop.current.add(timer, forMode: .default)
}
}
extension CLLocationCoordinate2D: Equatable {
/// Determine if coordinates match using latitude and longitude values.
public static func == (lhs: CLLocationCoordinate2D, rhs: CLLocationCoordinate2D) -> Bool {
lhs.latitude == rhs.latitude && lhs.longitude == rhs.longitude
}
/// Determine if coordinates do not match using latitude and longitude values.
public static func != (lhs: CLLocationCoordinate2D, rhs: CLLocationCoordinate2D) -> Bool {
!(lhs == rhs)
}
}
extension CLLocationCoordinate2D: CustomStringConvertible {
public var description: String {
.localizedStringWithFormat("%.2f°, %.2f°", latitude, longitude)
}
}
| 34.931298 | 105 | 0.612107 |
1ae837876011e26034ae41b718f7cb86d4a1d0bb | 575 | //
// Message.swift
// NStack
//
// Created by Kasper Welner on 21/10/15.
// Copyright © 2015 Nodes. All rights reserved.
//
import Foundation
internal struct Message: Codable {
let id: Int
let message: String
let showSetting: String
let url: URL?
/// Temporary solution for localizing the message's buttons
/// - Valid keys: `okBtn`, `urlBtn`
let localization: [String: String]?
enum CodingKeys: String, CodingKey {
case id, message
case showSetting = "show_setting"
case url
case localization
}
}
| 20.535714 | 63 | 0.636522 |
67e703515863812bbe37e640d1350accd2ae96f0 | 3,018 | //
// Register.swift
// SharedLogin (iOS)
//
// Created by Balaji on 11/01/21.
//
import SwiftUI
struct Register: View {
@EnvironmentObject var homeData : LoginViewModel
var body: some View {
VStack(alignment: .leading, spacing: 18, content: {
Label(
title: {
Text("Please Register")
.font(.title2)
.fontWeight(.bold)
.foregroundColor(.black) },
icon: {
// Back Button...
Button(action: {
homeData.clearData()
// Moving View Back To Login...
withAnimation{
homeData.gotoRegister.toggle()
}
}, label: {
Image("right")
.resizable()
.renderingMode(.template)
.frame(width: 20, height: 20)
.aspectRatio(contentMode: .fit)
.foregroundColor(.black)
.rotationEffect(.init(degrees: 180))
})
.buttonStyle(PlainButtonStyle())
})
Label(
title: { TextField("Enter Email", text: $homeData.email)
.textFieldStyle(PlainTextFieldStyle())
},
icon: { Image(systemName: "envelope")
.frame(width: 30)
.foregroundColor(.gray)
})
Divider()
Label(
title: { SecureField("Password", text: $homeData.password)
.textFieldStyle(PlainTextFieldStyle())
},
icon: { Image(systemName: "lock")
.frame(width: 30)
.foregroundColor(.gray)
})
.overlay(
Button(action: {}, label: {
Image(systemName: "eye")
.foregroundColor(.gray)
})
.buttonStyle(PlainButtonStyle())
,alignment: .trailing
)
Divider()
Label(
title: { SecureField("Re-Enter Password", text: $homeData.reEnter)
.textFieldStyle(PlainTextFieldStyle())
},
icon: { Image(systemName: "lock")
.frame(width: 30)
.foregroundColor(.gray)
})
Divider()
})
.modifier(LoginViewModifier())
}
}
struct Resigter_Previews: PreviewProvider {
static var previews: some View {
Register()
}
}
| 30.484848 | 82 | 0.382041 |
b9d37c5e7c33589f208ec368f29762224051e9b8 | 3,087 | //
// UUGradientView.swift
// Useful Utilities - Simple UIView subclass to draw a gradient background color
//
// License:
// You are free to use this code for whatever purposes you desire.
// The only requirement is that you smile everytime you use it.
//
#if os(iOS)
import UIKit
import UUSwiftCore
public enum UUGradientDirection : Int
{
case horizontal
case vertical
}
// This class is a simple UIView subclass that draws a gradient background using
// two colors.
//
//
@IBDesignable public class UUGradientView : UIView
{
@IBInspectable public var startColor : UIColor = UIColor(red: 0, green: 0, blue: 0, alpha: 1)
{
didSet
{
self.setNeedsDisplay()
}
}
@IBInspectable public var endColor : UIColor = UIColor(red: 1, green: 1, blue: 1, alpha: 1)
{
didSet
{
self.setNeedsDisplay()
}
}
@IBInspectable public var midPoint : Float = 0.5
{
didSet
{
self.setNeedsDisplay()
}
}
public var direction : UUGradientDirection = .horizontal
{
didSet
{
self.setNeedsDisplay()
}
}
public var transparentClipRect : CGRect = CGRect.zero
{
didSet
{
self.isOpaque = false
self.setNeedsDisplay()
}
}
@IBInspectable public var directionAdapter : Int
{
get
{
return self.direction.rawValue
}
set( val)
{
self.direction = UUGradientDirection(rawValue: val) ?? .horizontal
}
}
override required public init(frame: CGRect)
{
super.init(frame: frame)
}
required public init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
}
override public func draw(_ rect: CGRect)
{
let context = UIGraphicsGetCurrentContext()!
let colorSpace = CGColorSpaceCreateDeviceRGB()
let midColor = UIColor.uuCalculateMidColor(startColor: self.startColor, endColor: self.endColor)
let colors : [CGColor] = [ self.startColor.cgColor, midColor.cgColor, self.endColor.cgColor ]
let locations : [CGFloat] = [ 0.0, CGFloat(self.midPoint), 1.0 ]
let gradient = CGGradient(colorsSpace: colorSpace, colors: colors as CFArray, locations: locations)!
var startPoint = CGPoint(x: rect.minX, y: rect.midY)
var endPoint = CGPoint(x: rect.maxX, y: rect.midY)
if (self.direction == .vertical)
{
startPoint = CGPoint(x: rect.midX, y: rect.minY)
endPoint = CGPoint(x: rect.midX, y: rect.maxY)
}
context.saveGState()
context.addRect(rect)
context.clip()
context.drawLinearGradient(gradient, start: startPoint, end: endPoint, options: CGGradientDrawingOptions(rawValue: 0))
context.restoreGState()
context.clear(transparentClipRect)
}
}
#endif
| 24.895161 | 126 | 0.58309 |
3a43390ae96a39c9b95ac1ecd6756a7d4e777141 | 2,936 | import SpriteKit
public class GameScene: SKScene {
private var label : SKLabelNode!
private var spinnyNode : SKShapeNode!
let dog = SKSpriteNode(imageNamed: "dog")
override public func didMove(to view: SKView) {
// Get label node from scene and store it for use later
label = childNode(withName: "//helloLabel") as? SKLabelNode
label.alpha = 0.0
let fadeInOut = SKAction.sequence([.fadeIn(withDuration: 2.0),
.fadeOut(withDuration: 2.0)])
label.run(.repeatForever(fadeInOut))
// Create shape node to use during mouse interaction
let w = (size.width + size.height) * 0.02
spinnyNode = SKShapeNode(rectOf: CGSize(width: w, height: w), cornerRadius: w * 0.3)
spinnyNode.lineWidth = 2.5
let fadeAndRemove = SKAction.sequence([.wait(forDuration: 0.5),
.fadeOut(withDuration: 0.5),
.removeFromParent()])
spinnyNode.run(.repeatForever(.rotate(byAngle: CGFloat(Double.pi), duration: 1)))
spinnyNode.run(fadeAndRemove)
dog.position.x = self.frame.midX
dog.position.y = self.frame.midY
addChild(dog)
}
@objc static override public var supportsSecureCoding: Bool {
// SKNode conforms to NSSecureCoding, so any subclass going
// through the decoding process must support secure coding
get {
return true
}
}
func touchDown(atPoint pos : CGPoint) {
guard let n = spinnyNode.copy() as? SKShapeNode else { return }
n.position = pos
n.strokeColor = SKColor.green
addChild(n)
}
func touchMoved(toPoint pos : CGPoint) {
guard let n = self.spinnyNode.copy() as? SKShapeNode else { return }
n.position = pos
n.strokeColor = SKColor.yellow
addChild(n)
}
func touchUp(atPoint pos : CGPoint) {
guard let n = spinnyNode.copy() as? SKShapeNode else { return }
n.position = pos
n.strokeColor = SKColor.red
addChild(n)
}
override public func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { touchDown(atPoint: t.location(in: self)) }
}
override public func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { touchMoved(toPoint: t.location(in: self)) }
}
override public func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { touchUp(atPoint: t.location(in: self)) }
}
override public func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { touchUp(atPoint: t.location(in: self)) }
}
override public func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
}
}
| 32.988764 | 92 | 0.608992 |
1cae5673c1fa555a99935b5c23427c0b34884fd0 | 7,705 | //
// EnterStartViewController.swift
// WavesWallet-iOS
//
// Created by Pavel Gubin on 6/28/18.
// Copyright © 2018 Waves Platform. All rights reserved.
//
import UIKit
import Extensions
private enum Constants {
enum CollectionTopOffset: CGFloat {
case small = 0
case medium = 24
case big = 64
}
enum ButtonTopOffset: CGFloat {
case small = 14
case big = 44
}
enum PageControlTopOffset: CGFloat {
case small = 2
case big = 24
}
}
protocol EnterStartViewControllerDelegate: AnyObject {
func showSignInAccount()
func showImportCoordinator()
func showNewAccount()
func showLanguageCoordinator()
}
final class EnterStartViewController: UIViewController, UICollectionViewDelegate {
typealias Block = EnterStartTypes.Block
@IBOutlet weak var pageControl: UIPageControl!
@IBOutlet private weak var collectionViewHeightConstraint: NSLayoutConstraint!
@IBOutlet private weak var collectionTopOffsetConstraint: NSLayoutConstraint!
@IBOutlet weak var createAccountButtonTopConstraint: NSLayoutConstraint!
@IBOutlet weak var pageControlTopConstraint: NSLayoutConstraint!
@IBOutlet weak var importAccountView: UIView!
@IBOutlet weak var signInView: UIView!
@IBOutlet private weak var signInTitleLabel: UILabel!
@IBOutlet private weak var signInDetailLabel: UILabel!
@IBOutlet private weak var importAccountTitleLabel: UILabel!
@IBOutlet private weak var importAccountDetailLabel: UILabel!
@IBOutlet private weak var createNewAccountButton: UIButton!
@IBOutlet private weak var collectionView: UICollectionView!
@IBOutlet weak var orLabel: UILabel!
private var currentPage: Int = 0
private let blocks: [Block] = [.blockchain,
.wallet,
.dex]
weak var delegate: EnterStartViewControllerDelegate?
deinit {
unsubscribe()
}
override func viewDidLoad() {
super.viewDidLoad()
createMenuButton()
setupNavigationItem()
subscribeLanguageNotification()
setupLanguage()
setupCollectionView()
setupTopOffsetConstraint()
}
// MARK: - Setup
private func setupCollectionView() {
collectionView.register(EnterStartBlockCell.nib, forCellWithReuseIdentifier: EnterStartBlockCell.reuseIdentifier)
}
private func setupLanguage() {
collectionView.reloadData()
createNewAccountButton.setTitle(Localizable.Waves.Enter.Button.Createnewaccount.title, for: .normal)
orLabel.text = Localizable.Waves.Enter.Label.or
signInTitleLabel.text = Localizable.Waves.Enter.Button.Signin.title
signInDetailLabel.text = Localizable.Waves.Enter.Button.Signin.detail
importAccountTitleLabel.text = Localizable.Waves.Enter.Button.Importaccount.title
importAccountDetailLabel.text = Localizable.Waves.Enter.Button.Importaccount.detail
setupLanguageButton()
}
private func setupLanguageButton() {
let language = Language.currentLanguage
let code = language.titleCode ?? language.code
let title = code.uppercased()
let item = UIBarButtonItem(title: title, style: .plain, target: self, action: #selector(changeLanguage(_:)))
item.tintColor = .black
navigationItem.rightBarButtonItem = item
}
private func setupNavigationItem() {
navigationItem.backgroundImage = UIImage()
navigationItem.shadowImage = UIImage()
navigationItem.barTintColor = .black
navigationItem.tintColor = .black
}
// MARK: - Layout
private var layouted = false
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if !layouted {
layouted = true
var maxHeight: CGFloat = 0
for block in blocks {
let height = EnterStartBlockCell.cellHeight(model: block, width: view.bounds.width)
maxHeight = max(height, 0)
}
collectionViewHeightConstraint.constant = maxHeight
signInView.addTableCellShadowStyle()
importAccountView.addTableCellShadowStyle()
}
}
private func setupTopOffsetConstraint() {
if Platform.isIphone5 {
collectionTopOffsetConstraint.constant = Constants.CollectionTopOffset.small.rawValue
createAccountButtonTopConstraint.constant = Constants.ButtonTopOffset.small.rawValue
pageControlTopConstraint.constant = Constants.PageControlTopOffset.small.rawValue
} else if Platform.isIphone7 {
collectionTopOffsetConstraint.constant = Constants.CollectionTopOffset.medium.rawValue
createAccountButtonTopConstraint.constant = Constants.ButtonTopOffset.big.rawValue
pageControlTopConstraint.constant = Constants.PageControlTopOffset.big.rawValue
} else {
collectionTopOffsetConstraint.constant = Constants.CollectionTopOffset.big.rawValue
createAccountButtonTopConstraint.constant = Constants.ButtonTopOffset.big.rawValue
pageControlTopConstraint.constant = Constants.PageControlTopOffset.big.rawValue
}
}
// MARK: - Notification
private func subscribeLanguageNotification() {
NotificationCenter.default.addObserver(self, selector: #selector(changedLanguage(_:)), name: .changedLanguage, object: nil)
}
private func unsubscribe() {
NotificationCenter.default.removeObserver(self)
}
@objc private func changedLanguage(_ notification: NSNotification) {
setupLanguage()
}
// MARK: - Actions
@objc func changeLanguage(_ sender: Any) {
delegate?.showLanguageCoordinator()
}
@IBAction func signIn(_ sender: Any) {
delegate?.showSignInAccount()
}
@IBAction func importAccount(_ sender: Any) {
delegate?.showImportCoordinator()
}
@IBAction func createNewAccountTapped(_ sender: Any) {
delegate?.showNewAccount()
}
}
extension EnterStartViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return blocks.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell: EnterStartBlockCell = collectionView.dequeueReusableCell(withReuseIdentifier: EnterStartBlockCell.reuseIdentifier, for: indexPath) as! EnterStartBlockCell
let block = blocks[indexPath.row] as Block
cell.update(with: block)
return cell
}
}
extension EnterStartViewController: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let pageWidth = scrollView.frame.width
let fractionalPage = scrollView.contentOffset.x / pageWidth
let page = lround(Double(fractionalPage))
pageControl.currentPage = page
}
}
extension EnterStartViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return .init(width: collectionView.bounds.width, height: collectionView.bounds.height)
}
}
| 31.970954 | 172 | 0.675925 |
282b961ee8aec64d3150923592ec4651eeac92b0 | 10,568 | //
// SelectionService.swift
// iOS
//
// Created by Miguel de Icaza on 3/5/20.
// Copyright © 2020 Miguel de Icaza. All rights reserved.
//
import Foundation
/**
* Tracks the selection state in the terminal
*/
class SelectionService {
var terminal: Terminal
public init (terminal: Terminal)
{
self.terminal = terminal
_active = false
start = Position(col: 0, row: 0)
end = Position(col: 0, row: 0)
hasSelectionRange = false
}
/**
* Controls whether the selection is active or not. Changing the value will invoke the `selectionChanged`
* method on the terminal's delegate if the state changes.
*/
var _active: Bool = false
public var active: Bool {
get {
return _active
}
set(newValue) {
if _active != newValue {
_active = newValue
terminal.tdel?.selectionChanged (source: terminal)
}
}
}
/**
* Whether any range is selected
*/
public private(set) var hasSelectionRange: Bool
/**
* Returns the selection starting point in buffer coordinates
*/
public private(set) var start: Position {
didSet {
hasSelectionRange = start != end
}
}
/**
* Returns the selection ending point in buffer coordinates
*/
public private(set) var end: Position {
didSet {
hasSelectionRange = start != end
}
}
/**
* Starts the selection from the specific location
*/
public func startSelection (row: Int, col: Int)
{
setSoftStart(row: row, col: col)
active = true
}
func clamp (_ buffer: Buffer, _ p: Position) -> Position {
return Position(col: min (p.col, buffer.cols-1), row: min (p.row, buffer.rows-1))
}
/**
* Sets the selection, this is validated against the
*/
public func setSelection (start: Position, end: Position) {
let buffer = terminal.buffer
let sclamped = clamp (buffer, start)
let eclamped = clamp (buffer, end)
self.start = sclamped
self.end = eclamped
active = true
}
/**
* Starts selection, the range is determined by the last start position
*/
public func startSelection ()
{
end = start
active = true
}
/**
* Sets the start and end positions but does not start selection
* this lets us record the last position of mouse clicks so that
* drag and shift+click operations know from where to start selection
* from
*/
public func setSoftStart (row: Int, col: Int)
{
guard row < terminal.buffer.rows && col < terminal.buffer.cols else {
return
}
active = true
let p = Position(col: col, row: row + terminal.buffer.yDisp)
start = p
end = p
}
/**
* Extends the selection based on the user "shift" clicking. This has
* slightly different semantics than a "drag" extension because we can
* shift the start to be the last prior end point if the new extension
* is before the current start point.
*/
public func shiftExtend (row: Int, col: Int)
{
let newEnd = Position (col: col, row: row + terminal.buffer.yDisp)
var shouldSwapStart = false
if Position.compare (start, end) == .before {
// start is before end, is the new end before Start
if Position.compare (newEnd, start) == .before {
// yes, swap Start and End
shouldSwapStart = true
}
} else if Position.compare (start, end) == .after {
if Position.compare (newEnd, start) == .after {
// yes, swap Start and End
shouldSwapStart = true
}
}
if (shouldSwapStart) {
start = end
}
end = newEnd
active = true
terminal.tdel?.selectionChanged(source: terminal)
}
/**
* Extends the selection by moving the end point to the new point.
*/
public func dragExtend (row: Int, col: Int)
{
end = Position(col: col, row: row + terminal.buffer.yDisp)
active = true
terminal.tdel?.selectionChanged(source: terminal)
}
/**
* Selects the entire buffer and triggers the selection
*/
public func selectAll ()
{
start = Position(col: 0, row: 0)
end = Position(col: terminal.cols-1, row: terminal.buffer.lines.maxLength - 1)
active = true
}
/**
* Selectss the specified row and triggers the selection
*/
public func select(row: Int)
{
start = Position(col: 0, row: row)
end = Position(col: terminal.cols-1, row: row)
active = true
terminal.tdel?.selectionChanged(source: terminal)
}
/**
* Performs a simple "word" selection based on a function that determines inclussion into the group
*/
func simpleScanSelection (from position: Position, in buffer: Buffer, includeFunc: (Character)-> Bool)
{
// Look backward
var colScan = position.col
var left = colScan
while colScan >= 0 {
let ch = buffer.getChar(at: Position (col: colScan, row: position.row)).getCharacter()
if !includeFunc (ch) {
break
}
left = colScan
colScan -= 1
}
// Look forward
colScan = position.col
var right = colScan
let limit = terminal.cols
while colScan < limit {
let ch = buffer.getChar(at: Position (col: colScan, row: position.row)).getCharacter()
if !includeFunc (ch) {
break
}
colScan += 1
right = colScan
}
start = Position (col: left, row: position.row)
end = Position(col: right, row: position.row)
}
/**
* Performs a forward search for the `end` character, but this can extend across matching subexpressions
* made of pais of parenthesis, braces and brackets.
*/
func balancedSearchForward (from position: Position, in buffer: Buffer)
{
var startCol = position.col
var wait: [Character] = []
start = position
for line in position.row..<terminal.rows {
for col in startCol..<terminal.cols {
let p = Position(col: col, row: line)
let ch = buffer.getChar (at: p).getCharacter ()
if ch == "(" {
wait.append (")")
} else if ch == "[" {
wait.append ("]")
} else if ch == "{" {
wait.append ("}")
} else if let v = wait.last {
if v == ch {
wait.removeLast()
if wait.count == 0 {
end = Position(col: p.col+1, row: p.row)
return
}
}
}
}
startCol = 0
}
start = position
end = position
}
/**
* Performs a forward search for the `end` character, but this can extend across matching subexpressions
* made of pais of parenthesis, braces and brackets.
*/
func balancedSearchBackward (from position: Position, in buffer: Buffer)
{
var startCol = position.col
var wait: [Character] = []
end = position
for line in (0...position.row).reversed() {
for col in (0...startCol).reversed() {
let p = Position(col: col, row: line)
let ch = buffer.getChar (at: p).getCharacter ()
if ch == ")" {
wait.append ("(")
} else if ch == "]" {
wait.append ("[")
} else if ch == "}" {
wait.append ("{")
} else if let v = wait.last {
if v == ch {
wait.removeLast()
if wait.count == 0 {
end = Position(col: end.col+1, row: end.row)
start = p
return
}
}
}
}
startCol = terminal.cols-1
}
start = position
end = position
}
let nullChar = Character(UnicodeScalar(0))
/**
* Implements the behavior to select the word at the specified position or an expression
* which is a balanced set parenthesis, braces or brackets
*/
public func selectWordOrExpression (at uncheckedPosition: Position, in buffer: Buffer)
{
let position = Position(
col: max (min (uncheckedPosition.col, buffer.cols-1), 0),
row: max (min (uncheckedPosition.row, buffer.rows-1), 0))
switch buffer.getChar(at: position).getCharacter() {
case Character(UnicodeScalar(0)):
simpleScanSelection (from: position, in: buffer) { ch in ch == nullChar }
case " ":
// Select all white space
simpleScanSelection (from: position, in: buffer) { ch in ch == " " }
case let ch where ch.isLetter || ch.isNumber:
simpleScanSelection (from: position, in: buffer) { ch in ch.isLetter || ch.isNumber || ch == "." }
case "{":
fallthrough
case "(":
fallthrough
case "[":
balancedSearchForward (from: position, in: buffer)
case ")":
fallthrough
case "]":
fallthrough
case "}":
balancedSearchBackward(from: position, in: buffer)
default:
// For other characters, we just stop there
start = position
end = position
}
active = true
terminal.tdel?.selectionChanged(source: terminal)
}
/**
* Clears the selection
*/
public func selectNone ()
{
if active {
active = false
terminal.tdel?.selectionChanged(source: terminal)
}
}
public func getSelectedText () -> String {
terminal.getText(start: self.start, end: self.end)
}
}
| 30.367816 | 111 | 0.519966 |
dbba34c5007a651788e9e0178bc947e2641204e1 | 1,451 | //
// LargeValueFormatter.swift
// ChartsDemo
// Copyright © 2016 dcg. All rights reserved.
//
import Foundation
import Charts
private let MAX_LENGTH = 5
@objc protocol Testing123 { }
public class LargeValueFormatter: NSObject, IValueFormatter, IAxisValueFormatter {
/// Suffix to be appended after the values.
///
/// **default**: suffix: ["", "k", "m", "b", "t"]
public var suffix = ["", "k", "m", "b", "t"]
/// An appendix text to be added at the end of the formatted value.
public var appendix: String?
public init(appendix: String? = nil) {
self.appendix = appendix
}
fileprivate func format(value: Double) -> String {
var sig = value
var length = 0
let maxLength = suffix.count - 1
while sig >= 1000.0 && length < maxLength {
sig /= 1000.0
length += 1
}
var r = String(format: "%2.f", sig) + suffix[length]
if let appendix = appendix {
r += appendix
}
return r
}
public func stringForValue(_ value: Double, axis: AxisBase?) -> String {
return format(value: value)
}
public func stringForValue(
_ value: Double,
entry: ChartDataEntry,
dataSetIndex: Int,
viewPortHandler: ViewPortHandler?) -> String {
return format(value: value) + "\n\n" + entry.category
}
}
| 24.59322 | 82 | 0.560303 |
9b39665aa6c54bf9ec971845f4b55caa4321b9b9 | 1,717 | //
// HighScoresViewController.swift
// PongGame
//
// Created by Ashleigh Pinch on 16/05/2017.
// Copyright © 2017 Sandun Heenatigala. All rights reserved.
//
import UIKit
import Foundation
class HighScoresViewController : UIViewController, UITableViewDelegate, UITableViewDataSource
{
@available(iOS 2.0, *)
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell( withIdentifier: "highScoreCell", for: indexPath as IndexPath)
cell.textLabel?.textColor = UIColor.white
let name = _SCORES[indexPath.row].Name
let score = String(_SCORES[indexPath.row].Score)
let pos = String(indexPath.row + 1)
// Setting cell text
cell.textLabel?.text = pos + ". " + name + " : " + score + "pts"
return cell
}
var score : Score!
@IBOutlet var TableView : UITableView!
{didSet { TableView.dataSource = self} }
override func viewDidLoad() {
super.viewDidLoad()
//Loading scores into global _SCORES array
score = Score()
score.LoadScores()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return _SCORES.count
}
@IBAction func ClearScores()
{
//removing all scores from the array
score.removeAll()
//refreshing the table to show removed items
refreshTable()
}
func refreshTable()
{
TableView.reloadData()
}
}
| 25.626866 | 111 | 0.619685 |
e2baab850ff96995e7b5b37c9c943095ced061d8 | 808 | //
// URL+NetworkDataLoader.swift
// WaterMyPlants-iOS
//
// Created by Austin Potts on 3/5/20.
// Copyright © 2020 Lambda School. All rights reserved.
//
import Foundation
extension URLSession: NetworkDataLoader {
func loadData(from request: URLRequest, completion: @escaping (Data?, Error?) -> Void) {
let task = self.dataTask(with: request) { (data, _, error) in
DispatchQueue.main.sync {
completion(data, error)
}
}
task.resume()
}
func loadData(from url: URL, completion: @escaping (Data?, Error?) -> Void) {
let task = self.dataTask(with: url) { (data, _, error) in
DispatchQueue.main.sync {
completion(data, error)
}
}
task.resume()
}
}
| 26.064516 | 92 | 0.566832 |
200c76d4626872a48cc45223130cef4ac480bc6f | 1,606 | #if os(macOS)
import Cocoa
extension Snapshotting where Value == CALayer, Format == NSImage {
/// A snapshot strategy for comparing layers based on pixel equality.
public static var image: Snapshotting {
return .image(precision: 1)
}
/// A snapshot strategy for comparing layers based on pixel equality.
///
/// - Parameter precision: The percentage of pixels that must match.
public static func image(precision: Float) -> Snapshotting {
return SimplySnapshotting.image(precision: precision).pullback { layer in
let image = NSImage(size: layer.bounds.size)
image.lockFocus()
let context = NSGraphicsContext.current!.cgContext
layer.setNeedsLayout()
layer.layoutIfNeeded()
layer.render(in: context)
image.unlockFocus()
return image
}
}
}
#elseif os(iOS) || os(tvOS)
import UIKit
extension Snapshotting where Value == CALayer, Format == UIImage {
/// A snapshot strategy for comparing layers based on pixel equality.
public static var image: Snapshotting {
return .image()
}
/// A snapshot strategy for comparing layers based on pixel equality.
///
/// - Parameter precision: The percentage of pixels that must match.
public static func image(precision: Float = 1, traits: UITraitCollection = .init())
-> Snapshotting {
return SimplySnapshotting.image(precision: precision).pullback { layer in
renderer(bounds: layer.bounds, for: traits).image { ctx in
layer.setNeedsLayout()
layer.layoutIfNeeded()
layer.render(in: ctx.cgContext)
}
}
}
}
#endif
| 32.12 | 85 | 0.687422 |
feb84211f496c7fdc4ca942b9dc9c9a92278599b | 4,479 | //
// BorrowedBooksViewController.swift
// 先声
//
// Created by Wangshuo on 14-9-8.
// Copyright (c) 2014年 WangShuo. All rights reserved.
//
import UIKit
class BorrowedBooksViewController: UIViewController,UITableViewDataSource,UITableViewDelegate,APIGetter {
@IBOutlet weak var noBorrowLabel: UILabel!
@IBOutlet var tableView: UITableView!
var dataList:NSArray! = []
var API = HeraldAPI()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "已借书籍"
let refreshButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Refresh, target: self, action: Selector("refreshData"))
self.navigationItem.rightBarButtonItem = refreshButton
let initResult = Tool.initNavigationAPI(self)
if initResult{
Tool.showProgressHUD("正在查询图书借阅情况")
self.API.delegate = self
API.sendAPI("library")
}
}
override func viewWillDisappear(animated: Bool) {
Tool.dismissHUD()
API.cancelAllRequest()
}
func getResult(APIName: String, results: JSON) {
switch APIName{
case "library":
if let resultsArray = results["content"].arrayObject
{
Tool.showSuccessHUD("获取成功")
self.dataList = resultsArray
if self.dataList.count == 0{
tableView.hidden = true
noBorrowLabel.hidden = false
}
else{
noBorrowLabel.hidden = true
tableView.hidden = false
self.tableView.reloadDataAnimateWithWave(WaveAnimation.RightToLeftWaveAnimation)
}
}
case "libraryRenew":
if "success" == results.string{
Tool.showSuccessHUD("续借成功")
}
else{
Tool.showErrorHUD("续借失败")
}
default:break
}
}
func getError(APIName: String, statusCode: Int) {
Tool.showErrorHUD("获取数据失败")
}
func refreshData()
{
Tool.showProgressHUD("正在刷新")
API.sendAPI("library")
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 280
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataList.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier:String = "BorrowedBooksTableViewCell"
var cell: BorrowedBooksTableViewCell? = self.tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? BorrowedBooksTableViewCell
if nil == cell
{
let nibArray:NSArray = NSBundle.mainBundle().loadNibNamed("BorrowedBooksTableViewCell", owner: self, options: nil)
cell = nibArray.objectAtIndex(0) as? BorrowedBooksTableViewCell
}
let row = indexPath.row
cell?.bookName.text = self.dataList[row]["title"] as! NSString as String
cell?.borrowDate.text = self.dataList[row]["render_date"] as! NSString as String
cell?.dueDate.text = self.dataList[row]["due_date"] as! NSString as String
cell?.collectionSite.text = self.dataList[row]["place"] as! NSString as String
cell?.author.text = self.dataList[row]["author"] as! NSString as String
cell?.barCode.text = self.dataList[row]["barcode"] as! NSString as String
cell?.renewTime.text = self.dataList[row]["renew_time"] as! NSString as String
cell?.renewButton.tag = row
cell?.renewButton.addTarget(self, action: Selector("renewButtonClicked:"), forControlEvents: UIControlEvents.TouchUpInside)
let color = UIColor(red: 96/255, green: 199/255, blue: 222/255, alpha: 0.3)
cell?.backgroundColor = color
return cell!
}
func renewButtonClicked(sender: UIButton)
{
let row = sender.tag
let barcode:String? = self.dataList[row]["barcode"] as? String
Tool.showProgressHUD("正在续借图书")
API.sendAPI("libraryRenew", APIParameter: barcode ?? "")
}
} | 33.676692 | 143 | 0.606162 |
1e3de869bc7a9df1f991c2c870b14e46fb4a6906 | 7,975 | //
// DashSettingsViewModelTests.swift
// DashKitUITests
//
// Created by Pete Schwamb on 7/21/20.
// Copyright © 2020 Tidepool. All rights reserved.
//
import XCTest
import DashKit
import PodSDK
import LoopKit
@testable import DashKitUI
class DashSettingsViewModelTests: 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.
}
private var simulatedDate: Date = ISO8601DateFormatter().date(from: "2019-10-02T00:00:00Z")!
private var dateSimulationOffset: TimeInterval = 0
private func dateGenerator() -> Date {
return self.simulatedDate + dateSimulationOffset
}
func testBasalDeliveryRateWithScheduledBasal() {
let basalScheduleItems = [RepeatingScheduleValue(startTime: 0, value: 1.0)]
let schedule = BasalRateSchedule(dailyItems: basalScheduleItems, timeZone: .current)!
let state = DashPumpManagerState(basalRateSchedule: schedule, lastPodCommState: .active, dateGenerator: dateGenerator)!
let mockPodCommManager = MockPodCommManager()
mockPodCommManager.simulatedCommsDelay = TimeInterval(0)
let pumpManager = DashPumpManager(state: state, podCommManager: mockPodCommManager, dateGenerator: dateGenerator)
let viewModel = DashSettingsViewModel(pumpManager: pumpManager)
XCTAssertNotNil(viewModel.basalDeliveryRate)
let basalDeliveryRate = viewModel.basalDeliveryRate!
XCTAssertEqual(1.0, basalDeliveryRate)
}
func testBasalDeliveryRateWithSuspendedBasal() {
let basalScheduleItems = [RepeatingScheduleValue(startTime: 0, value: 1.0)]
let schedule = BasalRateSchedule(dailyItems: basalScheduleItems, timeZone: .current)!
var state = DashPumpManagerState(basalRateSchedule: schedule, lastPodCommState: .active, dateGenerator: dateGenerator)!
state.suspendState = .suspended(dateGenerator() - .hours(1))
let mockPodCommManager = MockPodCommManager()
mockPodCommManager.simulatedCommsDelay = TimeInterval(0)
let pumpManager = DashPumpManager(state: state, podCommManager: mockPodCommManager, dateGenerator: dateGenerator)
let viewModel = DashSettingsViewModel(pumpManager: pumpManager)
XCTAssertNil(viewModel.basalDeliveryRate)
}
func testBasalDeliveryRateWithHighTemp() {
let basalScheduleItems = [RepeatingScheduleValue(startTime: 0, value: 1.0)]
let schedule = BasalRateSchedule(dailyItems: basalScheduleItems, timeZone: .current)!
var state = DashPumpManagerState(basalRateSchedule: schedule, lastPodCommState: .active, dateGenerator: dateGenerator)!
state.unfinalizedTempBasal = UnfinalizedDose(tempBasalRate: 2.0, startTime: dateGenerator() - .minutes(5), duration: .minutes(30), scheduledCertainty: .certain)
let mockPodCommManager = MockPodCommManager()
mockPodCommManager.simulatedCommsDelay = TimeInterval(0)
let pumpManager = DashPumpManager(state: state, podCommManager: mockPodCommManager, dateGenerator: dateGenerator)
let viewModel = DashSettingsViewModel(pumpManager: pumpManager)
XCTAssertNotNil(viewModel.basalDeliveryRate)
let basalDeliveryRate = viewModel.basalDeliveryRate!
XCTAssertEqual(2, basalDeliveryRate)
}
func testBasalDeliveryRateWithLowTemp() {
let basalScheduleItems = [RepeatingScheduleValue(startTime: 0, value: 1.0)]
let schedule = BasalRateSchedule(dailyItems: basalScheduleItems, timeZone: .current)!
var state = DashPumpManagerState(basalRateSchedule: schedule, lastPodCommState: .active, dateGenerator: dateGenerator)!
state.unfinalizedTempBasal = UnfinalizedDose(tempBasalRate: 0.5, startTime: dateGenerator() - .minutes(5), duration: .minutes(30), scheduledCertainty: .certain)
let mockPodCommManager = MockPodCommManager()
mockPodCommManager.simulatedCommsDelay = TimeInterval(0)
let pumpManager = DashPumpManager(state: state, podCommManager: mockPodCommManager, dateGenerator: dateGenerator)
let viewModel = DashSettingsViewModel(pumpManager: pumpManager)
XCTAssertNotNil(viewModel.basalDeliveryRate)
let basalDeliveryRate = viewModel.basalDeliveryRate!
XCTAssertEqual(0.5, basalDeliveryRate)
}
func testExpirationReminderShouldBeComputedRelativeToExpirationTime() {
let basalScheduleItems = [RepeatingScheduleValue(startTime: 0, value: 1.0)]
let schedule = BasalRateSchedule(dailyItems: basalScheduleItems, timeZone: .current)!
var state = DashPumpManagerState(basalRateSchedule: schedule, lastPodCommState: .active, dateGenerator: dateGenerator)!
state.unfinalizedTempBasal = UnfinalizedDose(tempBasalRate: 0.5, startTime: dateGenerator() - .minutes(5), duration: .minutes(30), scheduledCertainty: .certain)
// Simulate pod clock running 15 minutes fast
let activationTime = dateGenerator() - TimeInterval(days: 2)
state.podActivatedAt = activationTime
let expirationTime = activationTime + Pod.lifetime - TimeInterval(minutes: 15)
state.podExpiresAt = expirationTime
let mockPodCommManager = MockPodCommManager(podStatus: .normal, dateGenerator: dateGenerator)
mockPodCommManager.simulatedCommsDelay = TimeInterval(0)
let pumpManager = DashPumpManager(state: state, podCommManager: mockPodCommManager, dateGenerator: dateGenerator)
let viewModel = DashSettingsViewModel(pumpManager: pumpManager)
let intervalBeforeExpiration = TimeInterval(hours: 3)
let selectedDate = expirationTime - intervalBeforeExpiration
viewModel.saveScheduledExpirationReminder(selectedDate) { error in
XCTAssertNil(error)
if let configuredIntervalBeforeExpiration = mockPodCommManager.podStatus?.podExpirationAlert?.intervalBeforeExpiration {
XCTAssertEqual(configuredIntervalBeforeExpiration, intervalBeforeExpiration, accuracy: 0.1)
} else {
XCTFail("Expiration alert was not configured")
}
}
}
func testIsScheduledBasal() {
// scheduled basal
let basalScheduleItems = [RepeatingScheduleValue(startTime: 0, value: 1.0)]
let schedule = BasalRateSchedule(dailyItems: basalScheduleItems, timeZone: .current)!
var state = DashPumpManagerState(basalRateSchedule: schedule, lastPodCommState: .active, dateGenerator: dateGenerator)!
let mockPodCommManager = MockPodCommManager()
mockPodCommManager.simulatedCommsDelay = TimeInterval(0)
var pumpManager = DashPumpManager(state: state, podCommManager: mockPodCommManager, dateGenerator: dateGenerator)
var viewModel = DashSettingsViewModel(pumpManager: pumpManager)
XCTAssertTrue(viewModel.isScheduledBasal)
// suspended
state.suspendState = .suspended(dateGenerator() - .hours(1))
pumpManager = DashPumpManager(state: state, podCommManager: mockPodCommManager, dateGenerator: dateGenerator)
viewModel = DashSettingsViewModel(pumpManager: pumpManager)
XCTAssertFalse(viewModel.isScheduledBasal)
// temp basal
state.unfinalizedTempBasal = UnfinalizedDose(tempBasalRate: 2.0, startTime: dateGenerator() - .minutes(5), duration: .minutes(30), scheduledCertainty: .certain)
pumpManager = DashPumpManager(state: state, podCommManager: mockPodCommManager, dateGenerator: dateGenerator)
viewModel = DashSettingsViewModel(pumpManager: pumpManager)
XCTAssertFalse(viewModel.isScheduledBasal)
}
}
| 50.796178 | 168 | 0.725392 |
61c063b2c97e2414e90930532753c3dc91777887 | 31,405 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//This is a very rudimentary HTTP server written plainly for testing URLSession.
//It is not concurrent. It listens on a port, reads once and writes back only once.
//We can make it better everytime we need more functionality to test different aspects of URLSession.
import Dispatch
#if canImport(MSVCRT)
import MSVCRT
import WinSDK
#elseif canImport(Darwin)
import Darwin
#elseif canImport(Glibc)
import Glibc
#endif
#if !os(Windows)
typealias SOCKET = Int32
#endif
public let globalDispatchQueue = DispatchQueue.global()
public let dispatchQueueMake: (String) -> DispatchQueue = { DispatchQueue.init(label: $0) }
public let dispatchGroupMake: () -> DispatchGroup = DispatchGroup.init
struct _HTTPUtils {
static let CRLF = "\r\n"
static let VERSION = "HTTP/1.1"
static let SPACE = " "
static let CRLF2 = CRLF + CRLF
static let EMPTY = ""
}
extension UInt16 {
public init(networkByteOrder input: UInt16) {
self.init(bigEndian: input)
}
}
class _TCPSocket {
#if !os(Windows)
private let sendFlags: CInt
#endif
private var listenSocket: SOCKET!
private var socketAddress = UnsafeMutablePointer<sockaddr_in>.allocate(capacity: 1)
private var connectionSocket: SOCKET!
private func isNotNegative(r: CInt) -> Bool {
return r != -1
}
private func isZero(r: CInt) -> Bool {
return r == 0
}
private func attempt<T>(_ name: String, file: String = #file, line: UInt = #line, valid: (T) -> Bool, _ b: @autoclosure () -> T) throws -> T {
let r = b()
guard valid(r) else {
throw ServerError(operation: name, errno: errno, file: file, line: line)
}
return r
}
public private(set) var port: UInt16
init(port: UInt16?) throws {
#if !os(Windows)
#if os(Linux) || os(Android) || os(FreeBSD)
sendFlags = CInt(MSG_NOSIGNAL)
#else
sendFlags = 0
#endif
#endif
self.port = port ?? 0
#if os(Windows)
listenSocket = try attempt("WSASocketW", valid: { $0 != INVALID_SOCKET }, WSASocketW(AF_INET, SOCK_STREAM, IPPROTO_TCP.rawValue, nil, 0, 0))
var value: Int8 = 1
_ = try attempt("setsockopt", valid: { $0 == 0 }, setsockopt(listenSocket, SOL_SOCKET, SO_REUSEADDR, &value, Int32(MemoryLayout.size(ofValue: value))))
#else
#if os(Linux) && !os(Android)
let SOCKSTREAM = Int32(SOCK_STREAM.rawValue)
#else
let SOCKSTREAM = SOCK_STREAM
#endif
listenSocket = try attempt("socket", valid: { $0 >= 0 }, socket(AF_INET, SOCKSTREAM, Int32(IPPROTO_TCP)))
var on: CInt = 1
_ = try attempt("setsockopt", valid: { $0 == 0 }, setsockopt(listenSocket, SOL_SOCKET, SO_REUSEADDR, &on, socklen_t(MemoryLayout<CInt>.size)))
#endif
let sa = createSockaddr(port)
socketAddress.initialize(to: sa)
try socketAddress.withMemoryRebound(to: sockaddr.self, capacity: MemoryLayout<sockaddr>.size, {
let addr = UnsafePointer<sockaddr>($0)
_ = try attempt("bind", valid: isZero, bind(listenSocket, addr, socklen_t(MemoryLayout<sockaddr>.size)))
_ = try attempt("listen", valid: isZero, listen(listenSocket, SOMAXCONN))
})
var actualSA = sockaddr_in()
withUnsafeMutablePointer(to: &actualSA) { ptr in
ptr.withMemoryRebound(to: sockaddr.self, capacity: 1) { (ptr: UnsafeMutablePointer<sockaddr>) in
var len = socklen_t(MemoryLayout<sockaddr>.size)
getsockname(listenSocket, ptr, &len)
}
}
self.port = UInt16(networkByteOrder: actualSA.sin_port)
}
private func createSockaddr(_ port: UInt16?) -> sockaddr_in {
// Listen on the loopback address so that OSX doesnt pop up a dialog
// asking to accept incoming connections if the firewall is enabled.
let addr = UInt32(INADDR_LOOPBACK).bigEndian
let netPort = UInt16(bigEndian: port ?? 0)
#if os(Android)
return sockaddr_in(sin_family: sa_family_t(AF_INET), sin_port: netPort, sin_addr: in_addr(s_addr: addr), __pad: (0,0,0,0,0,0,0,0))
#elseif os(Linux)
return sockaddr_in(sin_family: sa_family_t(AF_INET), sin_port: netPort, sin_addr: in_addr(s_addr: addr), sin_zero: (0,0,0,0,0,0,0,0))
#elseif os(Windows)
return sockaddr_in(sin_family: ADDRESS_FAMILY(AF_INET), sin_port: USHORT(netPort), sin_addr: IN_ADDR(S_un: in_addr.__Unnamed_union_S_un(S_addr: addr)), sin_zero: (CHAR(0), CHAR(0), CHAR(0), CHAR(0), CHAR(0), CHAR(0), CHAR(0), CHAR(0)))
#else
return sockaddr_in(sin_len: 0, sin_family: sa_family_t(AF_INET), sin_port: netPort, sin_addr: in_addr(s_addr: addr), sin_zero: (0,0,0,0,0,0,0,0))
#endif
}
func acceptConnection(notify: ServerSemaphore) throws {
try socketAddress.withMemoryRebound(to: sockaddr.self, capacity: MemoryLayout<sockaddr>.size, {
let addr = UnsafeMutablePointer<sockaddr>($0)
var sockLen = socklen_t(MemoryLayout<sockaddr>.size)
#if os(Windows)
connectionSocket = try attempt("WSAAccept", valid: { $0 != INVALID_SOCKET }, WSAAccept(listenSocket, addr, &sockLen, nil, 0))
#else
connectionSocket = try attempt("accept", valid: { $0 >= 0 }, accept(listenSocket, addr, &sockLen))
#endif
#if canImport(Dawin)
// Disable SIGPIPEs when writing to closed sockets
var on: CInt = 1
_ = try attempt("setsockopt", valid: isZero, setsockopt(connectionSocket, SOL_SOCKET, SO_NOSIGPIPE, &on, socklen_t(MemoryLayout<CInt>.size)))
#endif
})
}
func readData() throws -> String {
var buffer = [CChar](repeating: 0, count: 4096)
#if os(Windows)
var dwNumberOfBytesRecieved: DWORD = 0;
try buffer.withUnsafeMutableBufferPointer {
var wsaBuffer: WSABUF = WSABUF(len: ULONG($0.count), buf: $0.baseAddress)
var flags: DWORD = 0
_ = try attempt("WSARecv", valid: { $0 != SOCKET_ERROR }, WSARecv(connectionSocket, &wsaBuffer, 1, &dwNumberOfBytesRecieved, &flags, nil, nil))
}
#else
_ = try attempt("read", valid: { $0 >= 0 }, read(connectionSocket, &buffer, buffer.count))
#endif
return String(cString: &buffer)
}
func writeRawData(_ data: Data) throws {
#if os(Windows)
_ = try data.withUnsafeBytes {
var dwNumberOfBytesSent: DWORD = 0
var wsaBuffer: WSABUF = WSABUF(len: ULONG(data.count), buf: UnsafeMutablePointer<CHAR>(mutating: $0.bindMemory(to: CHAR.self).baseAddress))
_ = try attempt("WSASend", valid: { $0 != SOCKET_ERROR }, WSASend(connectionSocket, &wsaBuffer, 1, &dwNumberOfBytesSent, 0, nil, nil))
}
#else
_ = try data.withUnsafeBytes { ptr in
try attempt("send", valid: isNotNegative, CInt(send(connectionSocket, ptr.baseAddress!, data.count, sendFlags)))
}
#endif
}
private func _send(_ bytes: [UInt8]) throws -> Int {
#if os(Windows)
return try bytes.withUnsafeBytes {
var dwNumberOfBytesSent: DWORD = 0
var wsaBuffer: WSABUF = WSABUF(len: ULONG(bytes.count), buf: UnsafeMutablePointer<CHAR>(mutating: $0.bindMemory(to: CHAR.self).baseAddress))
return try Int(attempt("WSASend", valid: { $0 != SOCKET_ERROR }, WSASend(connectionSocket, &wsaBuffer, 1, &dwNumberOfBytesSent, 0, nil, nil)))
}
#else
return try bytes.withUnsafeBufferPointer {
try attempt("send", valid: { $0 >= 0 }, send(connectionSocket, $0.baseAddress, $0.count, sendFlags))
}
#endif
}
func writeData(header: String, bodyData: Data, sendDelay: TimeInterval? = nil, bodyChunks: Int? = nil) throws {
_ = try _send(Array(header.utf8))
if let sendDelay = sendDelay, let bodyChunks = bodyChunks {
let count = max(1, Int(Double(bodyData.count) / Double(bodyChunks)))
for startIndex in stride(from: 0, to: bodyData.count, by: count) {
Thread.sleep(forTimeInterval: sendDelay)
let endIndex = min(startIndex + count, bodyData.count)
try bodyData.withUnsafeBytes { (ptr: UnsafeRawBufferPointer) -> Void in
let chunk = UnsafeRawBufferPointer(rebasing: ptr[startIndex..<endIndex])
_ = try _send(Array(chunk.bindMemory(to: UInt8.self)))
}
}
} else {
try bodyData.withUnsafeBytes { (ptr: UnsafeRawBufferPointer) -> Void in
_ = try _send(Array(ptr.bindMemory(to: UInt8.self)))
}
}
}
func closeClient() {
if let connectionSocket = self.connectionSocket {
#if os(Windows)
closesocket(connectionSocket)
#else
close(connectionSocket)
#endif
self.connectionSocket = nil
}
}
func shutdownListener() {
closeClient()
#if os(Windows)
shutdown(listenSocket, SD_BOTH)
closesocket(listenSocket)
#else
shutdown(listenSocket, CInt(SHUT_RDWR))
close(listenSocket)
#endif
}
}
class _HTTPServer {
let socket: _TCPSocket
var willReadAgain = false
var port: UInt16 {
get {
return self.socket.port
}
}
init(port: UInt16?) throws {
socket = try _TCPSocket(port: port)
}
public class func create(port: UInt16?) throws -> _HTTPServer {
return try _HTTPServer(port: port)
}
public func listen(notify: ServerSemaphore) throws {
try socket.acceptConnection(notify: notify)
}
public func stop() {
if !willReadAgain {
socket.closeClient()
socket.shutdownListener()
}
}
public func request() throws -> _HTTPRequest {
var request = try _HTTPRequest(request: socket.readData())
if Int(request.getHeader(for: "Content-Length") ?? "0") ?? 0 > 0
|| (request.getHeader(for: "Transfer-Encoding") ?? "").lowercased() == "chunked" {
// According to RFC7230 https://tools.ietf.org/html/rfc7230#section-3
// We receive messageBody after the headers, so we need read from socket minimum 2 times
//
// HTTP-message structure
//
// start-line
// *( header-field CRLF )
// CRLF
// [ message-body ]
// We receives '{numofbytes}\r\n{data}\r\n'
// TODO read data until the end
let substr = try socket.readData().split(separator: "\r\n")
if substr.count >= 2 {
request.messageBody = String(substr[1])
}
}
return request
}
public func respond(with response: _HTTPResponse, startDelay: TimeInterval? = nil, sendDelay: TimeInterval? = nil, bodyChunks: Int? = nil) throws {
if let delay = startDelay {
Thread.sleep(forTimeInterval: delay)
}
do {
try self.socket.writeData(header: response.header, bodyData: response.bodyData, sendDelay: sendDelay, bodyChunks: bodyChunks)
} catch {
}
}
func respondWithBrokenResponses(uri: String) throws {
let responseData: Data
switch uri {
case "/LandOfTheLostCities/Pompeii":
/* this is an example of what you get if you connect to an HTTP2
server using HTTP/1.1. Curl interprets that as a HTTP/0.9
simple-response and therefore sends this back as a response
body. Go figure! */
responseData = Data([
0x00, 0x00, 0x18, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x10, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00,
0x01, 0x00, 0x05, 0x00, 0x00, 0x40, 0x00, 0x00, 0x06, 0x00,
0x00, 0x1f, 0x40, 0x00, 0x00, 0x86, 0x07, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
0x48, 0x54, 0x54, 0x50, 0x2f, 0x32, 0x20, 0x63, 0x6c, 0x69,
0x65, 0x6e, 0x74, 0x20, 0x70, 0x72, 0x65, 0x66, 0x61, 0x63,
0x65, 0x20, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x20, 0x6d,
0x69, 0x73, 0x73, 0x69, 0x6e, 0x67, 0x20, 0x6f, 0x72, 0x20,
0x63, 0x6f, 0x72, 0x72, 0x75, 0x70, 0x74, 0x2e, 0x20, 0x48,
0x65, 0x78, 0x20, 0x64, 0x75, 0x6d, 0x70, 0x20, 0x66, 0x6f,
0x72, 0x20, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x64,
0x20, 0x62, 0x79, 0x74, 0x65, 0x73, 0x3a, 0x20, 0x34, 0x37,
0x34, 0x35, 0x35, 0x34, 0x32, 0x30, 0x32, 0x66, 0x33, 0x33,
0x32, 0x66, 0x36, 0x34, 0x36, 0x35, 0x37, 0x36, 0x36, 0x39,
0x36, 0x33, 0x36, 0x35, 0x32, 0x66, 0x33, 0x31, 0x33, 0x32,
0x33, 0x33, 0x33, 0x34, 0x33, 0x35, 0x33, 0x36, 0x33, 0x37,
0x33, 0x38, 0x33, 0x39, 0x33, 0x30])
case "/LandOfTheLostCities/Sodom":
/* a technically valid HTTP/0.9 simple-response */
responseData = ("technically, this is a valid HTTP/0.9 " +
"simple-response. I know it's odd but CURL supports it " +
"still...\r\nFind out more in those URLs:\r\n " +
" - https://www.w3.org/Protocols/HTTP/1.0/spec.html#Message-Types\r\n" +
" - https://github.com/curl/curl/issues/467\r\n").data(using: .utf8)!
case "/LandOfTheLostCities/Gomorrah":
/* just broken, hope that's not officially HTTP/0.9 :p */
responseData = "HTTP/1.1\r\n\r\n\r\n".data(using: .utf8)!
case "/LandOfTheLostCities/Myndus":
responseData = ("HTTP/1.1 200 OK\r\n" +
"\r\n" +
"this is a body that isn't legal as it's " +
"neither chunked encoding nor any Content-Length\r\n").data(using: .utf8)!
case "/LandOfTheLostCities/Kameiros":
responseData = ("HTTP/1.1 999 Wrong Code\r\n" +
"illegal: status code (too large)\r\n" +
"\r\n").data(using: .utf8)!
case "/LandOfTheLostCities/Dinavar":
responseData = ("HTTP/1.1 20 Too Few Digits\r\n" +
"illegal: status code (too few digits)\r\n" +
"\r\n").data(using: .utf8)!
case "/LandOfTheLostCities/Kuhikugu":
responseData = ("HTTP/1.1 2000 Too Many Digits\r\n" +
"illegal: status code (too many digits)\r\n" +
"\r\n").data(using: .utf8)!
default:
responseData = ("HTTP/1.1 500 Internal Server Error\r\n" +
"case-missing-in: TestFoundation/HTTPServer.swift\r\n" +
"\r\n").data(using: .utf8)!
}
try self.socket.writeRawData(responseData)
}
func respondWithAuthResponse(uri: String, firstRead: Bool) throws {
let responseData: Data
if firstRead {
responseData = ("HTTP/1.1 401 UNAUTHORIZED \r\n" +
"Content-Length: 0\r\n" +
"WWW-Authenticate: Basic realm=\"Fake Relam\"\r\n" +
"Access-Control-Allow-Origin: *\r\n" +
"Access-Control-Allow-Credentials: true\r\n" +
"Via: 1.1 vegur\r\n" +
"Cache-Control: proxy-revalidate\r\n" +
"Connection: keep-Alive\r\n" +
"\r\n").data(using: .utf8)!
} else {
responseData = ("HTTP/1.1 200 OK \r\n" +
"Content-Length: 37\r\n" +
"Content-Type: application/json\r\n" +
"Access-Control-Allow-Origin: *\r\n" +
"Access-Control-Allow-Credentials: true\r\n" +
"Via: 1.1 vegur\r\n" +
"Cache-Control: proxy-revalidate\r\n" +
"Connection: keep-Alive\r\n" +
"\r\n" +
"{\"authenticated\":true,\"user\":\"user\"}\n").data(using: .utf8)!
}
try self.socket.writeRawData(responseData)
}
func respondWithUnauthorizedHeader() throws{
let responseData = ("HTTP/1.1 401 UNAUTHORIZED \r\n" +
"Content-Length: 0\r\n" +
"Connection: keep-Alive\r\n" +
"\r\n").data(using: .utf8)!
try self.socket.writeRawData(responseData)
}
}
struct _HTTPRequest {
enum Method : String {
case GET
case POST
case PUT
}
let method: Method
let uri: String
let body: String
var messageBody: String?
let headers: [String]
enum Error: Swift.Error {
case headerEndNotFound
}
public init(request: String) throws {
let headerEnd = (request as NSString).range(of: _HTTPUtils.CRLF2)
guard headerEnd.location != NSNotFound else { throw Error.headerEndNotFound }
let header = (request as NSString).substring(to: headerEnd.location)
headers = header.components(separatedBy: _HTTPUtils.CRLF)
let action = headers[0]
method = Method(rawValue: action.components(separatedBy: " ")[0])!
uri = action.components(separatedBy: " ")[1]
body = (request as NSString).substring(from: headerEnd.location + headerEnd.length)
}
public func getCommaSeparatedHeaders() -> String {
var allHeaders = ""
for header in headers {
allHeaders += header + ","
}
return allHeaders
}
public func getHeader(for key: String) -> String? {
let lookup = key.lowercased()
for header in headers {
let parts = header.components(separatedBy: ":")
if parts[0].lowercased() == lookup {
return parts[1].trimmingCharacters(in: CharacterSet(charactersIn: " "))
}
}
return nil
}
}
struct _HTTPResponse {
enum Response : Int {
case OK = 200
case REDIRECT = 302
case NOTFOUND = 404
}
private let responseCode: Response
private let headers: String
public let bodyData: Data
public init(response: Response, headers: String = _HTTPUtils.EMPTY, bodyData: Data) {
self.responseCode = response
self.headers = headers
self.bodyData = bodyData
}
public init(response: Response, headers: String = _HTTPUtils.EMPTY, body: String) {
self.init(response: response, headers: headers, bodyData: body.data(using: .utf8)!)
}
public var header: String {
let statusLine = _HTTPUtils.VERSION + _HTTPUtils.SPACE + "\(responseCode.rawValue)" + _HTTPUtils.SPACE + "\(responseCode)"
return statusLine + (headers != _HTTPUtils.EMPTY ? _HTTPUtils.CRLF + headers : _HTTPUtils.EMPTY) + _HTTPUtils.CRLF2
}
}
public class TestURLSessionServer {
let capitals: [String:String] = ["Nepal": "Kathmandu",
"Peru": "Lima",
"Italy": "Rome",
"USA": "Washington, D.C.",
"UnitedStates": "USA",
"UnitedKingdom": "UK",
"UK": "London",
"country.txt": "A country is a region that is identified as a distinct national entity in political geography"]
let httpServer: _HTTPServer
let startDelay: TimeInterval?
let sendDelay: TimeInterval?
let bodyChunks: Int?
var port: UInt16 {
get {
return self.httpServer.port
}
}
public init (port: UInt16?, startDelay: TimeInterval? = nil, sendDelay: TimeInterval? = nil, bodyChunks: Int? = nil) throws {
httpServer = try _HTTPServer.create(port: port)
self.startDelay = startDelay
self.sendDelay = sendDelay
self.bodyChunks = bodyChunks
}
public func readAndRespond() throws {
let req = try httpServer.request()
if let value = req.getHeader(for: "x-pause") {
if let wait = Double(value), wait > 0 {
Thread.sleep(forTimeInterval: wait)
}
}
if req.uri.hasPrefix("/LandOfTheLostCities/") {
/* these are all misbehaving servers */
try httpServer.respondWithBrokenResponses(uri: req.uri)
} else if req.uri == "/NSString-ISO-8859-1-data.txt" {
// Serve this directly as binary data to avoid any String encoding conversions.
if let url = testBundle().url(forResource: "NSString-ISO-8859-1-data", withExtension: "txt"),
let content = try? Data(contentsOf: url) {
var responseData = "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=ISO-8859-1\r\nContent-Length: \(content.count)\r\n\r\n".data(using: .ascii)!
responseData.append(content)
try httpServer.socket.writeRawData(responseData)
} else {
try httpServer.respond(with: _HTTPResponse(response: .NOTFOUND, body: "Not Found"))
}
} else if req.uri.hasPrefix("/auth") {
httpServer.willReadAgain = true
try httpServer.respondWithAuthResponse(uri: req.uri, firstRead: true)
} else if req.uri.hasPrefix("/unauthorized") {
try httpServer.respondWithUnauthorizedHeader()
} else {
try httpServer.respond(with: process(request: req), startDelay: self.startDelay, sendDelay: self.sendDelay, bodyChunks: self.bodyChunks)
}
}
public func readAndRespondAgain() throws {
let req = try httpServer.request()
if req.uri.hasPrefix("/auth/") {
try httpServer.respondWithAuthResponse(uri: req.uri, firstRead: false)
}
httpServer.willReadAgain = false
}
func process(request: _HTTPRequest) -> _HTTPResponse {
if request.method == .GET || request.method == .POST || request.method == .PUT {
return getResponse(request: request)
} else {
fatalError("Unsupported method!")
}
}
func getResponse(request: _HTTPRequest) -> _HTTPResponse {
let uri = request.uri
if uri == "/upload" {
let text = "Upload completed!"
return _HTTPResponse(response: .OK, headers: "Content-Length: \(text.data(using: .utf8)!.count)", body: text)
}
if uri == "/country.txt" {
let text = capitals[String(uri.dropFirst())]!
return _HTTPResponse(response: .OK, headers: "Content-Length: \(text.data(using: .utf8)!.count)", body: text)
}
if uri == "/requestHeaders" {
let text = request.getCommaSeparatedHeaders()
return _HTTPResponse(response: .OK, headers: "Content-Length: \(text.data(using: .utf8)!.count)", body: text)
}
if uri == "/emptyPost" {
if request.body.count == 0 && request.getHeader(for: "Content-Type") == nil {
return _HTTPResponse(response: .OK, body: "")
}
return _HTTPResponse(response: .NOTFOUND, body: "")
}
if uri == "/requestCookies" {
let text = request.getCommaSeparatedHeaders()
return _HTTPResponse(response: .OK, headers: "Content-Length: \(text.data(using: .utf8)!.count)\r\nSet-Cookie: fr=anjd&232; Max-Age=7776000; path=/\r\nSet-Cookie: nm=sddf&232; Max-Age=7776000; path=/; domain=.swift.org; secure; httponly\r\n", body: text)
}
if uri == "/setCookies" {
let text = request.getCommaSeparatedHeaders()
return _HTTPResponse(response: .OK, headers: "Content-Length: \(text.data(using: .utf8)!.count)", body: text)
}
if uri == "/redirectSetCookies" {
return _HTTPResponse(response: .REDIRECT, headers: "Location: /setCookies\r\nSet-Cookie: redirect=true; Max-Age=7776000; path=/", body: "")
}
if uri == "/UnitedStates" {
let value = capitals[String(uri.dropFirst())]!
let text = request.getCommaSeparatedHeaders()
let host = request.headers[1].components(separatedBy: " ")[1]
let ip = host.components(separatedBy: ":")[0]
let port = host.components(separatedBy: ":")[1]
let newPort = Int(port)! + 1
let newHost = ip + ":" + String(newPort)
let httpResponse = _HTTPResponse(response: .REDIRECT, headers: "Location: http://\(newHost + "/" + value)", body: text)
return httpResponse
}
if uri == "/DTDs/PropertyList-1.0.dtd" {
let dtd = """
<!ENTITY % plistObject "(array | data | date | dict | real | integer | string | true | false )" >
<!ELEMENT plist %plistObject;>
<!ATTLIST plist version CDATA "1.0" >
<!-- Collections -->
<!ELEMENT array (%plistObject;)*>
<!ELEMENT dict (key, %plistObject;)*>
<!ELEMENT key (#PCDATA)>
<!--- Primitive types -->
<!ELEMENT string (#PCDATA)>
<!ELEMENT data (#PCDATA)> <!-- Contents interpreted as Base-64 encoded -->
<!ELEMENT date (#PCDATA)> <!-- Contents should conform to a subset of ISO 8601 (in particular, YYYY '-' MM '-' DD 'T' HH ':' MM ':' SS 'Z'. Smaller units may be omitted with a loss of precision) -->
<!-- Numerical primitives -->
<!ELEMENT true EMPTY> <!-- Boolean constant true -->
<!ELEMENT false EMPTY> <!-- Boolean constant false -->
<!ELEMENT real (#PCDATA)> <!-- Contents should represent a floating point number matching ("+" | "-")? d+ ("."d*)? ("E" ("+" | "-") d+)? where d is a digit 0-9. -->
<!ELEMENT integer (#PCDATA)> <!-- Contents should represent a (possibly signed) integer number in base 10 -->
"""
return _HTTPResponse(response: .OK, body: dtd)
}
if uri == "/UnitedKingdom" {
let value = capitals[String(uri.dropFirst())]!
let text = request.getCommaSeparatedHeaders()
//Response header with only path to the location to redirect.
let httpResponse = _HTTPResponse(response: .REDIRECT, headers: "Location: \(value)", body: text)
return httpResponse
}
if uri == "/echo" {
return _HTTPResponse(response: .OK, body: request.messageBody ?? request.body)
}
if uri == "/redirect-with-default-port" {
let text = request.getCommaSeparatedHeaders()
let host = request.headers[1].components(separatedBy: " ")[1]
let ip = host.components(separatedBy: ":")[0]
let httpResponse = _HTTPResponse(response: .REDIRECT, headers: "Location: http://\(ip)/redirected-with-default-port", body: text)
return httpResponse
}
if uri == "/gzipped-response" {
// This is "Hello World!" gzipped.
let helloWorld = Data([0x1f, 0x8b, 0x08, 0x00, 0x6d, 0xca, 0xb2, 0x5c,
0x00, 0x03, 0xf3, 0x48, 0xcd, 0xc9, 0xc9, 0x57,
0x08, 0xcf, 0x2f, 0xca, 0x49, 0x51, 0x04, 0x00,
0xa3, 0x1c, 0x29, 0x1c, 0x0c, 0x00, 0x00, 0x00])
return _HTTPResponse(response: .OK,
headers: ["Content-Length: \(helloWorld.count)",
"Content-Encoding: gzip"].joined(separator: _HTTPUtils.CRLF),
bodyData: helloWorld)
}
return _HTTPResponse(response: .OK, body: capitals[String(uri.dropFirst())]!)
}
func stop() {
httpServer.stop()
}
}
struct ServerError : Error {
let operation: String
let errno: CInt
let file: String
let line: UInt
var _code: Int { return Int(errno) }
var _domain: String { return NSPOSIXErrorDomain }
}
extension ServerError : CustomStringConvertible {
var description: String {
let s = String(validatingUTF8: strerror(errno)) ?? ""
return "\(operation) failed: \(s) (\(_code))"
}
}
public class ServerSemaphore {
let dispatchSemaphore = DispatchSemaphore(value: 0)
public func wait(timeout: DispatchTime) -> DispatchTimeoutResult {
return dispatchSemaphore.wait(timeout: timeout)
}
public func signal() {
dispatchSemaphore.signal()
}
}
class LoopbackServerTest : XCTestCase {
private static let staticSyncQ = DispatchQueue(label: "org.swift.TestFoundation.HTTPServer.StaticSyncQ")
private static var _serverPort: Int = -1
private static let serverReady = ServerSemaphore()
private static var _serverActive = false
private static var testServer: TestURLSessionServer? = nil
static var serverPort: Int {
get {
return staticSyncQ.sync { _serverPort }
}
set {
staticSyncQ.sync { _serverPort = newValue }
}
}
static var serverActive: Bool {
get { return staticSyncQ.sync { _serverActive } }
set { staticSyncQ.sync { _serverActive = newValue }}
}
static func terminateServer() {
serverActive = false
testServer?.stop()
testServer = nil
}
override class func setUp() {
super.setUp()
func runServer(with condition: ServerSemaphore, startDelay: TimeInterval? = nil, sendDelay: TimeInterval? = nil, bodyChunks: Int? = nil) throws {
let server = try TestURLSessionServer(port: nil, startDelay: startDelay, sendDelay: sendDelay, bodyChunks: bodyChunks)
testServer = server
serverPort = Int(server.port)
serverReady.signal()
serverActive = true
while serverActive {
do {
try server.httpServer.listen(notify: condition)
try server.readAndRespond()
if server.httpServer.willReadAgain {
try server.httpServer.listen(notify: condition)
try server.readAndRespondAgain()
}
server.httpServer.socket.closeClient()
} catch {
}
}
serverPort = -2
}
globalDispatchQueue.async {
do {
try runServer(with: serverReady)
} catch {
}
}
let timeout = DispatchTime(uptimeNanoseconds: DispatchTime.now().uptimeNanoseconds + 2_000_000_000)
while serverPort == -1 {
guard serverReady.wait(timeout: timeout) == .success else {
fatalError("Timedout waiting for server to be ready")
}
}
}
override class func tearDown() {
super.tearDown()
terminateServer()
}
}
| 40.732815 | 266 | 0.581436 |
5d744d157996fb291d06db3ce76d9d96de13f0f8 | 411 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
if true {
var d = {
func a((() -> : AnyObject, b : a {
class a("))
}
enum A {
protocol b : a {
protocol B : A {
switch x }
protocol A : c<c> {
class A : Any, b {
class A {
}
}
}
enum A {
class a<T where h: a {
}
}
func b(i: c<T.c {
}
func a(
| 15.222222 | 87 | 0.620438 |
acdfaece658ae247366ece221e7456a646b6439b | 2,104 | //
// EventListView.swift
// SwiftySeatGeek
//
import SwiftUI
struct EventListView: View {
@StateObject private var viewModel = EventListViewModel()
@State private var searchTerm = ""
var body: some View {
SearchNavigation(text: $searchTerm, search: {}, cancel: cancel, content: {
ScrollView {
LazyVStack(alignment: .leading, spacing: 0) {
ForEach(Array(Set(viewModel.eventList).sorted(by: { $0.showtime < $1.showtime })), id: \.id) {
let viewModel = EventViewModel(event: $0)
ZStack(alignment: .leading) {
RoundedRectangle(cornerRadius: 6, style: .continuous)
.fill(Color.white)
NavigationLink(destination: EventDetailView(viewModel: viewModel)) {
EventCardView(viewModel: viewModel)
.padding(.leading)
.padding(.trailing)
}
}
.shadow(color: Color(UIColor.lightGray), radius: 6, x: 2, y: 0)
Spacer(minLength: 15)
}
if !viewModel.isFull {
ActivityIndicator()
.onAppear {
viewModel.loadEvents(query: searchTerm)
}
}
}
.padding(.top, 10)
.padding(.leading, 10)
.padding(.trailing, 10)
}
.navigationBarTitle("Events")
})
.edgesIgnoringSafeArea(.all)
.navigationBarColor(backgroundColor: UIColor(named: "NavigationBlue")!, tintColor: .white)
.onChange(of: searchTerm) { _ in
viewModel.refresh()
}
}
func cancel() {
searchTerm.removeAll()
}
}
struct EventListView_Previews: PreviewProvider {
static var previews: some View {
EventListView()
}
}
| 34.491803 | 114 | 0.47481 |
ef58b98a48a1b35c885a9852e912ec63a1604510 | 5,314 | // MIT license. Copyright (c) 2020 SwiftyFORM. All rights reserved.
import UIKit
import SwiftyFORM
class SignUpViewController: FormViewController {
override func loadView() {
super.loadView()
form_installSubmitButton()
}
override func populate(_ builder: FormBuilder) {
builder.navigationTitle = "Sign Up"
builder.toolbarMode = .simple
builder.demo_showInfo("SocialNetwork 123\nSign up form")
builder += SectionHeaderTitleFormItem().title("Details")
builder += userName
builder += password
builder += email
builder += maleOrFemale
builder += birthday
builder.alignLeft([userName, password, email])
builder += SectionFormItem()
builder += subscribeToNewsletter
builder += SectionFooterTitleFormItem().title("There is no way to unsubscribe our service")
builder += metaData
builder += SectionHeaderTitleFormItem().title("Buttons")
builder += randomizeButton
builder += jsonButton
}
lazy var userName: TextFieldFormItem = {
let instance = TextFieldFormItem()
instance.title("User Name").placeholder("required")
instance.keyboardType = .asciiCapable
instance.autocorrectionType = .no
instance.validate(CharacterSetSpecification.lowercaseLetters, message: "Must be lowercase letters")
instance.submitValidate(CountSpecification.min(6), message: "Length must be minimum 6 letters")
instance.validate(CountSpecification.max(8), message: "Length must be maximum 8 letters")
return instance
}()
lazy var maleOrFemale: ViewControllerFormItem = {
let instance = ViewControllerFormItem()
instance.title("Male or Female").placeholder("required")
instance.createViewController = { (dismissCommand: CommandProtocol) in
let vc = MaleFemaleViewController(dismissCommand: dismissCommand)
return vc
}
instance.willPopViewController = { (context: ViewControllerFormItemPopContext) in
if let x = context.returnedObject as? SwiftyFORM.OptionRowFormItem {
context.cell.detailTextLabel?.text = x.title
} else {
context.cell.detailTextLabel?.text = nil
}
}
return instance
}()
lazy var password: TextFieldFormItem = {
let instance = TextFieldFormItem()
instance.title("PIN Code").password().placeholder("required")
instance.keyboardType = .numberPad
instance.autocorrectionType = .no
instance.validate(CharacterSetSpecification.decimalDigits, message: "Must be digits")
instance.submitValidate(CountSpecification.min(4), message: "Length must be minimum 4 digits")
instance.validate(CountSpecification.max(6), message: "Length must be maximum 6 digits")
return instance
}()
lazy var email: TextFieldFormItem = {
let instance = TextFieldFormItem()
instance.title("Email").placeholder("[email protected]")
instance.keyboardType = .emailAddress
instance.submitValidate(CountSpecification.min(6), message: "Length must be minimum 6 letters")
instance.validate(CountSpecification.max(60), message: "Length must be maximum 60 letters")
instance.softValidate(EmailSpecification(), message: "Must be a valid email address")
return instance
}()
func offsetDate(_ date: Date, years: Int) -> Date {
var dateComponents = DateComponents()
dateComponents.year = years
let calendar = Calendar.current
guard let resultDate = calendar.date(byAdding: dateComponents, to: date) else {
return date
}
return resultDate
}
lazy var birthday: DatePickerFormItem = {
let today = Date()
let instance = DatePickerFormItem()
instance.title = "Birthday"
instance.datePickerMode = .date
instance.minimumDate = self.offsetDate(today, years: -150)
instance.maximumDate = today
return instance
}()
lazy var subscribeToNewsletter: SwitchFormItem = {
let instance = SwitchFormItem()
instance.title = "Subscribe to newsletter"
instance.value = true
return instance
}()
lazy var metaData: MetaFormItem = {
let instance = MetaFormItem()
var dict = [String: AnyObject?]()
dict["key0"] = "I'm hidden text" as AnyObject?
dict["key1"] = "I'm included when exporting to JSON" as AnyObject?
dict["key2"] = "Can be used to pass extra info along with the JSON" as AnyObject?
instance.value(dict as AnyObject?).elementIdentifier("metaData")
return instance
}()
lazy var randomizeButton: ButtonFormItem = {
let instance = ButtonFormItem()
instance.title = "Randomize"
instance.action = { [weak self] in
self?.randomize()
}
return instance
}()
func pickRandom(_ strings: [String]) -> String {
return strings.randomElement() ?? ""
}
func pickRandomDate() -> Date {
let i = Int.random(in: 20...60)
let today = Date()
return offsetDate(today, years: -i)
}
func randomize() {
userName.value = pickRandom(["john", "jane", "steve", "bill", "einstein", "newton"])
password.value = pickRandom(["1234", "0000", "111111", "abc", "111122223333"])
email.value = pickRandom(["[email protected]", "[email protected]", "[email protected]", "[email protected]", "not-a-valid-email"])
birthday.value = pickRandomDate()
subscribeToNewsletter.value = Bool.random()
}
lazy var jsonButton: ButtonFormItem = {
let instance = ButtonFormItem()
instance.title = "View JSON"
instance.action = { [weak self] in
if let vc = self {
DebugViewController.showJSON(vc, jsonData: vc.formBuilder.dump())
}
}
return instance
}()
}
| 34.064103 | 139 | 0.730711 |
ff3d2a8081ddf91c7ae50a88619f392d3aa622bb | 829 | //
// ListCardView.swift
// SwiftUI-Cards
//
// Created by Stadelman, Stan on 11/18/19.
// Copyright © 2019 sap. All rights reserved.
//
import SwiftUI
struct ListItemView: View {
let icon: Icon?
let title: String?
let description: String?
let actions: [Action] = []
let highlight: Highlight?
var body: some View {
HStack(alignment: .center, spacing: 12) {
SafeView(highlight)
HStack(alignment: .center, spacing: 12) {
AsyncImageView(url: icon?.src)
VStack(alignment: .leading, spacing: 3) {
SafeText(title)
SafeText(description).lineLimit(1).opacity(0.6)
}
}
.padding(EdgeInsets(top: 10.5, leading: 0, bottom: 10.5, trailing: 0))
}
}
}
| 25.121212 | 82 | 0.548854 |
ebc27046c18b5e72224abb1d7070a21bbbab1b8b | 5,671 | //
// TSChatViewController+ActionBar.swift
// TSWeChat
//
// Created by Hilen on 1/4/16.
// Copyright © 2016 Hilen. All rights reserved.
//
import Foundation
import RxCocoa
import RxBlocking
// MARK: - @extension TSChatViewController
extension TSChatViewController {
/**
初始化操作栏的 button 事件。包括 声音按钮,录音按钮,表情按钮,分享按钮 等各种事件的交互
*/
func setupActionBarButtonInterAction() {
let voiceButton: TSChatButton = self.chatActionBarView.voiceButton
let recordButton: UIButton = self.chatActionBarView.recordButton
let emotionButton: TSChatButton = self.chatActionBarView.emotionButton
let shareButton: TSChatButton = self.chatActionBarView.shareButton
//切换声音按钮
voiceButton.rx.tap.subscribe {[weak self] _ in
guard let strongSelf = self else { return }
strongSelf.chatActionBarView.resetButtonUI()
//根据不同的状态进行不同的键盘交互
let showRecoring = strongSelf.chatActionBarView.recordButton.isHidden
if showRecoring {
strongSelf.chatActionBarView.showRecording()
voiceButton.emotionSwiftVoiceButtonUI(showKeyboard: true)
strongSelf.controlExpandableInputView(showExpandable: false)
} else {
strongSelf.chatActionBarView.showTyingKeyboard()
voiceButton.emotionSwiftVoiceButtonUI(showKeyboard: false)
strongSelf.controlExpandableInputView(showExpandable: true)
}
}.disposed(by: self.disposeBag)
//录音按钮
var finishRecording: Bool = true //控制滑动取消后的结果,决定停止录音还是取消录音
let longTap = UILongPressGestureRecognizer()
recordButton.addGestureRecognizer(longTap)
longTap.rx.event.subscribe {[weak self] _ in
guard let strongSelf = self else { return }
if longTap.state == .began { //长按开始
finishRecording = true
strongSelf.voiceIndicatorView.recording()
AudioRecordInstance.startRecord()
recordButton.replaceRecordButtonUI(isRecording: true)
} else if longTap.state == .changed { //长按平移
let point = longTap.location(in: self!.voiceIndicatorView)
if strongSelf.voiceIndicatorView.point(inside: point, with: nil) {
strongSelf.voiceIndicatorView.slideToCancelRecord()
finishRecording = false
} else {
strongSelf.voiceIndicatorView.recording()
finishRecording = true
}
} else if longTap.state == .ended { //长按结束
if finishRecording {
AudioRecordInstance.stopRecord()
} else {
AudioRecordInstance.cancelRrcord()
}
strongSelf.voiceIndicatorView.endRecord()
recordButton.replaceRecordButtonUI(isRecording: false)
}
}.disposed(by: self.disposeBag)
//表情按钮
emotionButton.rx.tap.subscribe {[weak self] _ in
guard let strongSelf = self else { return }
strongSelf.chatActionBarView.resetButtonUI()
//设置 button 的UI
emotionButton.replaceEmotionButtonUI(showKeyboard: !emotionButton.showTypingKeyboard)
//根据不同的状态进行不同的键盘交互
if emotionButton.showTypingKeyboard {
strongSelf.chatActionBarView.showTyingKeyboard()
} else {
strongSelf.chatActionBarView.showEmotionKeyboard()
}
strongSelf.controlExpandableInputView(showExpandable: true)
}.disposed(by: self.disposeBag)
//分享按钮
shareButton.rx.tap.subscribe {[weak self] _ in
guard let strongSelf = self else { return }
strongSelf.chatActionBarView.resetButtonUI()
//根据不同的状态进行不同的键盘交互
if shareButton.showTypingKeyboard {
strongSelf.chatActionBarView.showTyingKeyboard()
} else {
strongSelf.chatActionBarView.showShareKeyboard()
}
strongSelf.controlExpandableInputView(showExpandable: true)
}.disposed(by: self.disposeBag)
//文字框的点击,唤醒键盘
let textView: UITextView = self.chatActionBarView.inputTextView
let tap = UITapGestureRecognizer()
textView.addGestureRecognizer(tap)
tap.rx.event.subscribe { _ in
textView.inputView = nil
textView.becomeFirstResponder()
textView.reloadInputViews()
}.disposed(by: self.disposeBag)
}
/**
Control the actionBarView height:
We should make actionBarView's height to original value when the user wants to show recording keyboard.
Otherwise we should make actionBarView's height to currentHeight
- parameter showExpandable: show or hide expandable inputTextView
*/
func controlExpandableInputView(showExpandable: Bool) {
let textView = self.chatActionBarView.inputTextView
let currentTextHeight = self.chatActionBarView.inputTextViewCurrentHeight
UIView.animate(withDuration: 0.3, animations: { () -> Void in
let textHeight = showExpandable ? currentTextHeight : kChatActionBarOriginalHeight
self.chatActionBarView.snp.updateConstraints { (make) -> Void in
make.height.equalTo(textHeight)
}
self.view.layoutIfNeeded()
self.listTableView.scrollBottomToLastRow()
textView?.contentOffset = CGPoint.zero
})
}
}
| 38.842466 | 107 | 0.624052 |
e90b96bbe49f81bfa399ca7806515a84f4bf70ae | 474 | //
// AppDelegate.swift
// StylableNavigationBar
//
// Created by Pavlo Chernovolenko on 09/29/2019.
// Copyright (c) 2019 Pavlo Chernovolenko. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
return true
}
}
| 21.545455 | 145 | 0.725738 |
bbb78d622b64c40209d09a1dbb2ba06c298e2ff1 | 1,042 | //
// MonsterCollectionViewCell.swift
// UhooiPicBook
//
// Created by uhooi on 2020/02/29.
//
import UIKit
final class MonsterCollectionViewCell: UICollectionViewCell {
// MARK: Stored Instance Properties
@IBInspectable private var masksToBounds: Bool = false {
willSet {
self.layer.masksToBounds = newValue
}
}
// MARK: IBOutlets
@IBOutlet private weak var baseView: BaseView!
@IBOutlet private weak var iconImageView: UIImageView!
@IBOutlet private weak var nameLabel: UILabel! {
willSet {
newValue.text = nil
}
}
// MARK: View Life-Cycle Methods
override func prepareForReuse() {
super.prepareForReuse()
self.iconImageView.image = nil
self.nameLabel.text = nil
}
// MARK: Other Internal Methods
func setup(name: String, icon: UIImage, elevation: Double) {
self.nameLabel.text = name
self.iconImageView.image = icon
self.baseView.elevate(elevation: elevation)
}
}
| 21.708333 | 64 | 0.641075 |
f42d63c7e7ca7172c5b589c492c942769277df11 | 1,176 | //
// Vehicle.swift
// Garage
//
// Created by Xiang Li on 28/10/2017.
// Copyright © 2017 Baixing. All rights reserved.
//
import UIKit
import RealmSwift
import Realm
import Foundation
import SKPhotoBrowser
class Vehicle: Object {
@objc dynamic var imageData: Data?
var contentMode: UIViewContentMode = .scaleAspectFill
var index: Int = 0
var image: UIImage? {
get {
if let imageData = imageData {
return UIImage(data: imageData)
}
return nil
}
}
// MARK: - Initializer
required init() {
self.imageData = nil
super.init()
}
required init(value: Any, schema: RLMSchema) {
super.init(value: value, schema: schema)
}
required init(realm: RLMRealm, schema: RLMObjectSchema) {
// wtf?
super.init(realm: realm, schema: schema)
}
init(image: UIImage) {
var imageData = UIImagePNGRepresentation(image)
if imageData == nil {
imageData = UIImageJPEGRepresentation(image, 0.7)
}
self.imageData = imageData
super.init()
}
}
| 20.631579 | 61 | 0.57398 |
628ea60561fc0487761a9ac24b0e576676168c5c | 12,736 | //
// XAxisRendererHorizontalBarChart.swift
// ChartsZyp
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ChartsZyp
//
import Foundation
import CoreGraphics
open class XAxisRendererHorizontalBarChart: XAxisRenderer
{
internal weak var chart: BarChartView?
@objc public init(viewPortHandler: ViewPortHandler, xAxis: XAxis?, transformer: Transformer?, chart: BarChartView)
{
super.init(viewPortHandler: viewPortHandler, xAxis: xAxis, transformer: transformer)
self.chart = chart
}
open override func computeAxis(min: Double, max: Double, inverted: Bool)
{
var min = min, max = max
if let transformer = self.transformer
{
// calculate the starting and entry point of the y-labels (depending on
// zoom / contentrect bounds)
if viewPortHandler.contentWidth > 10 && !viewPortHandler.isFullyZoomedOutY
{
let p1 = transformer.valueForTouchPoint(CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom))
let p2 = transformer.valueForTouchPoint(CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop))
if inverted
{
min = Double(p2.y)
max = Double(p1.y)
}
else
{
min = Double(p1.y)
max = Double(p2.y)
}
}
}
computeAxisValues(min: min, max: max)
}
open override func computeSize()
{
guard let
xAxis = self.axis as? XAxis
else { return }
let longest = xAxis.getLongestLabel() as NSString
let labelSize = longest.size(withAttributes: [NSAttributedString.Key.font: xAxis.labelFont])
let labelWidth = floor(labelSize.width + xAxis.xOffset * 3.5)
let labelHeight = labelSize.height
let labelRotatedSize = CGSize(width: labelSize.width, height: labelHeight).rotatedBy(degrees: xAxis.labelRotationAngle)
xAxis.labelWidth = labelWidth
xAxis.labelHeight = labelHeight
xAxis.labelRotatedWidth = round(labelRotatedSize.width + xAxis.xOffset * 3.5)
xAxis.labelRotatedHeight = round(labelRotatedSize.height)
}
open override func renderAxisLabels(context: CGContext)
{
guard
let xAxis = self.axis as? XAxis
else { return }
if !xAxis.isEnabled || !xAxis.isDrawLabelsEnabled || chart?.data === nil
{
return
}
let xoffset = xAxis.xOffset
if xAxis.labelPosition == .top
{
drawLabels(context: context, pos: viewPortHandler.contentRight + xoffset, anchor: CGPoint(x: 0.0, y: 0.5))
}
else if xAxis.labelPosition == .topInside
{
drawLabels(context: context, pos: viewPortHandler.contentRight - xoffset, anchor: CGPoint(x: 1.0, y: 0.5))
}
else if xAxis.labelPosition == .bottom
{
drawLabels(context: context, pos: viewPortHandler.contentLeft - xoffset, anchor: CGPoint(x: 1.0, y: 0.5))
}
else if xAxis.labelPosition == .bottomInside
{
drawLabels(context: context, pos: viewPortHandler.contentLeft + xoffset, anchor: CGPoint(x: 0.0, y: 0.5))
}
else
{ // BOTH SIDED
drawLabels(context: context, pos: viewPortHandler.contentRight + xoffset, anchor: CGPoint(x: 0.0, y: 0.5))
drawLabels(context: context, pos: viewPortHandler.contentLeft - xoffset, anchor: CGPoint(x: 1.0, y: 0.5))
}
}
/// draws the x-labels on the specified y-position
open override func drawLabels(context: CGContext, pos: CGFloat, anchor: CGPoint)
{
guard
let xAxis = self.axis as? XAxis,
let transformer = self.transformer
else { return }
let labelFont = xAxis.labelFont
let labelTextColor = xAxis.labelTextColor
let labelRotationAngleRadians = xAxis.labelRotationAngle.DEG2RAD
let centeringEnabled = xAxis.isCenterAxisLabelsEnabled
// pre allocate to save performance (dont allocate in loop)
var position = CGPoint(x: 0.0, y: 0.0)
for i in stride(from: 0, to: xAxis.entryCount, by: 1)
{
// only fill x values
position.x = 0.0
if centeringEnabled
{
position.y = CGFloat(xAxis.centeredEntries[i])
}
else
{
position.y = CGFloat(xAxis.entries[i])
}
transformer.pointValueToPixel(&position)
if viewPortHandler.isInBoundsY(position.y)
{
if let label = xAxis.valueFormatter?.stringForValue(xAxis.entries[i], axis: xAxis)
{
drawLabel(
context: context,
formattedLabel: label,
x: pos,
y: position.y,
attributes: [NSAttributedString.Key.font: labelFont, NSAttributedString.Key.foregroundColor: labelTextColor],
anchor: anchor,
angleRadians: labelRotationAngleRadians)
}
}
}
}
@objc open func drawLabel(
context: CGContext,
formattedLabel: String,
x: CGFloat,
y: CGFloat,
attributes: [NSAttributedString.Key : Any],
anchor: CGPoint,
angleRadians: CGFloat)
{
ChartUtils.drawText(
context: context,
text: formattedLabel,
point: CGPoint(x: x, y: y),
attributes: attributes,
anchor: anchor,
angleRadians: angleRadians)
}
open override var gridClippingRect: CGRect
{
var contentRect = viewPortHandler.contentRect
let dy = self.axis?.gridLineWidth ?? 0.0
contentRect.origin.y -= dy / 2.0
contentRect.size.height += dy
return contentRect
}
private var _gridLineSegmentsBuffer = [CGPoint](repeating: CGPoint(), count: 2)
open override func drawGridLine(context: CGContext, x: CGFloat, y: CGFloat)
{
if viewPortHandler.isInBoundsY(y)
{
context.beginPath()
context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: y))
context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: y))
context.strokePath()
}
}
open override func renderAxisLine(context: CGContext)
{
guard let xAxis = self.axis as? XAxis else { return }
if !xAxis.isEnabled || !xAxis.isDrawAxisLineEnabled
{
return
}
context.saveGState()
context.setStrokeColor(xAxis.axisLineColor.cgColor)
context.setLineWidth(xAxis.axisLineWidth)
if xAxis.axisLineDashLengths != nil
{
context.setLineDash(phase: xAxis.axisLineDashPhase, lengths: xAxis.axisLineDashLengths)
}
else
{
context.setLineDash(phase: 0.0, lengths: [])
}
if xAxis.labelPosition == .top ||
xAxis.labelPosition == .topInside ||
xAxis.labelPosition == .bothSided
{
context.beginPath()
context.move(to: CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentTop))
context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentBottom))
context.strokePath()
}
if xAxis.labelPosition == .bottom ||
xAxis.labelPosition == .bottomInside ||
xAxis.labelPosition == .bothSided
{
context.beginPath()
context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop))
context.addLine(to: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom))
context.strokePath()
}
context.restoreGState()
}
open override func renderLimitLines(context: CGContext)
{
guard
let xAxis = self.axis as? XAxis,
let transformer = self.transformer
else { return }
var limitLines = xAxis.limitLines
if limitLines.count == 0
{
return
}
let trans = transformer.valueToPixelMatrix
var position = CGPoint(x: 0.0, y: 0.0)
for i in 0 ..< limitLines.count
{
let l = limitLines[i]
if !l.isEnabled
{
continue
}
context.saveGState()
defer { context.restoreGState() }
var clippingRect = viewPortHandler.contentRect
clippingRect.origin.y -= l.lineWidth / 2.0
clippingRect.size.height += l.lineWidth
context.clip(to: clippingRect)
position.x = 0.0
position.y = CGFloat(l.limit)
position = position.applying(trans)
context.beginPath()
context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: position.y))
context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: position.y))
context.setStrokeColor(l.lineColor.cgColor)
context.setLineWidth(l.lineWidth)
if l.lineDashLengths != nil
{
context.setLineDash(phase: l.lineDashPhase, lengths: l.lineDashLengths!)
}
else
{
context.setLineDash(phase: 0.0, lengths: [])
}
context.strokePath()
let label = l.label
// if drawing the limit-value label is enabled
if l.drawLabelEnabled && label.count > 0
{
let labelLineHeight = l.valueFont.lineHeight
let xOffset: CGFloat = 4.0 + l.xOffset
let yOffset: CGFloat = l.lineWidth + labelLineHeight + l.yOffset
if l.labelPosition == .topRight
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: viewPortHandler.contentRight - xOffset,
y: position.y - yOffset),
align: .right,
attributes: [NSAttributedString.Key.font: l.valueFont, NSAttributedString.Key.foregroundColor: l.valueTextColor])
}
else if l.labelPosition == .bottomRight
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: viewPortHandler.contentRight - xOffset,
y: position.y + yOffset - labelLineHeight),
align: .right,
attributes: [NSAttributedString.Key.font: l.valueFont, NSAttributedString.Key.foregroundColor: l.valueTextColor])
}
else if l.labelPosition == .topLeft
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: viewPortHandler.contentLeft + xOffset,
y: position.y - yOffset),
align: .left,
attributes: [NSAttributedString.Key.font: l.valueFont, NSAttributedString.Key.foregroundColor: l.valueTextColor])
}
else
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: viewPortHandler.contentLeft + xOffset,
y: position.y + yOffset - labelLineHeight),
align: .left,
attributes: [NSAttributedString.Key.font: l.valueFont, NSAttributedString.Key.foregroundColor: l.valueTextColor])
}
}
}
}
}
| 35.67507 | 137 | 0.536746 |
38f6dd876695e0231e9ef7e9b739f3f5c8721bc8 | 3,738 | import XCTest
@testable import PostgresNIO
class Date_PSQLCodableTests: XCTestCase {
func testNowRoundTrip() {
let value = Date()
var buffer = ByteBuffer()
value.encode(into: &buffer, context: .forTests())
XCTAssertEqual(value.psqlType, .timestamptz)
XCTAssertEqual(buffer.readableBytes, 8)
let data = PSQLData(bytes: buffer, dataType: .timestamptz, format: .binary)
var result: Date?
XCTAssertNoThrow(result = try data.decode(as: Date.self, context: .forTests()))
XCTAssertEqual(value, result)
}
func testDecodeRandomDate() {
var buffer = ByteBuffer()
buffer.writeInteger(Int64.random(in: Int64.min...Int64.max))
let data = PSQLData(bytes: buffer, dataType: .timestamptz, format: .binary)
var result: Date?
XCTAssertNoThrow(result = try data.decode(as: Date.self, context: .forTests()))
XCTAssertNotNil(result)
}
func testDecodeFailureInvalidLength() {
var buffer = ByteBuffer()
buffer.writeInteger(Int64.random(in: Int64.min...Int64.max))
buffer.writeInteger(Int64.random(in: Int64.min...Int64.max))
let data = PSQLData(bytes: buffer, dataType: .timestamptz, format: .binary)
XCTAssertThrowsError(try data.decode(as: Date.self, context: .forTests())) { error in
XCTAssert(error is PSQLCastingError)
}
}
func testDecodeDate() {
var firstDateBuffer = ByteBuffer()
firstDateBuffer.writeInteger(Int32.min)
let firstDateData = PSQLData(bytes: firstDateBuffer, dataType: .date, format: .binary)
var firstDate: Date?
XCTAssertNoThrow(firstDate = try firstDateData.decode(as: Date.self, context: .forTests()))
XCTAssertNotNil(firstDate)
var lastDateBuffer = ByteBuffer()
lastDateBuffer.writeInteger(Int32.max)
let lastDateData = PSQLData(bytes: lastDateBuffer, dataType: .date, format: .binary)
var lastDate: Date?
XCTAssertNoThrow(lastDate = try lastDateData.decode(as: Date.self, context: .forTests()))
XCTAssertNotNil(lastDate)
}
func testDecodeDateFromTimestamp() {
var firstDateBuffer = ByteBuffer()
firstDateBuffer.writeInteger(Int32.min)
let firstDateData = PSQLData(bytes: firstDateBuffer, dataType: .date, format: .binary)
var firstDate: Date?
XCTAssertNoThrow(firstDate = try firstDateData.decode(as: Date.self, context: .forTests()))
XCTAssertNotNil(firstDate)
var lastDateBuffer = ByteBuffer()
lastDateBuffer.writeInteger(Int32.max)
let lastDateData = PSQLData(bytes: lastDateBuffer, dataType: .date, format: .binary)
var lastDate: Date?
XCTAssertNoThrow(lastDate = try lastDateData.decode(as: Date.self, context: .forTests()))
XCTAssertNotNil(lastDate)
}
func testDecodeDateFailsWithToMuchData() {
var buffer = ByteBuffer()
buffer.writeInteger(Int64(0))
let data = PSQLData(bytes: buffer, dataType: .date, format: .binary)
XCTAssertThrowsError(try data.decode(as: Date.self, context: .forTests())) { error in
XCTAssert(error is PSQLCastingError)
}
}
func testDecodeDateFailsWithWrongDataType() {
var buffer = ByteBuffer()
buffer.writeInteger(Int64(0))
let data = PSQLData(bytes: buffer, dataType: .int8, format: .binary)
XCTAssertThrowsError(try data.decode(as: Date.self, context: .forTests())) { error in
XCTAssert(error is PSQLCastingError)
}
}
}
| 38.142857 | 99 | 0.639647 |
eff4e9a5eb26ed5ab223f0a689c4db53b88e11cd | 1,675 | //
// HCAssociationAlbumsInfoModel.swift
// RxXMLY
//
// Created by sessionCh on 2018/2/6.
// Copyright © 2018年 sessionCh. All rights reserved.
//
/*
albumId : 4633831
coverMiddle : "http://fdfs.xmcdn.com/group26/M03/24/99/wKgJWFjKkOfhtj-SAAFdYJM1p44447_mobile_small.jpg"
coverSmall : "http://fdfs.xmcdn.com/group26/M03/24/99/wKgJWFjKkOfhtj-SAAFdYJM1p44447_mobile_small.jpg"
discountedPrice : 180
displayDiscountedPrice : "180.00喜点"
displayPrice : "180.00喜点"
displayVipPrice : "171.00喜点"
intro : "此专辑《每天听见吴晓波2016-2017》已经完更"
isDraft : false
isPaid : true
isVipFree : false
price : 180
priceTypeEnum : 2
priceTypeId : 2
priceUnit : "喜点"
recSrc : "MAIN"
recTrack : "ItemG.5"
refundSupportType : 0
title : "每天听见吴晓波·第一季"
uid : 12495477
updatedAt : 1517463574000
vipPrice : 171
*/
import Foundation
import ObjectMapper
struct HCAssociationAlbumsInfoModel: Mappable {
init?(map: Map) {
}
mutating func mapping(map: Map) {
albumId <- map["albumId"]
coverMiddle <- map["coverMiddle"]
displayDiscountedPrice <- map["displayDiscountedPrice"]
intro <- map["intro"]
title <- map["title"]
updatedAt <- map["updatedAt"]
discountedPrice <- map["discountedPrice"]
uid <- map["uid"]
isVipFree <- map["isVipFree"]
isPaid <- map["isPaid"]
}
var albumId: UInt32 = 0
var coverMiddle = ""
var displayDiscountedPrice = ""
var intro = ""
var title = ""
var updatedAt: UInt32 = 0
var discountedPrice: CGFloat = 0
var uid: UInt32 = 0
var isVipFree: Bool = false
var isPaid: Bool = false
}
| 23.263889 | 104 | 0.645373 |
335b200311708b83fd708b726e3c74b897c930db | 1,522 | //
// SceneDelegate.swift
// Swedish-Slovak Dictionary
//
// Created by Michal Špano on 09/11/2020.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
}
func sceneWillResignActive(_ scene: UIScene) {
}
func sceneWillEnterForeground(_ scene: UIScene) {
}
func sceneDidEnterBackground(_ scene: UIScene) {
}
}
| 32.382979 | 147 | 0.714849 |
1ac43bb2f3c25aacf096b15adf88fd7348382706 | 417 | // 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: "Palette",
platforms: [.iOS(.v14), .macOS(.v10_15)],
products: [
.library(name: "Palette", targets: ["Palette"])
],
dependencies: [],
targets: [
.target(name: "Palette", dependencies: [])
]
)
| 24.529412 | 96 | 0.630695 |
d51638b0827f57311c360134beec0f6b63ee8dd9 | 4,857 | // The MIT License (MIT) - Copyright (c) 2016 Carlos Vidal
//
// 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 XCTest
@testable import EasyPeasy
class ReferenceAttributeTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testThatOppositeAttributesAreCorrect() {
// given
// when
// then
XCTAssertTrue(ReferenceAttribute.Width.opposite == .Width)
XCTAssertTrue(ReferenceAttribute.Height.opposite == .Height)
XCTAssertTrue(ReferenceAttribute.Left.opposite == .Right)
XCTAssertTrue(ReferenceAttribute.Right.opposite == .Left)
XCTAssertTrue(ReferenceAttribute.Top.opposite == .Bottom)
XCTAssertTrue(ReferenceAttribute.Bottom.opposite == .Top)
XCTAssertTrue(ReferenceAttribute.Leading.opposite == .Trailing)
XCTAssertTrue(ReferenceAttribute.Trailing.opposite == .Leading)
XCTAssertTrue(ReferenceAttribute.CenterX.opposite == .CenterX)
XCTAssertTrue(ReferenceAttribute.CenterY.opposite == .CenterY)
XCTAssertTrue(ReferenceAttribute.LastBaseline.opposite == .LastBaseline)
}
func testThatOppositeAttributesAreCorrectiOS8AndAbove() {
XCTAssertTrue(ReferenceAttribute.FirstBaseline.opposite == .FirstBaseline)
XCTAssertTrue(ReferenceAttribute.LeftMargin.opposite == .RightMargin)
XCTAssertTrue(ReferenceAttribute.RightMargin.opposite == .LeftMargin)
XCTAssertTrue(ReferenceAttribute.TopMargin.opposite == .BottomMargin)
XCTAssertTrue(ReferenceAttribute.BottomMargin.opposite == .TopMargin)
XCTAssertTrue(ReferenceAttribute.LeadingMargin.opposite == .TrailingMargin)
XCTAssertTrue(ReferenceAttribute.TrailingMargin.opposite == .LeadingMargin)
XCTAssertTrue(ReferenceAttribute.CenterXWithinMargins.opposite == .CenterXWithinMargins)
XCTAssertTrue(ReferenceAttribute.CenterYWithinMargins.opposite == .CenterYWithinMargins)
XCTAssertTrue(ReferenceAttribute.NotAnAttribute.opposite == .NotAnAttribute)
}
func testThatAutoLayoutEquivalentIsTheExpected() {
// given
// when
// then
XCTAssertTrue(ReferenceAttribute.Width.layoutAttribute == .Width)
XCTAssertTrue(ReferenceAttribute.Height.layoutAttribute == .Height)
XCTAssertTrue(ReferenceAttribute.Left.layoutAttribute == .Left)
XCTAssertTrue(ReferenceAttribute.Right.layoutAttribute == .Right)
XCTAssertTrue(ReferenceAttribute.Top.layoutAttribute == .Top)
XCTAssertTrue(ReferenceAttribute.Bottom.layoutAttribute == .Bottom)
XCTAssertTrue(ReferenceAttribute.Leading.layoutAttribute == .Leading)
XCTAssertTrue(ReferenceAttribute.Trailing.layoutAttribute == .Trailing)
XCTAssertTrue(ReferenceAttribute.CenterX.layoutAttribute == .CenterX)
XCTAssertTrue(ReferenceAttribute.CenterY.layoutAttribute == .CenterY)
XCTAssertTrue(ReferenceAttribute.LastBaseline.layoutAttribute == .LastBaseline)
XCTAssertTrue(ReferenceAttribute.Width.layoutAttribute == .Width)
}
func testThatAutoLayoutEquivalentIsTheExpectediOS8AndAbove() {
// given
// when
// then
XCTAssertTrue(ReferenceAttribute.FirstBaseline.layoutAttribute == .FirstBaseline)
XCTAssertTrue(ReferenceAttribute.LeftMargin.layoutAttribute == .LeftMargin)
XCTAssertTrue(ReferenceAttribute.RightMargin.layoutAttribute == .RightMargin)
XCTAssertTrue(ReferenceAttribute.TopMargin.layoutAttribute == .TopMargin)
XCTAssertTrue(ReferenceAttribute.BottomMargin.layoutAttribute == .BottomMargin)
XCTAssertTrue(ReferenceAttribute.LeadingMargin.layoutAttribute == .LeadingMargin)
XCTAssertTrue(ReferenceAttribute.TrailingMargin.layoutAttribute == .TrailingMargin)
XCTAssertTrue(ReferenceAttribute.CenterXWithinMargins.layoutAttribute == .CenterXWithinMargins)
XCTAssertTrue(ReferenceAttribute.CenterYWithinMargins.layoutAttribute == .CenterYWithinMargins)
XCTAssertTrue(ReferenceAttribute.NotAnAttribute.layoutAttribute == .NotAnAttribute)
}
func testThatNotAnAttributeDoesNotHaveConflictingAttributes() {
// given
// when
// then
XCTAssertTrue(ReferenceAttribute.NotAnAttribute.conflictingAttributes.count == 0)
}
}
| 50.072165 | 103 | 0.738522 |
0ec38f2493414418ea71931c732ed2abe233c46d | 13,499 | // Copyright © 2019 Poikile Creations. All rights reserved.
import CoreData
import os
import PromiseKit
import Stylobate
import SwiftDiscogs
public class DiscogsCollectionImporter: NSManagedObjectContext {
public enum ImportError: Error {
/// If no Discogs folder with an ID of `0` was retrieved. Since *every*
/// user's collection has a `0` folder, this probably indicates that
/// `Discogs.collectionFolders()` failed.
case noAllFolderWasFound
/// If a `weak self` in a block became `nil` before the block was
/// executed. This is theoretically possible if the block operation
/// was queued for a long time.
case selfWentOutOfScope
}
public typealias CoreDataFieldsByID = [Int: CustomField]
public typealias CoreDataFoldersByID = [Int: Folder]
public typealias CoreDataItemsByID = [Int: CollectionItem]
// MARK: - Properties
private var coreDataFieldsByID = CoreDataFieldsByID()
private var coreDataFoldersByID = CoreDataFoldersByID()
private var coreDataItemsByID = CoreDataItemsByID()
private var discogs: Discogs = DiscogsManager.discogs
private var discogsFields = [SwiftDiscogs.CollectionCustomField]()
private var discogsFolders = [SwiftDiscogs.CollectionFolder]()
public weak var importerDelegate: ImportableServiceDelegate?
public weak var service: ImportableService?
private var importQueue = DispatchQueue(label: "DiscogsCollectionImporter",
qos: .background,
attributes: .concurrent,
autoreleaseFrequency: .inherit,
target: nil)
// MARK: - Import Functions
public func importDiscogsCollection(forUserName userName: String) -> Promise<Void> {
importerDelegate?.willBeginImporting(fromService: service)
return discogs.customCollectionFields(forUserName: userName)
.then(on: importQueue) { (discogsFieldsResult) -> Promise<CoreDataFieldsByID> in
self.discogsFields = discogsFieldsResult.fields ?? []
self.importerDelegate?.update(importedItemCount: 1, totalCount: 6, forService: self.service)
return self.createCoreDataFields(self.discogsFields)
}.then(on: importQueue) { _ -> Promise<CollectionFolders> in
self.importerDelegate?.update(importedItemCount: 2, totalCount: 6, forService: self.service)
return self.discogs.collectionFolders(forUserName: userName)
}.then(on: importQueue) { (discogsFoldersResult) -> Promise<CoreDataFoldersByID> in
self.discogsFolders = discogsFoldersResult.folders
self.importerDelegate?.update(importedItemCount: 3, totalCount: 6, forService: self.service)
return self.createCoreDataFolders(forDiscogsFolders: discogsFoldersResult.folders)
}.then(on: importQueue) { (coreDataFoldersByID) -> Promise<[CollectionFolderItem]> in
let masterFolderID = 0
guard let masterFolder = coreDataFoldersByID[masterFolderID] else {
throw ImportError.noAllFolderWasFound
}
self.importerDelegate?.update(importedItemCount: 4, totalCount: 6, forService: self.service)
return self.downloadDiscogsItems(forUserName: userName,
inFolderWithID: 0,
expectedItemCount: Int(masterFolder.expectedItemCount))
}.then(on: importQueue) { (discogsItems) -> Promise<CoreDataItemsByID> in
print("Importing \(discogsItems.count) Discogs collection items.")
self.importerDelegate?.update(importedItemCount: 5, totalCount: 6, forService: self.service)
return self.createCoreDataItems(forDiscogsItems: discogsItems)
}.then(on: importQueue) { _ -> Promise<Void> in
self.importerDelegate?.update(importedItemCount: 6, totalCount: 6, forService: self.service)
return self.addCoreDataItemsToOtherFolders(forUserName: userName)
}.then(on: importQueue) { _ -> Promise<Void> in
self.importerDelegate?.willFinishImporting(fromService: self.service)
try self.save()
return Promise<Void>()
}
}
/// Import the custom fields that the user has defined. The
/// `CustomCollectionField.fetchOrCreateEntity()` is a bit different from
/// the other managed objects' `fetchOrCreate()`s because there are two
/// custom field types (dropdown and textarea), and the appropriate one has
/// to be created.
public func createCoreDataFields(_ discogsFields: [CollectionCustomField]) -> Promise<CoreDataFieldsByID> {
return Promise<CoreDataFieldsByID> { (seal) in
coreDataFieldsByID = [:]
try discogsFields.forEach { [weak self] (discogsField) in
guard let self = self else {
throw ImportError.selfWentOutOfScope
}
let coreDataField = try CustomField.fetchOrCreateEntity(fromDiscogsField: discogsField, inContext: self)
coreDataFieldsByID[discogsField.id] = coreDataField
}
seal.fulfill(coreDataFieldsByID)
}
}
public func createCoreDataFolders(forDiscogsFolders discogsFolders: [CollectionFolder]) -> Promise<CoreDataFoldersByID> {
return Promise<CoreDataFoldersByID> { [weak self] (seal) in
coreDataFoldersByID = [:]
guard let self = self else {
throw ImportError.selfWentOutOfScope
}
try discogsFolders.forEach { (discogsFolder) in
let request: NSFetchRequest<Folder> = Folder.fetchRequest(sortDescriptors: [(\Folder.folderID).sortDescriptor()],
predicate: NSPredicate(format: "folderID == \(discogsFolder.id)"))
let coreDataFolder: Folder = try self.fetchOrCreate(withRequest: request) { (folder) in
folder.update(withDiscogsFolder: discogsFolder)
}
coreDataFoldersByID[discogsFolder.id] = coreDataFolder
}
seal.fulfill(coreDataFoldersByID)
}
}
public func downloadDiscogsItems(forUserName userName: String,
inFolderWithID folderID: Int,
expectedItemCount: Int) -> Promise<[CollectionFolderItem]> {
let pageSize = 500
let pageCount = (expectedItemCount / pageSize) + 1
let pagePromises: [Promise<CollectionFolderItems>] = pageCount.times.map { (pageNumber) -> Promise<CollectionFolderItems> in
return discogs.collectionItems(inFolderID: folderID,
userName: userName,
pageNumber: pageNumber + 1,
resultsPerPage: pageSize)
}
return when(resolved: pagePromises).then { (discogsItemsResults) in
return Promise<[CollectionFolderItem]> { (seal) in
let discogsItems = discogsItemsResults.reduce([CollectionFolderItem]()) { (allItems, result) in
switch result {
case .fulfilled(let discogsCollectionItems):
return allItems + (discogsCollectionItems.releases ?? [])
default:
return allItems
}
}
seal.fulfill(discogsItems)
}
}
}
public func createCoreDataItems(forDiscogsItems discogsItems: [SwiftDiscogs.CollectionFolderItem]) -> Promise<CoreDataItemsByID> {
return Promise<CoreDataItemsByID> { (seal) in
coreDataItemsByID = [:]
try discogsItems.forEach { (discogsItem) in
let request: NSFetchRequest<CollectionItem> = CollectionItem.fetchRequest(sortDescriptors: [],
predicate: CollectionItem.uniquePredicate(forReleaseVersionID: discogsItem.id))
let coreDataItem = try self.fetchOrCreate(withRequest: request) { (item) in
do {
try item.update(withDiscogsItem: discogsItem,
coreDataFields: coreDataFieldsByID,
inContext: self)
} catch {
os_log(.debug, "Failed to update CoreData fields for Discogs item %d", discogsItem.id)
}
}
coreDataItemsByID[discogsItem.id] = coreDataItem
}
seal.fulfill(coreDataItemsByID)
}
}
func addCoreDataItemsToOtherFolders(forUserName userName: String) -> Promise<Void> {
let folderPromises: [Promise<Void>] = discogsFolders.filter { $0.id != 0 }.map { (discogsFolder) -> Promise<Void> in
guard let coreDataFolder = self.coreDataFoldersByID[discogsFolder.id] else {
return Promise<Void>()
}
return downloadDiscogsItems(forUserName: userName,
inFolderWithID: discogsFolder.id,
expectedItemCount: discogsFolder.count).done { (discogsItems) in
print("Discogs folder \"\(discogsFolder.name)\" should have \(discogsItems.count) items:")
var coreDataItemCount = 0
discogsItems.forEach { (discogsItem) in
if let coreDataItem = self.coreDataItemsByID[discogsItem.id] {
print(" [\(coreDataItemCount + 1)] \(discogsItem.basicInformation!.title) (\(discogsItem.id))")
coreDataItem.addToFolders(coreDataFolder)
coreDataItemCount += 1
} else {
print("Failed to find or create a Core Data item for Discogs item \(discogsItem.id)!")
}
}
}
}
return when(resolved: folderPromises).then { (results) in
return Promise<Void> { (seal) in
results.forEach { (result) in
switch result {
case .rejected(let error):
seal.reject(error)
default:
break
// seal.fulfill()
}
}
}
}
}
}
public extension SwiftDiscogsApp.CollectionItem {
static func uniquePredicate(forReleaseVersionID releaseVersionID: Int) -> NSPredicate {
return NSPredicate(format: "releaseVersionID == \(releaseVersionID)")
}
func update(withDiscogsItem discogsItem: SwiftDiscogs.CollectionFolderItem,
coreDataFields: DiscogsCollectionImporter.CoreDataFieldsByID,
inContext context: NSManagedObjectContext) throws {
self.rating = Int16(discogsItem.rating)
self.releaseVersionID = Int64(discogsItem.id)
// Import the custom fields.
try discogsItem.notes?.forEach { (discogsNote) in
guard let discogsItemID = discogsItem.basicInformation?.id,
let coreDataField = coreDataFields[discogsNote.fieldId] else {
return
}
let fieldPredicate = CollectionItemField.uniquePredicate(forReleaseVersionID: discogsItemID,
fieldID: discogsNote.fieldId)
let request: NSFetchRequest<CollectionItemField> = CollectionItemField.fetchRequest(sortDescriptors: [],
predicate: fieldPredicate)
_ = try context.fetchOrCreate(withRequest: request) { (field) in
field.update(withDiscogsNote: discogsNote,
customField: coreDataField,
collectionItem: self)
}
}
}
}
public extension SwiftDiscogsApp.CollectionItemField {
static func uniquePredicate(forReleaseVersionID releaseVersionID: Int,
fieldID: Int) -> NSPredicate {
return NSPredicate(format: "collectionItem.releaseVersionID == \(Int64(releaseVersionID))")
+ NSPredicate(format: "customField.id == \(Int64(fieldID))")
}
func update(withDiscogsNote discogsNote: SwiftDiscogs.CollectionFolderItem.Note,
customField: SwiftDiscogsApp.CustomField,
collectionItem: SwiftDiscogsApp.CollectionItem) {
self.value = discogsNote.value
self.customField = customField
self.collectionItem = collectionItem
}
}
public extension SwiftDiscogsApp.Folder {
func update(withDiscogsFolder discogsFolder: SwiftDiscogs.CollectionFolder) {
self.folderID = Int64(discogsFolder.id)
self.name = discogsFolder.name
self.expectedItemCount = Int64(discogsFolder.count)
}
}
| 44.847176 | 169 | 0.590044 |
6ad9a008f0278c84c84053b3eb9b1f8f1f8b1529 | 1,447 | //
// RJCustomPresentVC.swift
// SwiftPractice
//
// Created by 吴蕾君 on 16/2/15.
// Copyright © 2016年 rayjuneWu. All rights reserved.
//
import UIKit
class RJCustomPresentVC: UIViewController {
@IBOutlet weak var someButton:UIButton!
let transition = BubbleTransition()
override func viewDidLoad() {
super.viewDidLoad()
title = "CustomPresent"
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let controller = segue.destinationViewController
controller.transitioningDelegate = self
controller.modalPresentationStyle = .Custom
}
}
extension RJCustomPresentVC:UIViewControllerTransitioningDelegate{
func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
transition.transitionMode = .Present
transition.startingPoint = someButton.center
transition.bubbleColor = someButton.backgroundColor!
return transition
}
func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
transition.transitionMode = .Dismiss
transition.startingPoint = someButton.center
transition.bubbleColor = someButton.backgroundColor!
return transition
}
}
| 31.456522 | 217 | 0.737388 |
e897d4934a0c3bae92ee44691dfcdc3530c0b8a3 | 1,399 | //
// AmTextDefaultButtonStyle.swift
// XGArqmobUI
//
// Created by Vero on 07/05/2020.
// Copyright © 2020 Sixtema. All rights reserved.
//
import UIKit
@objc
open class AmTextDefaultButtonStyle: NSObject {
@objc public override init() {}
private let bundle = Bundle(for: AmDefaultButtonStyle.self)
/**
The title color for normal state. Default is `white` .
*/
@objc public var titleColorNormal: UIColor = UIColor(named: "buttonEnableColor") ?? UIColor(named: "buttonEnableColor", in: Bundle(for: AmDefaultButton.self), compatibleWith: nil) ?? .darkGray
/**
The title color for highlighted state. Default is `white` .
*/
@objc public var titleColorHighlighted: UIColor = UIColor(named: "buttonHighlightedColor") ?? UIColor(named: "buttonHighlightedColor", in: Bundle(for: AmDefaultButton.self), compatibleWith: nil) ?? .darkGray
/**
The title color for disabled state. Default is `white` .
*/
@objc public var titleColorDisabled: UIColor = UIColor(named: "buttonDisabledColor") ?? UIColor(named: "buttonDisabledColor", in: Bundle(for: AmDefaultButton.self), compatibleWith: nil) ?? .darkGray
/**
The title font. Default is `Raleway-Semibold 15`.
*/
@objc public var titleFont: UIFont = UIFont(name: "Raleway-Semibold", size: 15) ?? UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.semibold)
}
| 38.861111 | 211 | 0.694067 |
0a26710514888c92d99c41f1fe036c720704c6f5 | 684 | //
// FeaturedLandmarksViewModel.swift
// SwiftUIExample
//
// Created by 이광용 on 2019/06/18.
// Copyright © 2019 GwangYongLee. All rights reserved.
//
import SwiftUI
import Combine
final class FeaturedLandmarksViewModel {
private let landmarks: [Landmark]
private weak var repository: Repository<Landmark>!
var itemViewModels: [LandmarkDetailViewModel] {
return landmarks.map {
LandmarkDetailViewModel(landmark: $0,
repository: self.repository) }
}
init(landmarks: [Landmark],
repository: Repository<Landmark>) {
self.landmarks = landmarks
self.repository = repository
}
}
| 26.307692 | 66 | 0.656433 |
9bbab6223f0ef33bb77df0cdd53fbdddcf7c1b02 | 766 | import Foundation
class FileUtil {
public static func getUrl(_ fileName: String, fileExt: String) -> URL? {
Bundle.main.url(forResource: fileName, withExtension: fileExt)
}
public static func readAsString(_ fileName: String, fileExt: String) -> String? {
let path = Bundle.main.path(forResource: fileName, ofType: fileExt)
return try? String(contentsOfFile:path!, encoding: String.Encoding.utf8)
}
public static func parseFileAsModel<T: Decodable>(fileName: String, fileExt: String, clazz: T.Type) -> T? {
guard let text = readAsString(fileName, fileExt: fileExt) else { return nil }
let jsonData: Data = text.data(using: .utf8)!
return try? JSONDecoder().decode(clazz, from: jsonData)
}
}
| 38.3 | 111 | 0.681462 |
03278f157c945dd139d0d4fa2d8fe599913cb52a | 3,088 | //
// The MIT License (MIT)
//
// Copyright (c) 2019 DeclarativeHub/Bond
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import Differ
public extension RangeReplaceableTreeNode {
public func diff(_ other: Self, sourceRoot: IndexPath = [], destinationRoot: IndexPath = [], areValuesEqual: @escaping (ChildNode.Value, ChildNode.Value) -> Bool) -> OrderedCollectionDiff<IndexPath> {
let isEqual: (ChildNode, ChildNode) -> Bool = { lhs, rhs in areValuesEqual(lhs.value, rhs.value) }
let traces = children.outputDiffPathTraces(to: other.children, isEqual: isEqual)
let diff = Diff(traces: traces)
var collectionDiff = OrderedCollectionDiff(from: diff, sourceRoot: sourceRoot, destinationRoot: destinationRoot)
for trace in traces {
if trace.from.x + 1 == trace.to.x && trace.from.y + 1 == trace.to.y {
// match point x -> y, diff children
let childA = children[trace.from.x]
let childB = other.children[trace.from.y]
let childDiff = childA.diff(
childB,
sourceRoot: sourceRoot.appending(trace.from.x),
destinationRoot: destinationRoot.appending(trace.from.y),
areValuesEqual: areValuesEqual
)
collectionDiff.merge(childDiff)
} else if trace.from.y < trace.to.y {
// inserted, do nothing
} else {
// deleted, do nothing
}
}
return collectionDiff
}
}
extension OrderedCollectionDiff where Index == IndexPath {
public init(from diff: Diff, sourceRoot: IndexPath, destinationRoot: IndexPath) {
self.init()
for element in diff.elements {
switch element {
case .insert(let at):
inserts.append(destinationRoot.appending(at))
case .delete(let at):
deletes.append(sourceRoot.appending(at))
}
}
}
}
| 42.30137 | 204 | 0.647992 |
72388cad2ec11a6b0303c6aa9bee2a875079e25f | 804 | //
// UserInfo.swift
// upbitBar
//
// Created by Fernando on 2021/03/09.
//
import Foundation
@propertyWrapper
struct UserInfo<T> {
private let key: String
private let defaultValue: T
var wrappedValue: T {
get { return UserDefaults.standard.object(forKey: key) as? T ?? defaultValue }
set { UserDefaults.standard.set(newValue, forKey: key) }
}
init(key: String, defaultValue: T) {
self.key = key
self.defaultValue = defaultValue
}
}
struct UPbitKeys {
@UserInfo(key: UpbitKey.accessKey.rawValue, defaultValue: "") var accessToken: String
@UserInfo(key: UpbitKey.secretKey.rawValue, defaultValue: "") var secretToken: String
@UserInfo(key: UpbitKey.refreshInterval.rawValue, defaultValue: 1) var refershInterVal: Int
}
| 25.125 | 95 | 0.677861 |
487a87c016c2fa04948f11e47cfa0df273d09139 | 4,518 | //
// Solver.swift
//
// Created by Michel Tilman on 27/10/2021.
// Copyright © 2021 Dotted.Pair.
// Licensed under Apache License v2.0.
//
import PythonKit
/**
Solver for a linear programming model.
Solving a model consists in the following steps:
1. Convert the model into a Python (PuLP) LpProblem.
2. Solve the problem with the default PuLP solver.
3. Construct a ``Solver/Result`` from the (Pulp) problem data.
*/
public struct Solver {
// MARK: -
/// Status of the solver result.
///
/// Raw enum values map one-to-one onto PuLP status values.
public enum Status: Double {
case unsolved = 0
case optimal = 1
case infeasible = -1
case unbounded = -2
case undefined = -3
}
// MARK: -
/// Result of the solver.
/// Contains status of solver result and values for the variables.
public struct Result {
// MARK: -
/// Status of the result.
public let status: Status
/// Computed values for the decision variables, keyed by the variable names.
public let variables: [String: Double]
// MARK: -
/// Creates a result with given status and variable bindings.
///
/// - Parameters:
/// - status: Status of the solver result.
/// - variables: Dictionary mapping variable names to the computed values.
public init(status: Status, variables: [String: Double]) {
self.status = status
self.variables = variables
}
}
// MARK: -
/// Default initializer made public.
public init() {}
// MARK: -
/// Solves given model and returns a result with status and computed variables.
///
/// Converts the model into a PuLP LpProblem, solves the problem using PuLP's default solver, and returns relevant information extracted from the solver.
///
/// - Parameters:
/// - model: Model being solved.
/// - logging: If true log the PuLP solver's messages.
/// - Returns: Optional ``Result``. Nil if the PuLP solver's state cannot be retrieved.
public func solve(_ model: Model, logging: Bool = false) -> Result? {
let pythonModel = model.pythonObject
let solver = PuLP.LpSolverDefault.copy()
solver.msg = logging.pythonObject
solver.solve(pythonModel)
return Result(pythonModel)
}
}
// MARK: - ConvertibleFromPython -
/**
Creating a Result from a LpProblem Python object.
*/
extension Solver.Result: ConvertibleFromPython {
// MARK: -
// Returns a name - value tuple for the Python object representing a resolved PuLP LpVariable.
// Returns nil if given Python object does not reference a LpVariable, or if the name or the value cannot be extracted.
private static func asTuple(object: PythonObject) -> (name: String, value: Double)? {
guard object.isInstance(of: PuLP.LpVariable),
let name = String(object.name),
let value = Double(object.value()) else { return nil }
return (name, value)
}
// MARK: -
/// Creates a result from the Python object representing a resolved PuLP LpProblem.
///
/// Fails if given Python object does not reference a LpProblem, or if the problem status cannot be resolved.
///
/// > Note: Problem variables that cannot be converted into name - value pairs are skipped.
///
/// - Parameter object: Python object referencing a PuLP LpProblem.
public init?(_ object: PythonObject) {
guard object.isInstance(of: PuLP.LpProblem),
let status = Solver.Status(object.status),
let values = Array(object.variables())?.compactMap(Self.asTuple) else { return nil }
self.status = status
self.variables = Dictionary(uniqueKeysWithValues: values)
}
}
// MARK: -
/**
Creating Result.Status from a Python float.
*/
extension Solver.Status: ConvertibleFromPython {
// MARK: -
/// Creates a status from given Python object.
///
/// Fails if the object is not a Python float or does not correspond to a known raw case value.
///
/// - Parameter object: Python object representing a PuLP status value.
public init?(_ object: PythonObject) {
guard let value = Double(object), let status = Self(rawValue: value) else { return nil }
self = status
}
}
| 29.529412 | 157 | 0.619301 |
e940164a7d9286605fdfb3efdb04400b9960a5aa | 72,417 | //
// main.swift
// AdventOfCode2021
//
// Created by Nikolay Valasatau on 1.12.21.
//
import Foundation
struct TaskInput {
var prefix: String = "task"
func readInput(_ num: String) -> String {
let name = "\(prefix)\(num)"
guard let url = Bundle.main.url(forResource: name, withExtension: "txt", subdirectory: "input")
else {
fatalError("Not found: input/\(name).txt")
}
return try! String(contentsOf: url)
}
}
// MARK: - Day 01
extension TaskInput {
func task01() -> [Int] {
readInput("01")
.split(separator: "\n")
.map { Int($0)! }
}
}
func task01_1(_ input: TaskInput) {
let numbers = input.task01()
let count = zip(numbers.dropLast(), numbers.dropFirst()).map { $0 < $1 ? 1 : 0 }.reduce(0, +)
print("T01_1: \(count)")
}
func task01_2(_ input: TaskInput) {
let numbers = input.task01()
let count = zip(numbers.dropLast(3), numbers.dropFirst(3)).map { $0 < $1 ? 1 : 0 }.reduce(0, +)
print("T01_2: \(count)")
}
// MARK: - Day 02
extension TaskInput {
enum Direction: String {
case forward
case up
case down
}
func task02() -> [(Direction, Int)] {
readInput("02")
.split(separator: "\n")
.map { line -> (Direction, Int) in
let pair = line.split(separator: " ")
return (.init(rawValue: String(pair[0]))!, Int(pair[1])!)
}
}
}
func task02_1(_ input: TaskInput) {
let instructions = input.task02()
var (x, y) = (0, 0)
for (direction, dist) in instructions {
switch direction {
case .forward:
x += dist
case .up:
y -= dist
case .down:
y += dist
}
}
print("T02_1: \(x)*\(y) = \(x * y)")
}
func task02_2(_ input: TaskInput) {
let instructions = input.task02()
var (x, y, aim) = (0, 0, 0)
for (direction, dist) in instructions {
switch direction {
case .forward:
x += dist
y += dist * aim
case .up:
aim -= dist
case .down:
aim += dist
}
}
print("T02_2: \(x)*\(y) = \(x * y)")
}
// MARK: - Day 03
extension TaskInput {
func task03() -> [[Bool]] {
readInput("03")
.split(separator: "\n")
.map { line in line.map { $0 == "1" } }
}
}
func task03_1(_ input: TaskInput) {
let lines = input.task03()
var nums = [Int](repeating: 0, count: lines.first!.count)
for line in lines {
for (idx, val) in line.enumerated() {
nums[idx] += val ? 1 : 0
}
}
let domination = lines.count / 2
var gamma = 0
var epsilon = 0
for val in nums {
if val > domination {
gamma = gamma * 2 + 1
epsilon = epsilon * 2
} else {
gamma = gamma * 2
epsilon = epsilon * 2 + 1
}
}
print("T03_1: \(gamma)*\(epsilon)=\(gamma * epsilon)")
}
func task03_2(_ input: TaskInput) {
let lines = input.task03()
func filter(_ values: [[Bool]], idx: Int = 0, flag: Bool) -> [[Bool]] {
let count = values.map({ $0[idx] ? 1 : 0 }).reduce(0, +)
let expected = (values.count % 2 == 0 && count == values.count / 2)
? flag
: flag ? (count > values.count / 2) : (count <= values.count / 2)
// print("\(count)/\(values.count) : \(expected)")
return values.filter { $0[idx] == expected }
}
func calc(_ values: [[Bool]], flag: Bool) -> Int {
var result = values
for idx in 0..<(values.first!.count) {
result = filter(result, idx: idx, flag: flag)
// print("\(result.map { l in l.map { $0 ? "1": "0" }.joined() })")
if result.count == 1 {
var num = 0
for val in result.first! {
num *= 2
if val {
num += 1
}
}
return num
}
}
assertionFailure("Whops!")
return 0
}
let o2 = calc(lines, flag: true)
// print("-")
let co2 = calc(lines, flag: false)
print("T03_2: \(o2) * \(co2) = \(o2 * co2)")
}
// MARK: - Day 04
extension TaskInput {
func task04() -> ([Int], [[[Int]]]) {
let lines = readInput("04").split(separator: "\n")
let nums = lines.first!.split(separator: ",").compactMap { Int($0) }
var boards = [[[Int]]]()
for b_idx in 0..<((lines.count - 1) / 5) {
boards.append(
lines[(1 + b_idx * 5)..<(1 + (b_idx + 1) * 5)]
.map { l in l.split(separator: " ").compactMap { Int($0) } }
)
}
return (nums, boards)
}
}
func task04_1(_ input: TaskInput) {
var (nums, boards) = input.task04()
var (bestIdx, bestSum, bestNum) = (Int.max, 0, 0)
// print("\(boards)")
for b in boards.indices {
var cols = [Int](repeating: 0, count: 5)
var rows = [Int](repeating: 0, count: 5)
for (idx, num) in nums.enumerated() {
if idx > bestIdx { break }
for y in 0..<5 {
for x in 0..<5 {
if boards[b][y][x] == num {
cols[x] += 1
rows[y] += 1
boards[b][y][x] *= -1
}
}
}
if cols.contains(5) || rows.contains(5) {
let sum = boards[b].map { r in r.filter({ $0 > 0 }).reduce(0, +) }.reduce(0, +)
bestIdx = idx
bestNum = num
bestSum = sum
// print("\(b) \(idx) \(num) \(sum)")
}
}
}
print("T04_1: \(bestSum) * \(bestNum) = \(bestNum * bestSum)")
}
func task04_2(_ input: TaskInput) {
var (nums, boards) = input.task04()
var (bestIdx, bestSum, bestNum) = (0, 0, 0)
// print("\(boards)")
for b in boards.indices {
var cols = [Int](repeating: 0, count: 5)
var rows = [Int](repeating: 0, count: 5)
for (idx, num) in nums.enumerated() {
for y in 0..<5 {
for x in 0..<5 {
if boards[b][y][x] == num {
cols[x] += 1
rows[y] += 1
boards[b][y][x] *= -1
}
}
}
if cols.contains(5) || rows.contains(5) {
// print("\(b) \(idx) \(num)")
if idx < bestIdx { break }
let sum = boards[b].map { r in r.filter({ $0 > 0 }).reduce(0, +) }.reduce(0, +)
bestIdx = idx
bestNum = num
bestSum = sum
break
// print("\(b) \(idx) \(num) \(sum)")
}
}
}
print("T04_2: \(bestSum) * \(bestNum) = \(bestNum * bestSum)")
}
// MARK: - Day 05
extension TaskInput {
struct Point: Hashable {
var x: Int
var y: Int
}
func task05() -> [(Point, Point)] {
readInput("05")
.split(separator: "\n")
.map { l -> (Point, Point) in
let pair = l.split(separator: ">")
let aa = pair[0].dropLast(2).split(separator: ",").map { Int($0)! }
let bb = pair[1].dropFirst().split(separator: ",").map { Int($0)! }
return (.init(x: aa[0], y: aa[1]), .init(x: bb[0], y: bb[1]))
}
}
}
func task05_1(_ input: TaskInput) {
let lines = input.task05()
let size = 1000
var field = [[Int]](repeating: [Int](repeating: 0, count: size), count: size)
for (a, b) in lines {
if a.y == b.y {
for x in min(a.x, b.x)...max(a.x, b.x) {
field[a.y][x] += 1
}
} else if a.x == b.x {
for y in min(a.y, b.y)...max(a.y, b.y) {
field[y][a.x] += 1
}
}
}
let count = field.map { l in l.map { $0 >= 2 ? 1 : 0 }.reduce(0, +) }.reduce(0, +)
// for y in 0..<10 {
// print(field[y][..<10].map { "\($0)" }.joined())
// }
print("T05_1: \(count)")
}
func task05_2(_ input: TaskInput) {
let lines = input.task05()
let size = 1000
var field = [[Int]](repeating: [Int](repeating: 0, count: size), count: size)
for (a, b) in lines {
if a.y == b.y {
for x in min(a.x, b.x)...max(a.x, b.x) {
field[a.y][x] += 1
}
} else if a.x == b.x {
for y in min(a.y, b.y)...max(a.y, b.y) {
field[y][a.x] += 1
}
} else if abs(a.x - b.x) == abs(a.y - b.y) {
let dx = (b.x - a.x)/abs(b.x - a.x)
let dy = (b.y - a.y)/abs(b.y - a.y)
for idx in 0...abs(b.x - a.x) {
field[a.y + dy * idx][a.x + dx * idx] += 1
}
}
}
let count = field.map { l in l.map { $0 >= 2 ? 1 : 0 }.reduce(0, +) }.reduce(0, +)
// for y in 0..<10 {
// print(field[y][..<10].map { $0 > 0 ? "\($0)" : "." }.joined())
// }
print("T05_2: \(count)")
}
// MARK: - Day 06
extension TaskInput {
func task06() -> [Int] {
readInput("06")
.split(separator: "\n")
.first!
.split(separator: ",")
.map { Int($0)! }
}
}
func task06_1(_ input: TaskInput) {
var fishes = input.task06()
for _ in 0..<80 {
let count = fishes.count
for idx in 0..<count {
fishes[idx] -= 1
if fishes[idx] < 0 {
fishes[idx] = 6
fishes.append(8)
}
}
}
print("T06_1: \(fishes.count)")
}
func task06_2(_ input: TaskInput) {
let fishes = input.task06()
let days = 256
var cache = [[Int]](repeating: [Int](repeating: -1, count: 10), count: days + 1)
func count(fish: Int, days: Int) -> Int {
if cache[days][fish] != -1 { return cache[days][fish] }
var total = 1
var daysLeft = days - fish
while daysLeft > 0 {
total += count(fish: 9, days: daysLeft)
daysLeft -= 7
}
cache[days][fish] = total
return total
}
let count = fishes.map { count(fish: $0, days: days) }.reduce(0, +)
print("T06_2: \(count)")
}
// MARK: - Day 07
extension TaskInput {
func task07() -> [Int] {
readInput("07")
.split(separator: "\n")
.first!
.split(separator: ",")
.map { Int($0)! }
}
}
func task07_1(_ input: TaskInput) {
let crabs = input.task07()
// let mean = crabs.reduce(0, +) / crabs.count
var minFuel = Int.max
for pos in crabs.min()!...crabs.max()! { //(mean-1)...(mean+1) {
minFuel = min(minFuel, crabs.map{ abs($0 - pos) }.reduce(0, +))
}
print("T07_1: \(minFuel)")
}
func task07_2(_ input: TaskInput) {
let crabs = input.task07()
var cache = [Int](repeating: 0, count: crabs.max()! - crabs.min()! + 1)
for idx in 1..<cache.count {
cache[idx] = cache[idx - 1] + idx
}
var minFuel = Int.max
for pos in crabs.min()!...crabs.max()! { //(mean-1)...(mean+1) {
minFuel = min(minFuel, crabs.map{ cache[abs($0 - pos)] }.reduce(0, +))
}
print("T07_2: \(minFuel)")
}
// MARK: - Day 08
let asciA = "a".first!.asciiValue!
extension TaskInput {
private func toSignals<T: StringProtocol>(_ str: T) -> [Set<Int>] {
str
.split(separator: " ")
.map { v in Set(v.map { Int($0.asciiValue! - asciA) }) }
}
func task08() -> [(Set<Set<Int>>, [Set<Int>])] {
readInput("08")
.split(separator: "\n")
.map { line -> (Set<Set<Int>>, [Set<Int>]) in
let pair = line.split(separator: "|")
let signals = Set(toSignals(pair[0]))
let digits = toSignals(pair[1])
return (signals, digits)
}
}
}
func task08_1(_ input: TaskInput) {
let lines = input.task08()
let count = lines.map(\.1).flatMap { $0 }.filter { [2,3,4,7].contains($0.count) }.count
print("T08_1: \(count)")
}
func task08_2(_ input: TaskInput) {
let lines = input.task08()
let digitMapping = [
0: "abcefg",
1: "cf",
2: "acdeg",
3: "acdfg",
4: "bcdf",
5: "abdfg",
6: "abdefg",
7: "acf",
8: "abcdefg",
9: "abcdfg",
].mapValues { v in v.map { Int($0.asciiValue! - asciA) } }
let allChars = Set<Int>(digitMapping.flatMap({ $0.value }))
func bf(signals: Set<Set<Int>>, map: inout [Int], leftChars: inout Set<Int>) -> [Set<Int>: Int]? {
guard map.count == 7 else {
for ch in leftChars.map({$0}) {
map.append(ch)
leftChars.remove(ch)
if let result = bf(signals: signals, map: &map, leftChars: &leftChars) {
return result
}
leftChars.insert(ch)
map.removeLast()
}
return nil
}
let mapping = digitMapping.mapValues { v in Set(v.map { map[$0] }) }
if Set(mapping.values) == signals {
return Dictionary(uniqueKeysWithValues: mapping.map { ($1, $0) })
} else {
return nil
}
}
let sum = lines.map { (signals, digits) in
var map = [Int]()
var leftChars = Set(allChars)
let mapping = bf(signals: signals, map: &map, leftChars: &leftChars)
let val = digits.map { mapping![$0]! }.reduce(0, { $0 * 10 + $1 })
return val
}.reduce(0, +)
print("T08_2: \(sum)")
}
// MARK: - Day 09
extension TaskInput {
func task09() -> [[Int]] {
readInput("09")
.split(separator: "\n")
.map { l in l.map { Int(String($0))! } }
}
}
public struct DSU {
private var parent: [Int] = []
private var sz: [Int] = []
public init(length: Int) {
let arange = (0..<length).map { $0 }
parent = arange
sz = arange
}
mutating public func findParent(of u: Int) -> Int {
var u = u
while parent[u] != u {
(u, parent[u]) = (parent[u], parent[parent[u]])
}
return u
}
mutating public func unionSets(_ u: Int, _ v: Int) {
var u = findParent(of: u)
var v = findParent(of: v)
guard u != v else { return }
if (sz[u] < sz[v]) {
(u, v) = (v, u)
}
parent[v] = u
sz[u] += sz[v]
}
}
func task09_1(_ input: TaskInput) {
let map = input.task09()
let (h, w) = (map.count, map.first!.count)
var total = 0
for y in 0..<h {
for x in 0..<w {
var isLowest = true
for (dy, dx) in [(0, 1), (0, -1), (1, 0), (-1, 0)] {
let (ny, nx) = (y + dy, x + dx)
guard 0 <= ny && ny < h && 0 <= nx && nx < w else { continue }
if map[ny][nx] <= map[y][x] {
isLowest = false
break
}
}
if isLowest {
total += (map[y][x] + 1)
}
}
}
print("T09_1: \(total)")
}
func task09_2(_ input: TaskInput) {
let map = input.task09()
let (h, w) = (map.count, map.first!.count)
var dsu = DSU(length: h * w)
for y in 0..<h {
for x in 0..<w {
guard map[y][x] != 9 else { continue }
for (dy, dx) in [(0, -1), (-1, 0)] {
let (ny, nx) = (y + dy, x + dx)
guard 0 <= ny && ny < h && 0 <= nx && nx < w else { continue }
guard map[ny][nx] != 9 else { continue }
dsu.unionSets(y * w + x, ny * w + nx)
}
}
}
var sizes: [Int: Int] = [:]
for y in 0..<h {
// var line = [Int]()
for x in 0..<w {
let p = dsu.findParent(of: y * w + x)
// line.append(p)
guard map[y][x] != 9 else { continue }
sizes[p, default: 0] += 1
}
// print(line.map { String(format: "%02d", $0) }.joined(separator: " "))
}
let greaterSizes = sizes.values.sorted().reversed()[0..<3]
let total = greaterSizes.reduce(1, *)
print("T09_2: \(greaterSizes) -> \(total)")
}
// MARK: - Day 10
extension TaskInput {
func task10() -> [[Character]] {
readInput("10")
.split(separator: "\n")
.map([Character].init)
}
}
enum T10 {
static let closers: [Character: Character] = [
"{": "}",
"[": "]",
"(": ")",
"<": ">",
]
static let score: [Character: Int] = [
")": 3,
"]": 57,
"}": 1197,
">": 25137,
]
static let cScore: [Character: Int] = [
")": 1,
"]": 2,
"}": 3,
">": 4,
]
}
func task10_1(_ input: TaskInput) {
let lines = input.task10()
var total = 0
for line in lines {
var stack = [Character]()
var done = false
for ch in line {
switch ch {
case "{", "[", "(", "<":
stack.append(ch)
default:
if stack.isEmpty || T10.closers[stack.removeLast()]! != ch {
total += T10.score[ch]!
done = true
break
}
}
if done { break }
}
}
print("T10_1: \(total)")
}
func task10_2(_ input: TaskInput) {
let lines = input.task10()
var totals = [Int]()
for line in lines {
var stack = [Character]()
var done = false
for ch in line {
switch ch {
case "{", "[", "(", "<":
stack.append(ch)
default:
if stack.isEmpty || T10.closers[stack.removeLast()]! != ch {
done = true
break
}
}
if done { break }
}
if done { continue }
totals.append(
stack.reversed().map { T10.cScore[T10.closers[$0]!]! }.reduce(0, { $0 * 5 + $1 })
)
}
totals.sort()
let mid = totals[totals.count / 2]
print("T10_2: \(mid)")
}
// MARK: - Day 11
extension TaskInput {
func task11() -> [[Int]] {
readInput("11")
.split(separator: "\n")
.map { l in l.map { Int(String($0))! } }
}
}
func task11_1(_ input: TaskInput) {
var map = input.task11()
let (h, w) = (map.count, map.first!.count)
var total = 0
let steps = 100
for _ in 0..<steps {
var flashes = [(Int, Int)]()
for y in 0..<h {
for x in 0..<w {
map[y][x] += 1
guard map[y][x] == 10 else { continue }
flashes.append((x, y))
}
}
while flashes.isEmpty == false {
let (x, y) = flashes.removeLast()
total += 1
for dy in -1...1 {
for dx in -1...1 {
let (nx, ny) = (x + dx, y + dy)
guard 0 <= nx && nx < w && 0 <= ny && ny < h && (dx != 0 || dy != 0) else { continue }
map[ny][nx] += 1
guard map[ny][nx] == 10 else { continue }
flashes.append((nx, ny))
}
}
}
for y in 0..<h {
for x in 0..<w {
guard map[y][x] >= 10 else { continue }
map[y][x] = 0
}
}
}
print("T11_1: \(total)")
}
func task11_2(_ input: TaskInput) {
var map = input.task11()
let (h, w) = (map.count, map.first!.count)
var step = 0
while true {
step += 1
var flashes = [(Int, Int)]()
for y in 0..<h {
for x in 0..<w {
map[y][x] += 1
guard map[y][x] == 10 else { continue }
flashes.append((x, y))
}
}
while flashes.isEmpty == false {
let (x, y) = flashes.removeLast()
for dy in -1...1 {
for dx in -1...1 {
let (nx, ny) = (x + dx, y + dy)
guard 0 <= nx && nx < w && 0 <= ny && ny < h && (dx != 0 || dy != 0) else { continue }
map[ny][nx] += 1
guard map[ny][nx] == 10 else { continue }
flashes.append((nx, ny))
}
}
}
var isFinal = true
for y in 0..<h {
for x in 0..<w {
guard map[y][x] >= 10 else {
isFinal = false
continue
}
map[y][x] = 0
}
}
if isFinal { break }
}
print("T11_2: \(step)")
}
// MARK: - Day 12
extension TaskInput {
func task12() -> [(String, String)] {
readInput("12")
.split(separator: "\n")
.map { (String($0.split(separator: "-")[0]), String($0.split(separator: "-")[1])) }
}
}
func task12_1(_ input: TaskInput) {
let pairs = input.task12()
let nbs = Dictionary(grouping: pairs + pairs.map { ($0.1, $0.0) }, by: { $0.0 }).mapValues { $0.map(\.1) }
var paths = Set<[String]>()
var path = [String]()
var visited = Dictionary(uniqueKeysWithValues: nbs.keys.map { ($0, 0) })
func dfs(node: String) {
guard let nnbs = nbs[node], (node != node.lowercased() || visited[node]! == 0) else { return }
visited[node, default: 0] += 1
for n in nnbs {
guard n != "start" else { continue }
guard n != "end" else {
paths.insert(path)
continue
}
path.append(n)
dfs(node: n)
path.removeLast()
}
visited[node, default: 0] -= 1
}
dfs(node: "start")
// print(paths.map{ $0.joined(separator: ",")}.sorted().joined(separator: "\n"))
print("T12_1: \(paths.count)")
}
func task12_2(_ input: TaskInput) {
let pairs = input.task12()
let nbs = Dictionary(grouping: pairs + pairs.map { ($0.1, $0.0) }, by: { $0.0 }).mapValues { $0.map(\.1) }
var paths = Set<[String]>()
var path = [String]()
var visited = Dictionary(uniqueKeysWithValues: nbs.keys.map { ($0, 0) })
var extraNode: String?
func dfs(node: String) {
guard let nnbs = nbs[node],
(node != node.lowercased() || visited[node]! == 0 || (node == extraNode && visited[node]! == 1))
else { return }
visited[node, default: 0] += 1
for n in nnbs {
guard n != "start" else { continue }
guard n != "end" else {
paths.insert(path)
continue
}
path.append(n)
dfs(node: n)
path.removeLast()
}
if node == node.lowercased() && extraNode == nil {
extraNode = node
for n in nnbs {
guard n != "start" else { continue }
guard n != "end" else {
paths.insert(path)
continue
}
path.append(n)
dfs(node: n)
path.removeLast()
}
extraNode = nil
}
visited[node, default: 0] -= 1
}
dfs(node: "start")
// print(paths.map{ $0.joined(separator: ",")}.sorted().joined(separator: "\n"))
print("T12_1: \(paths.count)")
}
// MARK: - Day 13
extension TaskInput {
func task13() -> ([Point], [Point]) {
let lines = readInput("13").split(separator: "\n")
var idx = 0
var coords = [Point]()
while lines[idx].starts(with: "fold") == false {
let pair = lines[idx].split(separator: ",")
coords.append(.init(x: Int(pair[0])!, y: Int(pair[1])!))
idx += 1
}
var folds = [Point]()
while idx < lines.count {
let pair = lines[idx].split(separator: " ").last!.split(separator: "=")
if pair[0] == "x" {
folds.append(.init(x: Int(pair[1])!, y:0))
} else {
folds.append(.init(x: 0, y: Int(pair[1])!))
}
idx += 1
}
return (coords, folds)
}
}
func task13_1(_ input: TaskInput) {
let (_coords, folds) = input.task13()
var coords = Set(_coords)
let fold = folds.first!
if fold.x == 0 {
for c in Array(coords) {
if c.y > fold.y {
coords.remove(c)
coords.insert(.init(x: c.x, y: c.y - (c.y - fold.y) * 2))
}
}
} else {
for c in Array(coords) {
if c.x > fold.x {
coords.remove(c)
coords.insert(.init(x: c.x - (c.x - fold.x) * 2, y: c.y))
}
}
}
print("T13_1: \(coords.count)")
}
func task13_2(_ input: TaskInput) {
let (_coords, folds) = input.task13()
var coords = Set(_coords)
for fold in folds {
if fold.x == 0 {
for c in Array(coords) {
if c.y > fold.y {
coords.remove(c)
coords.insert(.init(x: c.x, y: c.y - (c.y - fold.y) * 2))
}
}
} else {
for c in Array(coords) {
if c.x > fold.x {
coords.remove(c)
coords.insert(.init(x: c.x - (c.x - fold.x) * 2, y: c.y))
}
}
}
}
let (w, h) = (coords.map(\.x).max()! + 1, coords.map(\.y).max()! + 1)
var map = [[Bool]](repeating: [Bool](repeating: false, count: w), count: h)
for c in coords {
map[c.y][c.x] = true
}
let snap = map.map { l in l.map { $0 ? "@" : " " }.joined() }.joined(separator: "\n")
print("T13_2:\n\(snap)")
}
// MARK: - Day 14
extension TaskInput {
func task14() -> ([Character], [String: Character]) {
let lines = readInput("14").split(separator: "\n")
return (
Array(lines.first!),
Dictionary(uniqueKeysWithValues: lines.dropFirst().map { line in
let ar = Array(line)
return (String([ar[0], ar[1]]), ar[6])
})
)
}
}
enum T14 {
static func task14(_ input: TaskInput, sub: Int, steps: Int) {
let (line, moves) = input.task14()
var counts = [String: Int]()
for (a, b) in zip(line.dropLast(), line.dropFirst()) {
counts[String([a, b]), default: 0] += 1
}
var lCounts = Dictionary(grouping: line, by: { $0 }).mapValues { $0.count }
for _ in 0..<steps {
var nextCounts = counts
for (key, count) in counts {
if let next = moves[key] {
nextCounts[key, default: 0] -= count
nextCounts[String([key.first!, next]), default: 0] += count
nextCounts[String([next, key.last!]), default: 0] += count
lCounts[next, default: 0] += count
}
}
counts = nextCounts
// print("S \(idx): \(counts.map { "\($0.key)->\($0.value)" }.joined(separator: ", "))")
}
let mostCommon = lCounts.max(by: { $0.value < $1.value })!
let leastCommon = lCounts.min(by: { $0.value < $1.value })!
print("T14_\(sub): \(mostCommon.key) -> \(mostCommon.value), \(leastCommon.key) -> \(leastCommon.value), \(mostCommon.value - leastCommon.value)")
}
}
func task14_1(_ input: TaskInput) {
T14.task14(input, sub: 1, steps: 10)
}
func task14_2(_ input: TaskInput) {
T14.task14(input, sub: 1, steps: 40)
}
// MARK: - Day 15
extension TaskInput {
func task15() -> [[Int]] {
readInput("15").split(separator: "\n").map { l in l.map { Int(String($0))! }}
}
}
enum T15 {
static func task15(map: [[Int]], sub: Int) {
let (w, h) = (map.count, map.first!.count)
var score = [[Int]](repeating: [Int](repeating: Int.max, count: w), count: h)
score[0][0] = 0
var queue = [(0, 0)]
while queue.isEmpty == false {
let (x, y) = queue.removeFirst()
for (dx, dy) in [(0, 1), (0, -1), (-1, 0), (1, 0)] {
let (nx, ny) = (x + dx, y + dy)
guard 0 <= nx && nx < w && 0 <= ny && ny < h else { continue }
let s = score[y][x] + map[ny][nx]
guard s < score[ny][nx] else { continue }
score[ny][nx] = s
queue.append((nx, ny))
}
}
print("T15_\(sub): \(score.last!.last!)")
}
}
func task15_1(_ input: TaskInput) {
let map = input.task15()
T15.task15(map: map, sub: 1)
}
func task15_2(_ input: TaskInput) {
let tile = input.task15()
let (tw, th) = (tile.count, tile.first!.count)
var map = [[Int]](repeating: [Int](repeating: 0, count: tw * 5), count: th * 5)
let (w, h) = (map.count, map.first!.count)
for y in 0..<h {
for x in 0..<w {
let val = tile[y % th][x % tw] + (y / th) + (x / tw)
map[y][x] = val > 9 ? val - 9 : val
}
}
T15.task15(map: map, sub: 2)
}
// MARK: - Day 16
extension TaskInput {
final class BitsReader {
private static let hexMap: [Character: [Int]] = [
"0": [0,0,0,0],
"1": [0,0,0,1],
"2": [0,0,1,0],
"3": [0,0,1,1],
"4": [0,1,0,0],
"5": [0,1,0,1],
"6": [0,1,1,0],
"7": [0,1,1,1],
"8": [1,0,0,0],
"9": [1,0,0,1],
"A": [1,0,1,0],
"B": [1,0,1,1],
"C": [1,1,0,0],
"D": [1,1,0,1],
"E": [1,1,1,0],
"F": [1,1,1,1],
]
private(set) var idx = 0;
private let hex: [Character]
init<T: Collection>(hex: T) where T.Element == Character {
self.hex = .init(hex)
}
func nextInt(_ k: Int) -> Int {
var result = 0
for _ in 0..<k {
result = (result << 1) | Self.hexMap[hex[idx / 4]]![idx % 4]
idx += 1
}
return result;
}
}
func task16() -> [BitsReader] {
readInput("16").split(separator: "\n").map(BitsReader.init(hex:))
}
}
enum T16 {
struct Packet {
enum Operator: Int {
case sum = 0
case product = 1
case minimum = 2
case maximum = 3
case gt = 5
case lt = 6
case eq = 7
}
enum Payload {
case literal(Int)
case `operator`(Operator, [Packet])
}
var version: Int
var payload: Payload
}
static func parsePacket(_ reader: TaskInput.BitsReader) -> Packet {
let version = reader.nextInt(3)
let type = reader.nextInt(3)
let payload: Packet.Payload
switch type {
case 4:
var literal = 0
var isLast = false
while isLast == false {
isLast = reader.nextInt(1) == 0
let batch = reader.nextInt(4)
literal = (literal << 4) | batch
}
payload = .literal(literal)
default:
let lengthType = reader.nextInt(1)
var subpackets = [Packet]()
if lengthType == 0 {
let length = reader.nextInt(15)
let start = reader.idx
while reader.idx < start + length {
subpackets.append(parsePacket(reader))
}
} else {
let count = reader.nextInt(11)
for _ in 0..<count {
subpackets.append(parsePacket(reader))
}
}
payload = .operator(.init(rawValue: type)!, subpackets)
}
return .init(version: version, payload: payload)
}
}
func task16_1(_ input: TaskInput) {
let readers = input.task16()
for (idx, reader) in readers.enumerated() {
let packet = T16.parsePacket(reader)
func sumVersions(_ packet: T16.Packet) -> Int {
var result = packet.version
switch packet.payload {
case .literal:
break
case .operator(_, let subs):
result += subs.map(sumVersions).reduce(0, +)
}
return result
}
print("T16_1_\(idx): \(sumVersions(packet))")
}
}
func task16_2(_ input: TaskInput) {
let readers = input.task16()
for (idx, reader) in readers.enumerated() {
let packet = T16.parsePacket(reader)
func calc(_ packet: T16.Packet) -> Int {
switch packet.payload {
case .literal(let val):
return val
case .operator(let type, let subs):
let subVals = subs.map(calc)
switch type {
case .sum:
return subVals.reduce(0, +)
case .product:
return subVals.reduce(0, *)
case .minimum:
return subVals.min()!
case .maximum:
return subVals.max()!
case .gt:
return subVals[0] > subVals[1] ? 1 : 0
case .lt:
return subVals[0] < subVals[1] ? 1 : 0
case .eq:
return subVals[0] == subVals[1] ? 1 : 0
}
}
}
print("T16_2_\(idx): \(calc(packet))")
}
}
// MARK: - Day 17
extension TaskInput {
func task17() -> (x: ClosedRange<Int>, y: ClosedRange<Int>) {
let line = readInput("17").split(separator: "\n").first!
let coords = line
.split(separator: ":")[1]
.split(separator: ",")
.map { $0.dropFirst(3) }
.flatMap { $0.split(separator: ".") }
.map { Int($0)! }
return (x: coords[0]...coords[1], y: coords[2]...coords[3])
}
}
func task17_1(_ input: TaskInput) {
let ranges = input.task17()
var score = Int.min
for _vx in 0...ranges.x.upperBound {
for _vy in -ranges.y.upperBound...(4 * ranges.y.count + 1) {
var (x, y) = (0, 0)
var (vx, vy) = (_vx, _vy)
var maxY = Int.min
while x <= ranges.x.upperBound && y >= ranges.y.lowerBound {
maxY = max(maxY, y)
if ranges.x.contains(x) && ranges.y.contains(y) {
score = max(score, maxY)
// print("Match: \(_vx) \(_vy) -> \(score)")
break
}
if maxY < score && vy < 0 {
break
}
x += vx
y += vy
if vx != 0 {
vx -= vx / abs(vx)
}
vy -= 1
}
}
}
print("T17_1: \(score)")
}
func task17_2(_ input: TaskInput) {
let ranges = input.task17()
var count = 0
for _vx in 0...ranges.x.upperBound {
for _vy in (2 * ranges.y.upperBound)...(10 * ranges.y.count + 1) {
var (x, y) = (0, 0)
var (vx, vy) = (_vx, _vy)
var maxY = Int.min
while x <= ranges.x.upperBound && y >= ranges.y.lowerBound {
maxY = max(maxY, y)
if ranges.x.contains(x) && ranges.y.contains(y) {
count += 1
break
}
x += vx
y += vy
if vx != 0 {
vx -= vx / abs(vx)
}
vy -= 1
}
}
}
print("T17_2: \(count)")
}
// MARK: - Day 18
extension TaskInput {
func task18() -> [T18.TreeNode] {
readInput("18").split(separator: "\n").map(T18.TreeNode.parse)
}
}
enum T18 {
final class TreeNode {
var val: Int?
var left: TreeNode?
var right: TreeNode?
init(val: Int?, left: TreeNode?, right: TreeNode?) {
self.val = val
self.left = left
self.right = right
}
static func parse<T: StringProtocol>(_ str: T) -> TreeNode {
let result = parse(str, idx: str.startIndex).0
result.reduce()
return result
}
private static func parse<T: StringProtocol>(_ str: T, idx: T.Index) -> (TreeNode, T.Index) {
var val: Int?
var left: TreeNode?
var right: TreeNode?
var nextIdx = idx
if str[idx] == "[" {
nextIdx = str.index(after: nextIdx)
(left, nextIdx) = parse(str, idx: nextIdx)
nextIdx = str.index(after: nextIdx)
(right, nextIdx) = parse(str, idx: nextIdx)
nextIdx = str.index(after: nextIdx)
} else {
while str[nextIdx].isNumber {
nextIdx = str.index(after: nextIdx)
}
val = Int(str[idx..<nextIdx])!
}
return (.init(val: val, left: left, right: right), nextIdx)
}
private func reduce() {
var shouldContinue = true
while shouldContinue {
shouldContinue = explodeIfNeeded() != nil || splitIfNeeded()
}
}
private func explodeIfNeeded(_ level: Int = 0) -> (Int?, Int?)? {
if val != nil { return nil }
if level == 4 {
let result = (left!.val!, right!.val!)
val = 0
left = nil
right = nil
return result
}
if let (l, r) = left!.explodeIfNeeded(level + 1) {
if let r = r {
right!.addLeft(r)
}
return (l, nil)
} else if let (l, r) = right!.explodeIfNeeded(level + 1) {
if let l = l {
left!.addRight(l)
}
return (nil, r)
} else {
return nil
}
}
private func addLeft(_ val: Int) {
if self.val != nil {
self.val! += val
} else {
left!.addLeft(val)
}
}
private func addRight(_ val: Int) {
if self.val != nil {
self.val! += val
} else {
right!.addRight(val)
}
}
private func splitIfNeeded() -> Bool {
if let val = val {
if val < 10 { return false }
left = .init(val: val / 2, left: nil, right: nil)
right = .init(val: val - left!.val!, left: nil, right: nil)
self.val = nil
return true
}
return left!.splitIfNeeded() || right!.splitIfNeeded()
}
func magnitude() -> Int {
if let val = val { return val }
return 3 * left!.magnitude() + 2 * right!.magnitude()
}
func copy() -> TreeNode {
return TreeNode(val: val, left: left?.copy(), right: right?.copy())
}
static func +(_ lhs: TreeNode, _ rhs: TreeNode) -> TreeNode {
let result = TreeNode(val: nil, left: lhs.copy(), right: rhs.copy())
result.reduce()
return result
}
}
}
func task18_1(_ input: TaskInput) {
let nums = input.task18()
let result = nums.dropFirst().reduce(nums.first!, +)
print("T18_1: \(result.magnitude())")
}
func task18_2(_ input: TaskInput) {
let nums = input.task18()
var maxMagnitude = Int.min
for (i1, n1) in nums.enumerated() {
for (i2, n2) in nums.enumerated() {
if i1 == i2 { continue }
maxMagnitude = max(maxMagnitude, (n1 + n2).magnitude())
}
}
print("T18_2: \(maxMagnitude)")
}
// MARK: - Day 19
extension TaskInput {
struct Point3D: Hashable {
var x: Int
var y: Int
var z: Int
var isScanner: Bool = false
}
func task19() -> [Set<Point3D>] {
let lines = readInput("19").split(separator: "\n")
var result = [Set<Point3D>]()
var scaner = Set<Point3D>()
for line in lines {
if line.starts(with: "---") {
result.append(scaner)
scaner.removeAll()
scaner.insert(Point3D(x: 0, y: 0, z: 0, isScanner: true))
} else {
let ints = line.split(separator: ",").map { Int($0)! }
scaner.insert(.init(x: ints[0], y: ints[1], z: ints[2]))
}
}
result.append(scaner)
return Array(result.dropFirst())
}
}
extension Set where Element == TaskInput.Point3D {
private static let maps: [(Int, Int, Int) -> (Int, Int, Int)] = [
{ (x, y, z) in (x, y, z) },
{ (x, y, z) in (x, z, -y) },
{ (x, y, z) in (x, -y, -z) },
{ (x, y, z) in (x, -z, y) },
{ (x, y, z) in (-x, y, z) },
{ (x, y, z) in (-x, z, -y) },
{ (x, y, z) in (-x, -y, -z) },
{ (x, y, z) in (-x, -z, y) },
{ (x, y, z) in (-z, y, x) },
{ (x, y, z) in (-x, y, -z) },
{ (x, y, z) in (z, y, -x) },
{ (x, y, z) in (x, -y, z) },
{ (x, y, z) in (-z, -y, x) },
{ (x, y, z) in (-x, -y, -z) },
{ (x, y, z) in (z, -y, -x) },
{ (x, y, z) in (-y, x, z) },
{ (x, y, z) in (-x, -y, z) },
{ (x, y, z) in (-y, x, z) },
{ (x, y, z) in (x, y, -z) },
{ (x, y, z) in (-y, x, -z) },
{ (x, y, z) in (-x, -y, -z) },
{ (x, y, z) in (-y, x, -z) },
]
func rotations() -> [Set<TaskInput.Point3D>] {
Self.maps.map { m -> Set<TaskInput.Point3D> in
Set(self.map { p -> TaskInput.Point3D in
let (x, y, z) = m(p.x, p.y, p.z)
return TaskInput.Point3D(x: x, y: y, z: z, isScanner: p.isScanner)
})
}
}
func transpose(_ point: TaskInput.Point3D) -> Set<TaskInput.Point3D> {
Set(self.map { p in .init(x: p.x - point.x, y: p.y - point.y, z: p.z - point.z, isScanner: p.isScanner) })
}
func allVariants() -> [Set<TaskInput.Point3D>] {
rotations().flatMap { r in r.map { r.transpose($0) } }
}
}
enum T19 {
static func match(_ scanners: [Set<TaskInput.Point3D>]) -> (Int, Int, Set<TaskInput.Point3D>) {
let allVariants = scanners.enumerated()
.flatMap { (idx, s) in s.allVariants().map { (idx, $0) } }
.shuffled()
for (idx1, s1) in allVariants {
for (idx2, s2) in allVariants {
guard idx2 > idx1 else { continue }
if s1.intersection(s2).count >= 12 {
return (idx1, idx2, s1.union(s2))
}
}
}
fatalError()
}
}
func task19_1(_ input: TaskInput) {
var scanners = input.task19()
while scanners.count != 1 {
let (i1, i2, ns) = T19.match(scanners)
scanners.remove(at: i1)
scanners[i2 - 1] = ns
}
print("T19_1: \(scanners.first!.filter { $0.isScanner == false }.count)")
let sPoints = scanners.first!.filter { $0.isScanner }
var maxDist = Int.min
for (idx, p1) in sPoints.enumerated() {
for p2 in sPoints.dropFirst(idx + 1) {
maxDist = max(maxDist, abs(p1.x - p2.x) + abs(p1.y - p2.y) + abs(p1.z - p2.z))
}
}
print("T19_2: \(maxDist)")
}
func task19_2(_ input: TaskInput) {
// In _1
}
// MARK: - Day 20
extension TaskInput {
func task20() -> ([Bool], [[Bool]]) {
let lines = readInput("20").split(separator: "\n")
let alg = lines.first!.map { $0 == "#" }
let img = lines.dropFirst().map { l in l.map { $0 == "#" } }
return (alg, img)
}
}
enum T20 {
static func processStep(_ img: [[Bool]], alg: [Bool], step: Int) -> [[Bool]] {
let (h, w) = (img.count, img.first!.count)
var result = [[Bool]](repeating: [Bool](repeating: false, count: w + 2), count: h + 2)
for y in 0..<(h + 2) {
for x in 0..<(w + 2) {
var val = 0
for dy in -1...1 {
for dx in -1...1 {
let (px, py) = (x + dx - 1, y + dy - 1)
val <<= 1
if 0 <= px && px < w && 0 <= py && py < h {
val += img[py][px] ? 1 : 0
} else {
val += (step % 2 == 0) ? 0 : (alg[0] ? 1 : 0)
}
}
}
result[y][x] = alg[val]
}
}
return result
}
}
func task20_1(_ input: TaskInput) {
let (alg, img) = input.task20()
var result = img
for idx in 0..<2 {
result = T20.processStep(result, alg: alg, step: idx)
}
// print(result.map { l in l.map { $0 ? "#" : "." }.joined()}.joined(separator: "\n"))
let count = result.flatMap { l in l.map { $0 ? 1 : 0 } }.reduce(0, +)
print("T20_1: \(count)")
}
func task20_2(_ input: TaskInput) {
let (alg, img) = input.task20()
var result = img
for idx in 0..<50 {
result = T20.processStep(result, alg: alg, step: idx)
}
let count = result.flatMap { l in l.map { $0 ? 1 : 0 } }.reduce(0, +)
print("T20_2: \(count)")
}
// MARK: - Day 21
extension TaskInput {
func task21() -> (Int, Int) {
let p = readInput("21").split(separator: "\n").map { l in Int(l.split(separator: " ").last!)! }
return (p[0], p[1])
}
}
enum T21 {
}
func task21_1(_ input: TaskInput) {
var (a, b) = input.task21()
(a, b) = (a - 1, b - 1)
var roll = 1
var (sA, sB) = (0, 0)
var count = 0
while max(sA, sB) < 1000 {
for _ in 0..<3 {
a = (a + roll) % 10
if roll == 100 { roll = 1 } else { roll += 1 }
count += 1
}
sA += (a + 1)
(a, b) = (b, a)
(sA, sB) = (sB, sA)
}
let other = min(sA, sB)
print("T21_1: \(count), \(other) -> \(count * other)")
}
func task21_2(_ input: TaskInput) {
let (a, b) = input.task21()
struct State: Hashable {
var a: Int
var b: Int
var sA: Int = 0
var sB: Int = 0
var turnA: Bool = true
}
let winScore = 21
var cache = [State: (Int, Int)]()
func solve(_ state: State) -> (Int, Int) {
if state.sA >= winScore { return (1, 0) }
if state.sB >= winScore { return (0, 1) }
if let result = cache[state] { return result }
var (wA, wB) = (0, 0)
for r1 in 1...3 {
for r2 in 1...3 {
for r3 in 1...3 {
var state = state
if state.turnA {
state.a = (state.a + r1 + r2 + r3) % 10
state.sA += (state.a + 1)
} else {
state.b = (state.b + r1 + r2 + r3) % 10
state.sB += (state.b + 1)
}
state.turnA.toggle()
let (rA, rB) = solve(state)
wA += rA
wB += rB
}
}
}
cache[state] = (wA, wB)
return (wA, wB)
}
let (wA, wB) = solve(.init(a: a - 1, b: b - 1))
print("T21_2: \(wA), \(wB) -> \(max(wA, wB))")
}
// MARK: - Day 22
extension TaskInput {
func task22() -> [(Bool, T22.RebootStep)] {
readInput("22").split(separator: "\n").map { l in
let p1 = l.split(separator: " ")
let isOn = p1[0] == "on"
let coords = p1[1].split(separator: ",").map { c in c.dropFirst(2).split(separator: ".").map { Int($0)! } }
return (isOn, T22.RebootStep(
x: coords[0][0]...coords[0][1],
y: coords[1][0]...coords[1][1],
z: coords[2][0]...coords[2][1]
))
}
}
}
enum T22 {
struct RebootStep {
var x: ClosedRange<Int>
var y: ClosedRange<Int>
var z: ClosedRange<Int>
}
}
extension ClosedRange where Bound == Int {
func split(_ other: Self) -> [Self] {
if lowerBound > other.upperBound || upperBound < other.lowerBound {
return []
}
if other.lowerBound <= lowerBound && upperBound <= other.upperBound {
return [self]
}
if lowerBound < other.lowerBound && upperBound > other.upperBound {
return [lowerBound...(other.lowerBound - 1), other, (other.upperBound + 1)...upperBound]
}
if other.lowerBound <= lowerBound {
return [lowerBound...other.upperBound, (other.upperBound + 1)...upperBound]
} else {
return [lowerBound...(other.lowerBound - 1), other.lowerBound...upperBound]
}
}
}
extension T22.RebootStep {
func intersects(_ other: T22.RebootStep) -> Bool {
x.overlaps(other.x) && y.overlaps(other.y) && z.overlaps(other.z)
}
func removing(_ other: T22.RebootStep) -> [T22.RebootStep] {
let xInts = x.split(other.x)
let yInts = y.split(other.y)
let zInts = z.split(other.z)
guard xInts.isEmpty == false && yInts.isEmpty == false && zInts.isEmpty == false
else {
return [self]
}
var result = [T22.RebootStep]()
for xInt in xInts {
for yInt in yInts {
for zInt in zInts {
result.append(.init(x: xInt, y: yInt, z: zInt))
}
}
}
return result.filter { $0.intersects(other) == false }
}
var count: Int { x.count * y.count * z.count }
}
extension T22 {
static func processSteps(_ steps: [(Bool, RebootStep)]) -> [RebootStep] {
var onRegions = [RebootStep]()
for (isOn, step) in steps {
var nextOn = [RebootStep]()
for region in onRegions {
nextOn.append(contentsOf: region.removing(step))
}
if isOn {
nextOn.append(step)
}
onRegions = nextOn
}
return onRegions
}
}
func task22_1(_ input: TaskInput) {
let steps = input.task22()
let size = 50
let onRegions = T22.processSteps(steps + [
(false, T22.RebootStep(x: Int.min...(-size - 1), y: Int.min...Int.max, z: Int.min...Int.max)),
(false, T22.RebootStep(x: (size + 1)...Int.max, y: Int.min...Int.max, z: Int.min...Int.max)),
(false, T22.RebootStep(x: Int.min...Int.max, y: Int.min...(-size - 1), z: Int.min...Int.max)),
(false, T22.RebootStep(x: Int.min...Int.max, y: (size + 1)...Int.max, z: Int.min...Int.max)),
(false, T22.RebootStep(x: Int.min...Int.max, y: Int.min...Int.max, z: Int.min...(-size - 1))),
(false, T22.RebootStep(x: Int.min...Int.max, y: Int.min...Int.max, z: (size + 1)...Int.max)),
])
let count = onRegions.map(\.count).reduce(0, +)
print("T22_1: \(count)")
}
func task22_2(_ input: TaskInput) {
let steps = input.task22()
let onRegions = T22.processSteps(steps)
let count = onRegions.map(\.count).reduce(0, +)
print("T22_2: \(count)")
}
// MARK: - Day 23
extension TaskInput {
func task23() -> [TaskInput.Point: Int] {
let lines = readInput("23").split(separator: "\n").dropFirst(2).dropLast()
let aLetter = Int("A".first!.asciiValue!)
return Dictionary(uniqueKeysWithValues: lines.enumerated().flatMap { (y, l) -> [(TaskInput.Point, Int)] in
l.split(separator: "#").filter { $0.count == 1 }.enumerated().map { (x, g) -> (TaskInput.Point, Int) in
(TaskInput.Point(x: 2 + x * 2, y: y + 1), (Int(g.first!.asciiValue!) - aLetter) * 2 + 2)
}
})
}
}
enum T23 {
}
func task23_1(_ input: TaskInput) {
let pods = input.task23()
var cache = [[TaskInput.Point: Int]:Int]()
let mult: [Int: Int] = [2: 1, 4: 10, 6: 100, 8: 1000]
func solve(pods: [TaskInput.Point: Int]) -> Int {
if pods.allSatisfy({ $0.key.x == $0.value }) { return 0 }
if let score = cache[pods] { return score }
var minScore = Int.max
// var viz = [[String]](repeating: [String](repeating: "#", count: 13), count: 5)
// for x in 1...11 {
// viz[1][x] = "."
// }
// for x in [3,5,7,9] {
// viz[2][x] = "."
// viz[3][x] = "."
// }
// for (pos, dest) in pods {
// viz[pos.y + 1][pos.x + 1] = [2: "A", 4: "B", 6: "C", 8: "D"][dest]!
// }
// print(viz.map { $0.joined() }.joined(separator: "\n"))
// print("")
func tryMove(pos: TaskInput.Point, dest: Int, nextPos: TaskInput.Point) {
var nextPods = pods
nextPods[pos] = nil
nextPods[nextPos] = dest
let nextScore = solve(pods: nextPods)
if nextScore != Int.max {
let score = nextScore + mult[dest]! * (abs(pos.x - nextPos.x) + abs(pos.y - nextPos.y))
minScore = min(minScore, score)
}
}
for (pos, dest) in pods {
if pos.x == dest && (pos.y == 2 || pods[.init(x: dest, y: 2)] == dest) { continue }
if pos.y == 0 {
var possible = true
for x in min(pos.x, dest)...max(pos.x, dest) {
if x == pos.x { continue }
if pods[.init(x: x, y: 0)] != nil {
possible = false
break
}
}
if possible {
let p2 = pods[.init(x: dest, y: 2)]
if p2 == nil {
tryMove(pos: pos, dest: dest, nextPos: .init(x: dest, y: 2))
} else if pods[.init(x: dest, y: 1)] == nil && p2 == dest {
tryMove(pos: pos, dest: dest, nextPos: .init(x: dest, y: 1))
}
}
} else if pos.y == 1 || (pos.y == 2 && pods[.init(x: pos.x, y: 1)] == nil) {
for nextX in [0, 1, 3, 5, 7, 9, 10] {
var possible = true
for x in min(pos.x, nextX)...max(pos.x, nextX) {
if x == pos.x { continue }
if pods[.init(x: x, y: 0)] != nil {
possible = false
break
}
}
if possible {
tryMove(pos: pos, dest: dest, nextPos: .init(x: nextX, y: 0))
}
}
}
}
cache[pods] = minScore
return minScore
}
let score = solve(pods: pods)
print("T23_1: \(score)")
}
func task23_2(_ input: TaskInput) {
var pods = input.task23()
for x in [2,4,6,8] {
let dest = pods[.init(x: x, y: 2)]
pods[.init(x: x, y: 2)] = nil
pods[.init(x: x, y: 4)] = dest
}
pods[.init(x: 2, y: 2)] = 8
pods[.init(x: 2, y: 3)] = 8
pods[.init(x: 4, y: 2)] = 6
pods[.init(x: 4, y: 3)] = 4
pods[.init(x: 6, y: 2)] = 4
pods[.init(x: 6, y: 3)] = 2
pods[.init(x: 8, y: 2)] = 2
pods[.init(x: 8, y: 3)] = 6
var cache = [[TaskInput.Point: Int]:Int]()
let mult: [Int: Int] = [2: 1, 4: 10, 6: 100, 8: 1000]
func solve(pods: [TaskInput.Point: Int], depth: Int = 0) -> Int {
if pods.allSatisfy({ $0.key.x == $0.value }) { return 0 }
if let score = cache[pods] { return score }
var minScore = Int.max
cache[pods] = minScore
// var viz = [[String]](repeating: [String](repeating: "#", count: 13), count: 7)
// for x in 1...11 {
// viz[1][x] = "."
// }
// for x in [3,5,7,9] {
// viz[2][x] = "."
// viz[3][x] = "."
// viz[4][x] = "."
// viz[5][x] = "."
// }
// for (pos, dest) in pods {
// viz[pos.y + 1][pos.x + 1] = [2: "A", 4: "B", 6: "C", 8: "D"][dest]!
// }
// print(viz.map { $0.joined() }.joined(separator: "\n"))
// print("")
func tryMove(pos: TaskInput.Point, dest: Int, nextPos: TaskInput.Point) {
var nextPods = pods
nextPods[pos] = nil
nextPods[nextPos] = dest
let nextScore = solve(pods: nextPods, depth: depth + 1)
if nextScore != Int.max {
let score = nextScore + mult[dest]! * (abs(pos.x - nextPos.x) + abs(pos.y - nextPos.y))
minScore = min(minScore, score)
}
}
for (pos, dest) in pods {
if pos.x == dest && (pos.y...4).allSatisfy({ pods[.init(x: dest, y: $0)] == dest }) { continue }
if pos.y == 0 {
var possible = true
for x in min(pos.x, dest)...max(pos.x, dest) {
if x == pos.x { continue }
if pods[.init(x: x, y: 0)] != nil {
possible = false
break
}
}
if possible {
for y in (1...4).reversed() {
let val = pods[.init(x: dest, y: y)]
if val == nil {
tryMove(pos: pos, dest: dest, nextPos: .init(x: dest, y: y))
break
} else if val != dest {
break
}
}
}
} else if pos.y == 1 || (1..<pos.y).allSatisfy({ pods[.init(x: pos.x, y: $0)] == nil }) {
for nextX in [0, 1, 3, 5, 7, 9, 10] {
var possible = true
for x in min(pos.x, nextX)...max(pos.x, nextX) {
if x == pos.x { continue }
if pods[.init(x: x, y: 0)] != nil {
possible = false
break
}
}
if possible {
tryMove(pos: pos, dest: dest, nextPos: .init(x: nextX, y: 0))
}
}
}
}
cache[pods] = minScore
return minScore
}
let score = solve(pods: pods)
print("T23_2: \(score)")
}
// MARK: - Day 24
extension TaskInput {
private static let wCharIdx = "w".first!.asciiValue!
func task24() -> [T24.Op] {
readInput("24").split(separator: "\n").map { l in
let parts = l.split(separator: " ")
var rhs: T24.Lit?
if parts.count == 3 {
if parts[2].first!.isLetter {
rhs = .var(Int(parts[2].first!.asciiValue! - Self.wCharIdx))
} else {
rhs = .num(Int(parts[2])!)
}
}
let lhs = Int(parts[1].first!.asciiValue! - Self.wCharIdx)
switch parts[0] {
case "inp":
return .inp(lhs)
case "add":
return .add(lhs, rhs!)
case "mul":
return .mul(lhs, rhs!)
case "div":
return .div(lhs, rhs!)
case "mod":
return .mod(lhs, rhs!)
case "eql":
return .eql(lhs, rhs!)
default:
fatalError()
}
}
}
}
enum T24 {
typealias Var = Int
enum Lit {
case `var`(Var)
case num(Int)
}
enum Op {
case inp(Var)
case add(Var, Lit)
case mul(Var, Lit)
case div(Var, Lit)
case mod(Var, Lit)
case eql(Var, Lit)
}
}
extension T24.Op {
var isInp: Bool {
if case .inp = self { return true }
return false
}
var lhs: T24.Var {
switch self {
case .inp(let v), .add(let v, _), .mul(let v, _), .div(let v, _), .mod(let v, _), .eql(let v, _):
return v
}
}
var rhs: T24.Lit {
switch self {
case .inp:
return .num(0) // noop
case .add(_, let l), .mul(_, let l), .div(_, let l), .mod(_, let l), .eql(_, let l):
return l
}
}
}
extension T24 {
struct State: Hashable {
var idx: Int
var d1: Int
var d2: Int
var d3: Int
}
static func stringify(ops: [Op]) -> String {
let prefix = ["{ (w: Int, x: inout Int, y: inout Int, z: inout Int) -> Void in"]
let postfix = ["},"]
let letter = ["w", "x", "y", "z"]
var result = [String]()
for op in ops {
let lhs = letter[op.lhs]
let rhs: String
switch op.rhs {
case .num(let val):
rhs = "\(val)"
case .var(let idx):
rhs = letter[idx]
}
switch op {
case .inp:
result.append(contentsOf: postfix + prefix)
case .add:
result.append(" \(lhs) += \(rhs)")
case .mul:
result.append(" \(lhs) *= \(rhs)")
case .div:
result.append(" \(lhs) /= \(rhs)")
case .mod:
result.append(" \(lhs) %= \(rhs)")
case .eql:
result.append(" \(lhs) = (\(lhs) == \(rhs)) ? 1 : 0")
}
}
if result.isEmpty { return "" }
result.removeFirst(1)
result.append(contentsOf: postfix)
let content = result.map { " \($0)" }.joined(separator: "\n")
return """
static let processors: [(Int, inout Int, inout Int, inout Int) -> Void] = [
\(content)
]
"""
}
// Generated
static let processors: [(Int, inout Int, inout Int, inout Int) -> Void] = [
{ (w: Int, x: inout Int, y: inout Int, z: inout Int) -> Void in
x *= 0
x += z
x %= 26
z /= 1
x += 12
x = (x == w) ? 1 : 0
x = (x == 0) ? 1 : 0
y *= 0
y += 25
y *= x
y += 1
z *= y
y *= 0
y += w
y += 4
y *= x
z += y
},
{ (w: Int, x: inout Int, y: inout Int, z: inout Int) -> Void in
x *= 0
x += z
x %= 26
z /= 1
x += 11
x = (x == w) ? 1 : 0
x = (x == 0) ? 1 : 0
y *= 0
y += 25
y *= x
y += 1
z *= y
y *= 0
y += w
y += 11
y *= x
z += y
},
{ (w: Int, x: inout Int, y: inout Int, z: inout Int) -> Void in
x *= 0
x += z
x %= 26
z /= 1
x += 13
x = (x == w) ? 1 : 0
x = (x == 0) ? 1 : 0
y *= 0
y += 25
y *= x
y += 1
z *= y
y *= 0
y += w
y += 5
y *= x
z += y
},
{ (w: Int, x: inout Int, y: inout Int, z: inout Int) -> Void in
x *= 0
x += z
x %= 26
z /= 1
x += 11
x = (x == w) ? 1 : 0
x = (x == 0) ? 1 : 0
y *= 0
y += 25
y *= x
y += 1
z *= y
y *= 0
y += w
y += 11
y *= x
z += y
},
{ (w: Int, x: inout Int, y: inout Int, z: inout Int) -> Void in
x *= 0
x += z
x %= 26
z /= 1
x += 14
x = (x == w) ? 1 : 0
x = (x == 0) ? 1 : 0
y *= 0
y += 25
y *= x
y += 1
z *= y
y *= 0
y += w
y += 14
y *= x
z += y
},
{ (w: Int, x: inout Int, y: inout Int, z: inout Int) -> Void in
x *= 0
x += z
x %= 26
z /= 26
x += -10
x = (x == w) ? 1 : 0
x = (x == 0) ? 1 : 0
y *= 0
y += 25
y *= x
y += 1
z *= y
y *= 0
y += w
y += 7
y *= x
z += y
},
{ (w: Int, x: inout Int, y: inout Int, z: inout Int) -> Void in
x *= 0
x += z
x %= 26
z /= 1
x += 11
x = (x == w) ? 1 : 0
x = (x == 0) ? 1 : 0
y *= 0
y += 25
y *= x
y += 1
z *= y
y *= 0
y += w
y += 11
y *= x
z += y
},
{ (w: Int, x: inout Int, y: inout Int, z: inout Int) -> Void in
x *= 0
x += z
x %= 26
z /= 26
x += -9
x = (x == w) ? 1 : 0
x = (x == 0) ? 1 : 0
y *= 0
y += 25
y *= x
y += 1
z *= y
y *= 0
y += w
y += 4
y *= x
z += y
},
{ (w: Int, x: inout Int, y: inout Int, z: inout Int) -> Void in
x *= 0
x += z
x %= 26
z /= 26
x += -3
x = (x == w) ? 1 : 0
x = (x == 0) ? 1 : 0
y *= 0
y += 25
y *= x
y += 1
z *= y
y *= 0
y += w
y += 6
y *= x
z += y
},
{ (w: Int, x: inout Int, y: inout Int, z: inout Int) -> Void in
x *= 0
x += z
x %= 26
z /= 1
x += 13
x = (x == w) ? 1 : 0
x = (x == 0) ? 1 : 0
y *= 0
y += 25
y *= x
y += 1
z *= y
y *= 0
y += w
y += 5
y *= x
z += y
},
{ (w: Int, x: inout Int, y: inout Int, z: inout Int) -> Void in
x *= 0
x += z
x %= 26
z /= 26
x += -5
x = (x == w) ? 1 : 0
x = (x == 0) ? 1 : 0
y *= 0
y += 25
y *= x
y += 1
z *= y
y *= 0
y += w
y += 9
y *= x
z += y
},
{ (w: Int, x: inout Int, y: inout Int, z: inout Int) -> Void in
x *= 0
x += z
x %= 26
z /= 26
x += -10
x = (x == w) ? 1 : 0
x = (x == 0) ? 1 : 0
y *= 0
y += 25
y *= x
y += 1
z *= y
y *= 0
y += w
y += 12
y *= x
z += y
},
{ (w: Int, x: inout Int, y: inout Int, z: inout Int) -> Void in
x *= 0
x += z
x %= 26
z /= 26
x += -4
x = (x == w) ? 1 : 0
x = (x == 0) ? 1 : 0
y *= 0
y += 25
y *= x
y += 1
z *= y
y *= 0
y += w
y += 14
y *= x
z += y
},
{ (w: Int, x: inout Int, y: inout Int, z: inout Int) -> Void in
x *= 0
x += z
x %= 26
z /= 26
x += -5
x = (x == w) ? 1 : 0
x = (x == 0) ? 1 : 0
y *= 0
y += 25
y *= x
y += 1
z *= y
y *= 0
y += w
y += 14
y *= x
z += y
},
]
static func process(digits: [Int], cache: inout Set<State>) -> String {
func solve(state: State) -> String? {
guard state.idx < processors.count else { return state.d3 == 0 ? "" : nil }
if cache.contains(state) { return nil }
for val in digits {
var state = state
processors[state.idx](val, &state.d1, &state.d2, &state.d3)
state.idx += 1
if let result = solve(state: state) {
return "\(val)\(result)"
}
}
cache.insert(state)
return nil
}
return solve(state: .init(idx: 0, d1: 0, d2: 0, d3: 0))!
}
}
func task24_1(_ input: TaskInput) {
guard input.prefix != "sample" else {
// No sample
return
}
if T24.processors.count == 0 {
let ops = input.task24()
print(T24.stringify(ops: ops))
} else {
var cache = Set<T24.State>()
let maxVal = T24.process(digits: (1...9).reversed(), cache: &cache)
let minVal = T24.process(digits: Array(1...9), cache: &cache)
print("T24_1: \(maxVal)")
print("T24_2: \(minVal)")
}
}
func task24_2(_ input: TaskInput) {
// In _1
}
// MARK: - Day 25
extension TaskInput {
func task25() -> [[Int]] {
readInput("25").split(separator: "\n").map { l in
l.map { c in
switch c {
case ".":
return 0
case ">":
return 1
case "v":
return 2
default:
fatalError()
}
}
}
}
}
enum T25 {
}
func task25_1(_ input: TaskInput) {
var field = input.task25()
let (h, w) = (field.count, field.first!.count)
var step = 0
var moved = true
while moved {
moved = false
step += 1
for (m, dx, dy) in [(1, 1, 0), (2, 0, 1)] {
var moves = [(Int, Int, Int, Int)]()
for y in 0..<h {
for x in 0..<w {
let (nx, ny) = ((x + dx) % w, (y + dy) % h)
if field[y][x] == m && field[ny][nx] == 0 {
moves.append((x, y, nx, ny))
}
}
}
moved = moved || moves.isEmpty == false
for (x, y, nx, ny) in moves {
(field[y][x], field[ny][nx]) = (field[ny][nx], field[y][x])
}
}
// print(field.map { l in l.map { $0 == 0 ? "." : ($0 == 1 ? ">" : "v") }.joined()}.joined(separator: "\n"))
}
print("T25_1: \(step)")
}
func task25_2(_ input: TaskInput) {
print("T25_2: Merry Christmas!")
}
// MARK: - Main
let inputs = [
TaskInput(prefix: "sample"),
TaskInput(),
]
for input in inputs {
print("Run for \(input.prefix)")
let start = Date()
task01_1(input)
task01_2(input)
task02_1(input)
task02_2(input)
task03_1(input)
task03_2(input)
task04_1(input)
task04_2(input)
task05_1(input)
task05_2(input)
task06_1(input)
task06_2(input)
task07_1(input)
task07_2(input)
task08_1(input)
task08_2(input)
task09_1(input)
task09_2(input)
task10_1(input)
task10_2(input)
task11_1(input)
task11_2(input)
task12_1(input)
task12_2(input)
task13_1(input)
task13_2(input)
task14_1(input)
task14_2(input)
task15_1(input)
task15_2(input)
task16_1(input)
task16_2(input)
task17_1(input)
task17_2(input)
task18_1(input)
task18_2(input)
task19_1(input)
task19_2(input)
task20_1(input)
task20_2(input)
task21_1(input)
task21_2(input)
task22_1(input)
task22_2(input)
task23_1(input)
task23_2(input)
task24_1(input)
task24_2(input)
task25_1(input)
task25_2(input)
print("Time: \(String(format: "%0.4f", -start.timeIntervalSinceNow))")
}
| 28.476996 | 154 | 0.421572 |
9ba9a78e3302bcc412ddb87e82213894cf014403 | 4,241 | import UIKit
public class RangeSlider: UIControl {
override public var frame: CGRect {
didSet {
updateLayerFrames()
}
}
public var trackLayerBGColor: UIColor = .clear {
didSet {
configureSlider()
}
}
public var minimumValue: CGFloat = 0 {
didSet {
updateLayerFrames()
}
}
public var maximumValue: CGFloat = 1 {
didSet {
updateLayerFrames()
}
}
public var currentValue: CGFloat = 0.2 {
didSet {
updateLayerFrames()
}
}
public var trackTintColor = UIColor.gray {
didSet {
trackLayer.setNeedsDisplay()
}
}
public var trackHighlightTintColor = UIColor.lightGray {
didSet {
trackLayer.setNeedsDisplay()
}
}
public var thumbBackgroundColor = UIColor.darkGray {
didSet {
thumbView.setNeedsDisplay()
}
}
public var thumbTextColor = UIColor.white {
didSet {
thumbView.setNeedsDisplay()
}
}
private let trackLayer = RangeSliderTrackLayer()
private let thumbView = UILabel()
private let thumbSize = CGSize(width: 50, height: 25)
private var previousLocation = CGPoint()
public var didBeginTracking: ((RangeSlider) -> ())?
public var didEndTracking: ((RangeSlider) -> ())?
override public init(frame: CGRect) {
super.init(frame: frame)
configureSlider()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configureSlider()
}
private func configureSlider() {
trackLayer.rangeSlider = self
trackLayer.contentsScale = UIScreen.main.scale
layer.addSublayer(trackLayer)
thumbView.backgroundColor = thumbBackgroundColor
thumbView.applyCornerRadius()
thumbView.textColor = thumbTextColor
thumbView.textAlignment = .center
addSubview(thumbView)
updateLayerFrames()
}
private func updateLayerFrames() {
CATransaction.begin()
CATransaction.setDisableActions(true)
trackLayer.frame = bounds.insetBy(dx: 0.0, dy: 14.6)
trackLayer.masksToBounds = true
trackLayer.cornerRadius = trackLayer.frame.height / 2
trackLayer.setNeedsDisplay()
thumbView.frame = CGRect(origin: thumbOriginForValue(currentValue), size: thumbSize)
thumbView.text = "\(Int(currentValue * 100))"
CATransaction.commit()
}
internal func positionForValue(_ value: CGFloat) -> CGFloat {
return bounds.width * value
}
private func thumbOriginForValue(_ value: CGFloat) -> CGPoint {
let x = positionForValue(value) - thumbSize.width / 2.0
return CGPoint(x: x, y: (bounds.height - thumbSize.height) / 2.0)
}
}
extension RangeSlider {
override public func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
previousLocation = touch.location(in: self)
if thumbView.frame.contains(previousLocation) {
thumbView.isHighlighted = true
}
didBeginTracking?(self)
return thumbView.isHighlighted
}
override public func continueTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
let location = touch.location(in: self)
let deltaLocation = location.x - previousLocation.x
let deltaValue = (maximumValue - minimumValue) * deltaLocation / bounds.width
previousLocation = location
if thumbView.isHighlighted {
currentValue += deltaValue
currentValue = boundValue(currentValue, toLowerValue: minimumValue, upperValue: maximumValue)
}
thumbView.text = "\(Int(currentValue * 100))"
sendActions(for: .valueChanged)
return true
}
private func boundValue(_ value: CGFloat, toLowerValue lowerValue: CGFloat,
upperValue: CGFloat) -> CGFloat {
return min(max(value, lowerValue), upperValue)
}
override public func endTracking(_ touch: UITouch?, with event: UIEvent?) {
thumbView.isHighlighted = false
didEndTracking?(self)
}
}
| 30.078014 | 105 | 0.622259 |
d6581a9897007a8f78238cda96eddf3eb72ff79e | 7,783 | //
// walletTests.swift
// walletTests
//
// Created by Francisco Gindre on 12/26/19.
// Copyright © 2019 Francisco Gindre. All rights reserved.
//
import XCTest
@testable import ECC_Wallet_Testnet
import MnemonicSwift
@testable import ZcashLightClientKit
class walletTests: 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 testReplyToMemo() {
let memo = "Happy Birthday! Have fun spending these ZEC! visit https://paywithz.cash to know all the places that take ZEC payments!"
let replyTo = "testsapling1ctuamfer5xjnnrdr3xdazenljx0mu0gutcf9u9e74tr2d3jwjnt0qllzxaplu54hgc2tyjdc2p6"
let replyToMemo = SendFlowEnvironment.includeReplyTo(address: replyTo, in: memo)
let expected = memo + "\nReply-To: \(replyTo)"
XCTAssertTrue(replyToMemo.count <= SendFlowEnvironment.maxMemoLength)
XCTAssertEqual(replyToMemo, expected)
}
func testOnlyReplyToMemo() {
let memo = ""
let replyTo = "testsapling1ctuamfer5xjnnrdr3xdazenljx0mu0gutcf9u9e74tr2d3jwjnt0qllzxaplu54hgc2tyjdc2p6"
let replyToMemo = SendFlowEnvironment.buildMemo(memo: memo, includesMemo: true, replyToAddress: replyTo)
let expected = memo + "\nReply-To: \(replyTo)"
guard replyToMemo != nil else {
XCTFail("memo nil when it shouldn't be")
return }
XCTAssertTrue(replyToMemo!.count <= SendFlowEnvironment.maxMemoLength)
XCTAssertEqual(replyToMemo, expected)
}
func testReplyToHugeMemo() {
let memo = "Happy Birthday! Have fun spending these ZEC! visit https://paywithz.cash to know all the places that take ZEC payments! Happy Birthday! Have fun spending these ZEC! visit https://paywithz.cash to know all the places that take ZEC payments! Happy Birthday! Have fun spending these ZEC! visit https://paywithz.cash to know all the places that take ZEC payments! Happy Birthday! Have fun spending these ZEC! visit https://paywithz.cash to know all the places that take ZEC payments!"
let replyTo = "testsapling1ctuamfer5xjnnrdr3xdazenljx0mu0gutcf9u9e74tr2d3jwjnt0qllzxaplu54hgc2tyjdc2p6"
let replyToMemo = SendFlowEnvironment.includeReplyTo(address: replyTo, in: memo)
let trimmedExpected = "Happy Birthday! Have fun spending these ZEC! visit https://paywithz.cash to know all the places that take ZEC payments! Happy Birthday! Have fun spending these ZEC! visit https://paywithz.cash to know all the places that take ZEC payments! Happy Birthday! Have fun spending these ZEC! visit https://paywithz.cash to know all the places that take ZEC payments! Happy Birthday! Have "
let expected = trimmedExpected + "\nReply-To: \(replyTo)"
XCTAssertTrue(replyToMemo.count <= SendFlowEnvironment.maxMemoLength)
XCTAssertEqual(replyToMemo, expected)
// XCTAssertEqual(trimmedExpected, replyToMemo.)
}
func testKeyPadDecimalLimit() {
let keyPadViewModel = KeyPadViewModel(value: .constant(""))
XCTAssertFalse(keyPadViewModel.hasEightOrMoreDecimals("hello world"))
XCTAssertFalse(keyPadViewModel.hasEightOrMoreDecimals("0.0"))
XCTAssertFalse(keyPadViewModel.hasEightOrMoreDecimals("1.0"))
XCTAssertFalse(keyPadViewModel.hasEightOrMoreDecimals("100000"))
XCTAssertFalse(keyPadViewModel.hasEightOrMoreDecimals("1.0000000"))
XCTAssertFalse(keyPadViewModel.hasEightOrMoreDecimals("1000000.0000000"))
XCTAssertFalse(keyPadViewModel.hasEightOrMoreDecimals("1.0000000"))
XCTAssertTrue(keyPadViewModel.hasEightOrMoreDecimals("1.00000000"))
XCTAssertTrue(keyPadViewModel.hasEightOrMoreDecimals("0.000000001"))
XCTAssertTrue(keyPadViewModel.hasEightOrMoreDecimals("0.000000000"))
XCTAssertTrue(keyPadViewModel.hasEightOrMoreDecimals("0.0000000000"))
}
func testMnemonics() throws {
let phrase = try Mnemonic.generateMnemonic(strength: 256)
XCTAssertTrue(phrase.split(separator: " ").count == 24)
XCTAssertNotNil(try Mnemonic.deterministicSeedString(from: phrase),"could not generate seed from phrase: \(phrase)")
}
func testRestore() throws {
let expectedSeed = "715b4b7950c2153e818f88122f8e54a00e36c42e47ba9589dc82fcecfc5b7ec7d06f4e3a3363a0221e06f14f52e03294290139d05d293059a55076b7f37d6726"
let phrase = "abuse fee wage robot october tongue utility gloom dizzy best victory armor second share pilot help cotton mango music decorate scheme mix tell never"
XCTAssertEqual(try MnemonicSeedProvider.default.toSeed(mnemonic: phrase).hexString,expectedSeed)
}
func testAddressSlicing() {
let address = "zs1gn2ah0zqhsxnrqwuvwmgxpl5h3ha033qexhsz8tems53fw877f4gug353eefd6z8z3n4zxty65c"
let split = address.slice(into: 8)
XCTAssert(split.count == 8)
}
func testCompatibility() throws {
let words = "human pulse approve subway climb stairs mind gentle raccoon warfare fog roast sponsor under absorb spirit hurdle animal original honey owner upper empower describe"
let hex = "f4e3d38d9c244da7d0407e19a93c80429614ee82dcf62c141235751c9f1228905d12a1f275f5c22f6fb7fcd9e0a97f1676e0eec53fdeeeafe8ce8aa39639b9fe"
XCTAssertNoThrow(try MnemonicSeedProvider.default.isValid(mnemonic: words))
XCTAssertEqual(try MnemonicSeedProvider.default.toSeed(mnemonic: words).hexString, hex)
}
// func testAlmostIncludesReplyTo() {
// let memo = "this is a test memo"
// let addr = "nowhere"
// let expected = "\(memo)\nReply-To: \(addr)"
// XCTAssertFalse(expected.includesReplyTo)
// XCTAssertNil(expected.replyToAddress)
// }
//
// func testIncludesReplyTo() {
// let memo = "this is a test memo"
// let addr = "zs1gn2ah0zqhsxnrqwuvwmgxpl5h3ha033qexhsz8tems53fw877f4gug353eefd6z8z3n4zxty65c"
// let expected = "\(memo)\nReply-To: \(addr)"
// XCTAssertTrue(expected.includesReplyTo)
// XCTAssertNotNil(expected.replyToAddress)
// }
func testBuildMemo() {
let memo = "this is a test memo"
let addr = "zs1gn2ah0zqhsxnrqwuvwmgxpl5h3ha033qexhsz8tems53fw877f4gug353eefd6z8z3n4zxty65c"
let expected = "\(memo)\nReply-To: \(addr)"
XCTAssertEqual(expected, SendFlowEnvironment.buildMemo(memo: memo, includesMemo: true, replyToAddress: addr))
XCTAssertEqual(nil, SendFlowEnvironment.buildMemo(memo: "", includesMemo: true, replyToAddress: nil))
XCTAssertEqual(nil, SendFlowEnvironment.buildMemo(memo: memo, includesMemo: false, replyToAddress: addr))
}
func testBlockExplorerUrl() {
let txId = "4fd71c6363ac451674ae117f98e8225e0d4d1de67d44091287e62ba0ccf5358b"
let expectedMainnetURL = "https://blockchair.com/zcash/transaction/\(txId)"
let expectedTestnetURL = "https://explorer.testnet.z.cash/tx/\(txId)"
let mainnetURL = UrlHandler.blockExplorerURLMainnet(for: txId)?.absoluteString
let testnetURL = UrlHandler.blockExplorerURLTestnet(for: txId)?.absoluteString
XCTAssertEqual(mainnetURL, expectedMainnetURL)
XCTAssertEqual(testnetURL, expectedTestnetURL)
}
}
extension Array where Element == UInt8 {
var hexString: String {
self.map { String(format: "%02x", $0) }.joined()
}
}
| 49.259494 | 500 | 0.708981 |
097f70e0ca336861f017240a9bf45b295c3219fa | 7,336 | //
// Element.swift
// DetoxTestRunner
//
// Created by Leo Natan (Wix) on 2/27/20.
//
import Foundation
import UIKit
import WebKit
class Element : NSObject {
let predicate : Predicate
let index : Int?
struct Keys {
static let predicate = "predicate"
static let index = "atIndex"
}
required init(predicate: Predicate, index: Int?) {
self.predicate = predicate
self.index = index
}
class func with(dictionaryRepresentation: [String: Any]) throws -> Element {
let predicateDictionaryRepresentation = dictionaryRepresentation[Keys.predicate] as! [String: Any]
let index = dictionaryRepresentation[Keys.index] as! Int?
return Element(predicate: try Predicate.with(dictionaryRepresentation: predicateDictionaryRepresentation), index: index)
}
var exists : Bool {
do {
var moreThanZero : Bool = false
try dtx_try {
moreThanZero = self.views.count > 0
}
return moreThanZero
} catch {
return false
}
}
private var views : [NSObject] {
//TODO: Consider searching here in all windows from all scenes.
let array = (UIView.dtx_findViewsInKeySceneWindows(passing: predicate.predicateForQuery()) as! [NSObject])
guard array.count > 0 else {
dtx_fatalError("No elements found for “\(self.description)”", viewDescription: failDebugAttributes)
}
return array
}
private var view : NSObject {
let array = self.views
let element : NSObject
if let index = index {
guard index < array.count else {
dtx_fatalError("Index \(index) beyond bounds \(array.count > 0 ? "[0 .. \(array.count - 1)] " : " ")for “\(self.description)”", viewDescription: failDebugAttributes)
}
element = array[index]
} else {
//Will fail test if more than one element are resolved from the query
guard array.count == 1 else {
dtx_fatalError("Multiple elements found for “\(self.description)”", viewDescription: failDebugAttributes)
}
element = array.first!
}
return element
}
private func extractScrollView() -> UIScrollView {
if let view = self.view as? UIScrollView {
return view
}
else if let view = self.view as? WKWebView {
return view.scrollView
} else if ReactNativeSupport.isReactNativeApp && NSStringFromClass(type(of: view)) == "RCTScrollView" {
return (view.value(forKey: "scrollView") as! UIScrollView)
}
dtx_fatalError("View “\(self.view.dtx_shortDescription)” is not an instance of “UIScrollView”", viewDescription: debugAttributes)
}
override var description: String {
return String(format: "MATCHER(%@)%@", predicate.description, index != nil ? " AT INDEX(\(index!))" : "")
}
fileprivate var failDebugAttributes: [String: Any] {
return NSObject.dtx_genericElementDebugAttributes
}
var debugAttributes: [String: Any] {
do {
var rv: [String: Any]! = nil
try dtx_try {
rv = view.dtx_elementDebugAttributes
}
return rv
} catch {
return failDebugAttributes
}
}
func tap(at point: CGPoint? = nil, numberOfTaps: Int = 1) {
guard let point = point else {
view.dtx_tapAtAccessibilityActivationPoint(withNumberOfTaps: UInt(numberOfTaps))
return
}
view.dtx_tap(at: point, numberOfTaps: UInt(numberOfTaps))
}
func longPress(at point: CGPoint? = nil, duration: TimeInterval = 1.0) {
guard let point = point else {
view.dtx_longPressAtAccessibilityActivationPoint(forDuration: duration)
return
}
view.dtx_longPress(at: point, duration: duration)
}
func longPress(at normalizedPoint: CGPoint, duration: TimeInterval, dragToElement targetElement: Element, normalizedTargetPoint: CGPoint, velocity: CGFloat, holdForDuration lastHoldDuration: TimeInterval) {
view.dtx_longPress(at:normalizedPoint, duration:duration, target:targetElement.view, normalizedTargetPoint:normalizedTargetPoint, velocity:velocity, lastHoldDuration:lastHoldDuration)
}
func swipe(normalizedOffset: CGPoint, velocity: CGFloat = 1.0, normalizedStartingPoint: CGPoint? = nil) {
if let normalizedStartingPoint = normalizedStartingPoint {
view.dtx_swipe(withNormalizedOffset: normalizedOffset, velocity: velocity, normalizedStartingPoint: normalizedStartingPoint)
} else {
view.dtx_swipe(withNormalizedOffset: normalizedOffset, velocity: velocity)
}
}
func pinch(withScale scale: CGFloat, velocity: CGFloat = 2.0, angle: CGFloat = 0.0) {
view.dtx_pinch(withScale: scale, velocity: velocity, angle: angle)
}
func scroll(to edge: UIRectEdge) {
let scrollView = extractScrollView()
scrollView.dtx_scroll(to: edge)
}
func scroll(withOffset offset: CGPoint, normalizedStartingPoint: CGPoint? = nil) {
let scrollView = extractScrollView()
if let normalizedStartingPoint = normalizedStartingPoint {
scrollView.dtx_scroll(withOffset: offset, normalizedStartingPoint: normalizedStartingPoint)
} else {
scrollView.dtx_scroll(withOffset: offset)
}
}
func clearText() {
view.dtx_clearText()
}
func typeText(_ text: String) {
view.dtx_typeText(text)
}
func replaceText(_ text: String) {
view.dtx_replaceText(text)
}
func adjust(toDate date: Date) {
if let view = view as? UIDatePicker {
view.dtx_adjust(to: date)
} else {
dtx_fatalError("View “\(view.dtx_shortDescription)” is not an instance of “UIDatePicker”", viewDescription: debugAttributes)
}
}
func setComponent(_ component: Int, toValue value: Any) {
if let view = view as? UIPickerView {
view.dtx_setComponent(component, toValue: value)
} else {
dtx_fatalError("View “\(view.dtx_shortDescription)” is not an instance of “UIPickerView”", viewDescription: debugAttributes)
}
}
func adjust(toNormalizedSliderPosition normalizedSliderPosition: Double) {
guard let slider = view as? UISlider else {
dtx_fatalError("View \(view.dtx_shortDescription) is not instance of “UISlider”", viewDescription: debugAttributes)
}
slider.dtx_normalizedSliderPosition = normalizedSliderPosition
}
func isVisible() throws -> Bool {
var error: NSError? = nil
let rv = view.dtx_isVisible(at: view.dtx_bounds, error: &error)
if let error = error {
throw error
}
return rv
}
func isFocused() -> Bool {
return view.dtx_isFocused()
}
func isHittable() throws -> Bool {
var error: NSError? = nil
let rv = view.dtx_isHittable(at: view.dtx_accessibilityActivationPointInViewCoordinateSpace, error: &error)
if let error = error {
throw error
}
return rv
}
@objc
var text: String? {
return view.value(forKey: "dtx_text") as? String
}
@objc
var placeholder: String? {
return view.value(forKey: "dtx_placeholder") as? String
}
@objc
var identifier: String? {
return view.accessibilityIdentifier
}
@objc
var label: String? {
return view.accessibilityLabel
}
@objc
var value: String? {
return view.accessibilityValue
}
@objc
var normalizedSliderPosition: Double {
get {
guard let slider = view as? UISlider else {
dtx_fatalError("View \(view.dtx_shortDescription) is not instance of “UISlider”", viewDescription: debugAttributes)
}
return slider.dtx_normalizedSliderPosition
}
}
@objc
var attributes: [String : Any] {
let views = self.views
if views.count == 1 {
return views.first!.dtx_attributes
} else {
let elements = views.map {
return $0.dtx_attributes
}
return ["elements": elements]
}
}
}
| 27.17037 | 207 | 0.716739 |
dd44e05c56061230366ca62ebe7caecd13d0ab19 | 436 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
struct d{class A{func a{var A{{a{{var
| 43.6 | 79 | 0.75 |
1d5a62dea085f8d6fe9ac851c10b7206ee5be9e0 | 486 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
func a{
struct S<T where g:T{
{
}
class B
struct S{
func d{
let a=B
a{{}}}}
struct B{var _=a{
| 25.578947 | 78 | 0.722222 |
095c4caddddf6e7138fc6e44fb52313f2e246830 | 1,429 | //
// AppDelegate.swift
// SplashAnimate
//
// Created by Hanson on 2017/12/6.
// Copyright © 2017年 HansonStudio. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
setUpWindowAndRootView()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
}
func applicationDidEnterBackground(_ application: UIApplication) {
}
func applicationWillEnterForeground(_ application: UIApplication) {
}
func applicationDidBecomeActive(_ application: UIApplication) {
}
func applicationWillTerminate(_ application: UIApplication) {
}
}
extension AppDelegate {
func setUpWindowAndRootView() {
window = UIWindow(frame: UIScreen.main.bounds)
window!.backgroundColor = UIColor.white
window!.makeKeyAndVisible()
let adVC = AdViewController()
adVC.completion = {
let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ViewController") as! ViewController
vc.adView = adVC.view
self.window!.rootViewController = vc
}
window!.rootViewController = adVC
}
}
| 25.517857 | 144 | 0.680896 |
f9b807a4c0243f9f7788cb9faf55a262c724725b | 568 | import CoreImage
public class PhotoEffectInstant {
public var image: CIImage
required public init(image: CIImage){
self.image = image
}
public func filter() -> CIFilter? {
guard let filter = CIFilter(name: "CIPhotoEffectInstant") else { return nil }
filter.setValue(image, forKey: "inputImage")
return filter
}
}
extension CIImage {
public func photoEffectInstantFilter() -> CIImage? {
guard let filter = CIFilter(name: "CIPhotoEffectInstant") else { return nil }
filter.setValue(self, forKey: "inputImage")
return filter.outputImage
}
} | 21.037037 | 79 | 0.725352 |
7a5c1550395238eea21e9eedf2c9b57f54e0aa37 | 725 | import Foundation
struct RoomResponse: Codable {
let id: String
let displayName: String
enum CodingKeys: String, CodingKey {
case id
case displayName = "display_name"
}
}
struct CreateRoom: Codable {
struct Body: Codable {
let displayName: String
enum CodingKeys: String, CodingKey {
case displayName = "display_name"
}
}
struct Response: Codable {
let id: String
}
}
struct Auth: Codable {
struct Body: Codable {
let name: String
}
struct Response: Codable {
let name: String
let jwt: String
}
}
struct Member: Hashable {
let id: String
let name: String
}
| 17.261905 | 45 | 0.577931 |
2353f2291202cd187d74a12922cdbe3f790d87cf | 519 | //
// FlowStepType.swift
// Flowter
//
// Created by Paulo Cesar Saito on 13/08/18.
// Copyright 2018 Zazcar. All rights reserved.
//
import Foundation
internal protocol BaseFlowStepType {
var nextStep: BaseFlowStepType? { get set }
var endFlowAction: ( () -> Void)? { get set }
func destroy()
}
internal protocol FlowStepType: BaseFlowStepType {
func present(with context: Any?)
func dismiss()
}
internal extension FlowStepType {
func present() {
present(with: nil)
}
}
| 19.222222 | 50 | 0.662813 |
91ad077a413fc055222d10709c7da2a01adad8d8 | 110 | public enum LzwCodingError: Error {
case decodedIndicesEmpty
case noLastCode
case tableTooSmall
}
| 18.333333 | 35 | 0.754545 |
ddb7b25700ca0ff470bfedadcaab339c3bd10f10 | 5,428 | // Copyright 2016 LinkedIn Corp.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
import UIKit
// MARK: - ReloadableView
/**
A view that can be reloaded with data.
UITableView and UICollectionView conform to this protocol.
*/
public protocol ReloadableView: class {
/// The bounds rectangle, which describes the view’s location and size in its own coordinate system.
var bounds: CGRect { get }
/// Returns whether the user has touched the content to initiate scrolling.
var isTracking: Bool { get }
/// Returns whether the content is moving in the scroll view after the user lifted their finger.
var isDecelerating: Bool { get }
/**
Reloads the data synchronously.
This means that it must be safe to immediately call other operations such as `insert`.
*/
func reloadDataSynchronously()
/// Registers views for the reuse identifier.
func registerViews(withReuseIdentifier reuseIdentifier: String)
/**
Performs a set of updates in a batch.
The reloadable view must follow the same semantics for handling the index paths
of concurrent inserts/updates/deletes as UICollectionView documents in `performBatchUpdates`.
*/
func perform(batchUpdates: BatchUpdates, completion: (() -> Void)?)
}
// MARK: - UICollectionView
/// Make UICollectionView conform to ReloadableView protocol.
extension UICollectionView: ReloadableView {
@objc
open func reloadDataSynchronously() {
reloadData()
// Force a layout so that it is safe to call insert after this.
layoutIfNeeded()
}
@objc
open func registerViews(withReuseIdentifier reuseIdentifier: String) {
register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: reuseIdentifier)
register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: reuseIdentifier)
}
@objc
open func perform(batchUpdates: BatchUpdates, completion: (() -> Void)?) {
performBatchUpdates({
if batchUpdates.insertItems.count > 0 {
self.insertItems(at: batchUpdates.insertItems)
}
if batchUpdates.deleteItems.count > 0 {
self.deleteItems(at: batchUpdates.deleteItems)
}
if batchUpdates.reloadItems.count > 0 {
self.reloadItems(at: batchUpdates.reloadItems)
}
for move in batchUpdates.moveItems {
self.moveItem(at: move.from, to: move.to)
}
if batchUpdates.insertSections.count > 0 {
self.insertSections(batchUpdates.insertSections)
}
if batchUpdates.deleteSections.count > 0 {
self.deleteSections(batchUpdates.deleteSections)
}
if batchUpdates.reloadSections.count > 0 {
self.reloadSections(batchUpdates.reloadSections)
}
for move in batchUpdates.moveSections {
self.moveSection(move.from, toSection: move.to)
}
}, completion: { _ in
completion?()
})
}
}
// MARK: - UITableView
/// Make UITableView conform to ReloadableView protocol.
extension UITableView: ReloadableView {
@objc
open func reloadDataSynchronously() {
reloadData()
}
@objc
open func registerViews(withReuseIdentifier reuseIdentifier: String) {
register(UITableViewCell.self, forCellReuseIdentifier: reuseIdentifier)
register(UITableViewHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: reuseIdentifier)
}
@objc
open func perform(batchUpdates: BatchUpdates, completion: (() -> Void)?) {
beginUpdates()
// Update items.
if batchUpdates.insertItems.count > 0 {
insertRows(at: batchUpdates.insertItems, with: .automatic)
}
if batchUpdates.deleteItems.count > 0 {
deleteRows(at: batchUpdates.deleteItems, with: .automatic)
}
if batchUpdates.reloadItems.count > 0 {
reloadRows(at: batchUpdates.reloadItems, with: .automatic)
}
for move in batchUpdates.moveItems {
moveRow(at: move.from, to: move.to)
}
// Update sections.
if batchUpdates.insertSections.count > 0 {
insertSections(batchUpdates.insertSections, with: .automatic)
}
if batchUpdates.deleteSections.count > 0 {
deleteSections(batchUpdates.deleteSections, with: .automatic)
}
if batchUpdates.reloadSections.count > 0 {
reloadSections(batchUpdates.reloadSections, with: .automatic)
}
for move in batchUpdates.moveSections {
moveSection(move.from, toSection: move.to)
}
endUpdates()
completion?()
}
}
| 35.246753 | 156 | 0.665438 |
6445f97af44314fd0136d1e86b6eda95ddef3036 | 5,637 | //
// DMLoginViewController.swift
// Dominant Investors
//
// Created by Nekit on 19.02.17.
// Copyright © 2017 Dominant. All rights reserved.
//
import UIKit
import MBProgressHUD
class DMLoginViewController: DMViewController, UITextFieldDelegate {
@IBOutlet weak var usernameTextField : UITextField!
@IBOutlet weak var passwordTextField : UITextField!
@IBOutlet weak var overlayView : FXBlurView!
@IBOutlet weak var createNewAccount : UIButton!
@IBOutlet var backgroundImageView : UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
// MARK: Private
private func setupUI() {
drawBlurOverlay()
configureLabels()
configureTextFields()
configureKeyboard()
}
private func configureKeyboard() {
let recognizer = UITapGestureRecognizer(target: self, action: #selector(self.hideKeyboard))
self.view.addGestureRecognizer(recognizer)
}
@objc private func hideKeyboard() {
self.view.endEditing(true)
}
private func drawBlurOverlay() {
self.overlayView.clipsToBounds = true
self.overlayView.layer.cornerRadius = 7
self.overlayView.isBlurEnabled = true
self.overlayView.blurRadius = 20
self.overlayView.isDynamic = false
self.overlayView.tintColor = UIColor.lightGray
}
private func configureLabels() {
let underlineAttriString = NSMutableAttributedString(string:"CREATE ACCOUNT", attributes:
[NSAttributedStringKey.underlineStyle: NSUnderlineStyle.styleSingle.rawValue])
underlineAttriString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.white, range: NSRange.init(location: 0, length: underlineAttriString.length))
underlineAttriString.addAttribute(NSAttributedStringKey.font, value: Fonts.DMMyseoFont, range: NSRange.init(location: 0, length: underlineAttriString.length))
createNewAccount.setAttributedTitle(underlineAttriString, for: .normal)
}
private func configureTextFields() {
self.usernameTextField.attributedPlaceholder =
NSAttributedString(string:"USERNAME",
attributes:[NSAttributedStringKey.foregroundColor: UIColor.white])
self.passwordTextField.attributedPlaceholder =
NSAttributedString(string:"PASSWORD",
attributes:[NSAttributedStringKey.foregroundColor: UIColor.white])
self.usernameTextField.delegate = self
self.passwordTextField.delegate = self
}
private func showTabBar() {
let tabBar = UIStoryboard(name: "TabBar", bundle: nil).instantiateInitialViewController()
self.navigationController?.pushViewController(tabBar!, animated: true)
}
private func proceedLogin() {
self.showActivityIndicator()
DMAuthorizationManager.sharedInstance.loginWith(login: self.usernameTextField.text!,
password: self.passwordTextField.text!) { (success, error) in
DispatchQueue.main.async {
self.dismissActivityIndicator()
if (success) {
self.showTabBar()
} else {
self.showAlertWith(title: NSLocalizedString("Authorization error", comment: ""),
message: error!.description,
cancelButton: false)
}
}
}
}
// MARK: Actions
@IBAction func loginButtonPressed(sender : UIButton) {
self.proceedLogin()
}
@IBAction func signUpButtonPressed(sender : UIButton) {
let signUp = UIStoryboard(name: "Authorization", bundle: nil).instantiateViewController(withIdentifier: "DMSignUpViewController")
self.present(signUp, animated: false, completion: nil)
}
// MARK: UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if (textField.tag == 3) {
self.proceedLogin()
}
let nextField = textField.tag + 1
let nextResponder = self.view.viewWithTag(nextField) as UIResponder!
if (nextResponder != nil){
nextResponder?.becomeFirstResponder()
} else {
textField.resignFirstResponder()
}
return false
}
func textFieldDidBeginEditing(_ textField: UITextField) {
textField.placeholder = nil;
if (textField.tag == 3) {
UIView.animate(withDuration: 0.2, animations: {
self.view.frame.origin.y = -150
})
}
}
func textFieldDidEndEditing(_ textField: UITextField) {
self.configureTextFields()
if (textField.tag == 3) {
UIView.animate(withDuration: 0.2, animations: {
self.view.frame.origin.y = 0
})
}
}
}
| 37.085526 | 173 | 0.560759 |
f95a9280bfce9f2ebb83cce4e3e55fa4fe6d58de | 2,729 | //
// LogViewController.swift
// Agora iOS Tutorial
//
// Created by CavanSu on 2019/8/1.
// Copyright © 2019 Agora.io. All rights reserved.
//
import UIKit
struct Log {
enum ContentType {
case info, warning, error, caption
var color: UIColor {
switch self {
case .info: return UIColor(red: 74.0 / 255.0, green: 144.0 / 255.0, blue: 226.0 / 255.0, alpha: 1)
case .warning: return UIColor(red: 254.0 / 255.0, green: 221.0 / 255.0, blue: 86.0 / 255.0, alpha: 1)
case .error: return UIColor(red: 254.0 / 255.0, green: 55.0 / 255.0, blue: 95.0 / 255.0, alpha: 1)
case .caption: return UIColor(red: 50.0 / 255.0, green: 50.0 / 255.0, blue: 50.0 / 255.0, alpha: 0.3)
}
}
}
var type: ContentType
var content: String
}
class LogCell: UITableViewCell {
@IBOutlet weak var content: UILabel!
@IBOutlet weak var colorView: UIView!
override func awakeFromNib() {
super.awakeFromNib()
colorView.layer.cornerRadius = 12.25
}
func update(_ log: Log) {
content.text = log.content
colorView.backgroundColor = log.type.color
}
}
class LogViewController: UITableViewController {
private lazy var list = [Log]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 44
tableView.cellLayoutMarginsFollowReadableWidth = false
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return list.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "LogCell", for: indexPath) as! LogCell
cell.update(list[indexPath.row])
return cell
}
}
extension LogViewController {
func log(type: Log.ContentType, content: String) {
let log = Log(type: type, content: content)
list.append(log)
let index = IndexPath(row: list.count - 1, section: 0)
tableView.insertRows(at: [index], with: .automatic)
tableView.scrollToRow(at: index, at: .middle, animated: true)
}
func update(content: String) {
if (list[list.count - 1].type != Log.ContentType.caption) {
log(type: Log.ContentType.caption, content: content)
} else {
list[list.count - 1].content = content
}
let index = IndexPath(row: list.count - 1, section: 0)
tableView.scrollToRow(at: index, at: .middle, animated: false)
}
}
| 32.105882 | 116 | 0.61561 |
0a99920bcd880ed9699307aba31fdb88b7d8f901 | 714 | //
// ViewController.swift
// Exmoney
//
// Created by Galina Gaynetdinova on 03/02/2017.
// Copyright © 2017 Galina Gaynetdinova. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.setToolbarHidden(true, animated: false)
navigationController?.isNavigationBarHidden = true
if (!userDefaults.bool(forKey: "flagToken")) {
//First opening App goes to Form with URL, Pass and Email
self.performSegue(withIdentifier: "URLView", sender: self)
} else {
self.performSegue(withIdentifier: "accountsSeque1", sender: self)
}
}
}
| 26.444444 | 77 | 0.666667 |
d69f290450250bde672152fce77fa5c52fdff61b | 151 | import Combine
public extension Sequence where Element: Publisher {
var merge: Publishers.MergeMany<Element> {
Publishers.MergeMany(self)
}
}
| 15.1 | 52 | 0.754967 |
266a5cf4b8fdbd6afc6ac1e51d89517c7d6ce8c3 | 3,284 | /*
MIT License
Copyright (c) 2017-2018 MessageKit
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import Foundation
import UIKit
open class ContactMessageSizeCalculator: MessageSizeCalculator {
public var incomingMessageNameLabelInsets = UIEdgeInsets(top: 7, left: 46, bottom: 7, right: 30)
public var outgoingMessageNameLabelInsets = UIEdgeInsets(top: 7, left: 41, bottom: 7, right: 35)
public var contactLabelFont = UIFont.preferredFont(forTextStyle: .body)
internal func contactLabelInsets(for message: MessageType) -> UIEdgeInsets {
let dataSource = messagesLayout.messagesDataSource
let isFromCurrentSender = dataSource.isFromCurrentSender(message: message)
return isFromCurrentSender ? outgoingMessageNameLabelInsets : incomingMessageNameLabelInsets
}
open override func messageContainerMaxWidth(for message: MessageType) -> CGFloat {
let maxWidth = super.messageContainerMaxWidth(for: message)
let textInsets = contactLabelInsets(for: message)
return maxWidth - textInsets.horizontal
}
open override func messageContainerSize(for message: MessageType) -> CGSize {
let maxWidth = messageContainerMaxWidth(for: message)
var messageContainerSize: CGSize
let attributedText: NSAttributedString
switch message.kind {
case .contact(let item):
attributedText = NSAttributedString(string: item.displayName, attributes: [.font: contactLabelFont])
default:
fatalError("messageContainerSize received unhandled MessageDataType: \(message.kind)")
}
messageContainerSize = labelSize(for: attributedText, considering: maxWidth)
let messageInsets = contactLabelInsets(for: message)
messageContainerSize.width += messageInsets.horizontal
messageContainerSize.height += messageInsets.vertical
return messageContainerSize
}
open override func configure(attributes: UICollectionViewLayoutAttributes) {
super.configure(attributes: attributes)
guard let attributes = attributes as? MessagesCollectionViewLayoutAttributes else { return }
attributes.messageLabelFont = contactLabelFont
}
}
| 43.786667 | 112 | 0.740256 |
61ff0c2a4c7349d1887aa0607a5cc3579ee456c4 | 2,298 | // RUN: %target-swift-emit-silgen %s -verify
// REQUIRES: asserts
// TF-881: User-defined Swift derivative functions cannot capture local values.
// Captured local values become extra SIL function arguments, breaking the
// expected derivative function type logic.
//
// In the short term, we should diagnose these cases to prevent crashes.
// In the long term, we should investigate supporting these cases.
do {
let capturedValue: Int = 3
func original(_ x: Float) -> Float { x }
// expected-error @+1 {{attribute '@derivative' can only be used in a non-local scope}}
@derivative(of: original)
func vjp(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
// Reference a local variable.
// This causes the top-level SIL function @vjp to have extra arguments.
_ = capturedValue
return (x, { $0 })
}
}
// Original crasher:
// SIL verification failed: apply doesn't have right number of arguments for function: site.getNumArguments() == substConv.getNumSILArguments()
// Verifying instruction:
// %0 = argument of bb0 : $Float // user: %2
// // function_ref vjp #1 (_:) in
// %1 = function_ref @$s4main3vjpL_ySf5value_S2fc8pullbacktSfF : $@convention(thin) (Float, Int) -> (Float, @owned @callee_guaranteed (Float) -> Float) // user: %2
// -> %2 = apply %1(%0) : $@convention(thin) (Float, Int) -> (Float, @owned @callee_guaranteed (Float) -> Float) // user: %3
// return %2 : $(Float, @callee_guaranteed (Float) -> Float) // id: %3
// In function:
// // AD__$s4main8originalL_yS2fF__vjp_src_0_wrt_0
// sil hidden [always_inline] [ossa] @AD__$s4main8originalL_yS2fF__vjp_src_0_wrt_0 : $@convention(thin) (Float) -> (Float, @owned @callee_guaranteed (Float) -> Float) {
// // %0 // user: %2
// bb0(%0 : $Float):
// // function_ref vjp #1 (_:) in
// %1 = function_ref @$s4main3vjpL_ySf5value_S2fc8pullbacktSfF : $@convention(thin) (Float, Int) -> (Float, @owned @callee_guaranteed (Float) -> Float) // user: %2
// %2 = apply %1(%0) : $@convention(thin) (Float, Int) -> (Float, @owned @callee_guaranteed (Float) -> Float) // user: %3
// return %2 : $(Float, @callee_guaranteed (Float) -> Float) // id: %3
// } // end sil function 'AD__$s4main8originalL_yS2fF__vjp_src_0_wrt_0'
| 52.227273 | 168 | 0.655788 |
e699753f172fa38940d51ee22f8e7f089f4dd9ba | 1,643 | //
// LebonbienTests.swift
// LebonbienTests
//
// Created by nelson on 14/09/2021.
//
import XCTest
@testable import Lebonbien
class MainViewTests: XCTestCase {
let serverAPIClientMock = ServerAPIClientMock()
lazy var mainViewModel = MainViewModel(serverAPI: serverAPIClientMock)
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 testInit() throws {
XCTAssertEqual(mainViewModel.categories[0], serverAPIClientMock.mockedCategories[0])
XCTAssertEqual(mainViewModel.categories[1], serverAPIClientMock.mockedCategories[1])
XCTAssertEqual(mainViewModel.items[0], serverAPIClientMock.mockedItems[1])
XCTAssertEqual(mainViewModel.items[1], serverAPIClientMock.mockedItems[2])
XCTAssertEqual(mainViewModel.items[2], serverAPIClientMock.mockedItems[0])
}
func testGetItemsForCategory() throws {
// When
let items = mainViewModel.getItemsForCategory(category: mainViewModel.categories[0])
// Then
XCTAssertEqual(items[0].title, serverAPIClientMock.mockedItems[1].title)
XCTAssertEqual(items[1].title, serverAPIClientMock.mockedItems[0].title)
}
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.
}
}
}
| 32.86 | 111 | 0.707243 |
c1660e5ca63f56612bad6f6cdf193f54ca66bb4b | 928 | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// MapViewController.swift
// GoogleMapsSwiftUI
//
// Created by Chris Arriola on 2/5/21.
//
import GoogleMaps
import SwiftUI
import UIKit
class MapViewController: UIViewController {
let map = GMSMapView(frame: .zero)
var isAnimating: Bool = false
override func loadView() {
super.loadView()
self.view = map
}
}
| 25.777778 | 75 | 0.726293 |
e2dd6f272829fcab7f812d5654581a048c2d5b14 | 259 | //
// TsetTool.swift
// LeLeText
//
// Created by yc_htl on 2020/12/18.
//
import UIKit
open class TsetTool: NSObject {
public func sayHello() {
print("hello")
}
public func sayHelloSwift() {
print("helloSwift")
}
}
| 13.631579 | 37 | 0.571429 |
2f52a30f9809bfe64d0ff78bf286afa3487904a8 | 1,896 | //: Playground - noun: a place where people can play
import Cocoa
import SwiftUtilities
func hexdump <Target : OutputStreamType>(buffer: UnsafeBufferPointer <Void>, width: Int = 16, zeroBased: Bool = false, separator: String = "\n", terminator: String = "", inout stream: Target) {
let buffer = UnsafeBufferPointer <UInt8> (start: UnsafePointer <UInt8> (buffer.baseAddress), count: buffer.count)
for index in 0.stride(through: buffer.count, by: width) {
let address = zeroBased == false ? String(buffer.baseAddress + index) : try! UInt(index).encodeToString(base: 16, prefix: true, width: 16)
let chunk = buffer.subBuffer(index, count: min(width, buffer.length - index))
if chunk.count == 0 {
break
}
let hex = chunk.map() {
try! $0.encodeToString(base: 16, prefix: false, width: 2)
}.joinWithSeparator(" ")
let paddedHex = hex.stringByPaddingToLength(width * 3 - 1, withString: " ", startingAtIndex: 0)
let string = chunk.map() {
(c: UInt8) -> String in
let scalar = UnicodeScalar(c)
let character = Character(scalar)
if isprint(Int32(c)) != 0 {
return String(character)
}
else {
return "?"
}
}.joinWithSeparator("")
stream.write("\(address) \(paddedHex) \(string)")
stream.write(separator)
}
stream.write(terminator)
}
func hexdump(buffer: UnsafeBufferPointer <Void>, width: Int = 16, zeroBased: Bool = false) {
var string = ""
hexdump(buffer, width: width, zeroBased: zeroBased, stream: &string)
print(string)
}
let s = "The quick brown fox jumped over the lazy\n dog"
let d = s.dataUsingEncoding(NSUTF8StringEncoding)
let b: UnsafeBufferPointer <Void> = d!.toUnsafeBufferPointer()
hexdump(b, width: 20, zeroBased: true)
| 34.472727 | 193 | 0.621835 |
ef44b52ca1ab894289d28989152677ecd3552c0b | 26,386 | //
// MaterialShowcase.swift
// MaterialShowcase
//
// Created by Quang Nguyen on 5/4/17.
// Copyright © 2017 Aromajoin. All rights reserved.
//
import UIKit
@objc public protocol MaterialShowcaseDelegate: class {
@objc optional func showCaseWillDismiss(showcase: MaterialShowcase, didTapTarget:Bool)
@objc optional func showCaseDidDismiss(showcase: MaterialShowcase, didTapTarget:Bool)
}
open class MaterialShowcase: UIView {
@objc public enum BackgroundTypeStyle: Int {
case circle //default
case full//full screen
}
@objc public enum SkipButtonStyle: Int {
case image
case text
}
@objc public enum SkipButtonPosition: Int {
case topRight
case topLeft
case bottomLeft
case bottomRight
case belowInstruction
}
// MARK: Material design guideline constant
let BACKGROUND_PROMPT_ALPHA: CGFloat = 0.96
let TARGET_HOLDER_RADIUS: CGFloat = 44
let TEXT_CENTER_OFFSET: CGFloat = 44 + 20
let INSTRUCTIONS_CENTER_OFFSET: CGFloat = 20
let LABEL_MARGIN: CGFloat = 40
let TARGET_PADDING: CGFloat = 20
let SKIP_BUTTON_MARGIN: CGFloat = 16
let SKIP_BUTTON_CONTENT_INSET: CGFloat = 8
let SKIP_BUTTON_BORDER_WIDTH: CGFloat = 1
let SKIP_BUTTON_CORNER_RADIUS: CGFloat = 4
// Other default properties
let LABEL_DEFAULT_HEIGHT: CGFloat = 50
let BACKGROUND_DEFAULT_COLOR = UIColor.fromHex(hexString: "#2196F3")
let TARGET_HOLDER_COLOR = UIColor.white
// MARK: Animation properties
var ANI_COMEIN_DURATION: TimeInterval = 0.5 // second
var ANI_GOOUT_DURATION: TimeInterval = 0.5 // second
var ANI_TARGET_HOLDER_SCALE: CGFloat = 2.2
let ANI_RIPPLE_COLOR = UIColor.white
let ANI_RIPPLE_ALPHA: CGFloat = 0.5
let ANI_RIPPLE_SCALE: CGFloat = 1.6
var offsetThreshold: CGFloat = 88
// MARK: Private view properties
var closeButton : UIButton!
var containerView: UIView!
var targetView: UIView!
var backgroundView: UIView!
var targetHolderView: UIView!
var hiddenTargetHolderView: UIView!
var targetRippleView: UIView!
var targetCopyView: UIView!
var instructionView: MaterialShowcaseInstructionView!
public var skipButton: (() -> Void)?
var onTapThrough: (() -> Void)?
// MARK: Public Properties
// Skip Button
private var skipButtonType: SkipButtonStyle = .image
public var skipButtonPosition: SkipButtonPosition = .topRight
public var skipButtonImage = "HintClose" {
didSet {
skipButtonType = .image
}
}
public var skipButtonTitle = "" {
didSet {
skipButtonType = .text
}
}
// Background
@objc public var backgroundAlpha: CGFloat = 1.0
@objc public var backgroundPromptColor: UIColor!
@objc public var backgroundPromptColorAlpha: CGFloat = 0.0
@objc public var backgroundViewType: BackgroundTypeStyle = .circle
@objc public var backgroundRadius: CGFloat = -1.0 // If the value is negative, calculate the radius automatically
// Tap zone settings
// - false: recognize tap from all displayed showcase.
// - true: recognize tap for targetView area only.
@objc public var isTapRecognizerForTargetView: Bool = false
// Target
@objc public var shouldSetTintColor: Bool = true
@objc public var targetTintColor: UIColor!
@objc public var targetHolderRadius: CGFloat = 0.0
@objc public var targetHolderColor: UIColor!
// Text
@objc public var primaryText: String!
@objc public var secondaryText: String!
@objc public var primaryTextColor: UIColor!
@objc public var secondaryTextColor: UIColor!
@objc public var primaryTextSize: CGFloat = 0.0
@objc public var secondaryTextSize: CGFloat = 0.0
@objc public var primaryTextFont: UIFont?
@objc public var secondaryTextFont: UIFont?
@objc public var primaryTextAlignment: NSTextAlignment = .left
@objc public var secondaryTextAlignment: NSTextAlignment = .left
// Animation
@objc public var aniComeInDuration: TimeInterval = 0.0
@objc public var aniGoOutDuration: TimeInterval = 0.0
@objc public var aniRippleScale: CGFloat = 0.0
@objc public var aniRippleColor: UIColor!
@objc public var aniRippleAlpha: CGFloat = 0.0
// Delegate
@objc public weak var delegate: MaterialShowcaseDelegate?
public init() {
// Create frame
let frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
super.init(frame: frame)
configure()
}
// No supported initilization method
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - Public APIs
extension MaterialShowcase {
/// Sets a general UIView as target
@objc public func setTargetView(view: UIView) {
targetView = view
if let label = targetView as? UILabel {
targetTintColor = label.textColor
backgroundPromptColor = label.textColor
} else if let button = targetView as? UIButton {
let tintColor = button.titleColor(for: .normal)
targetTintColor = tintColor
backgroundPromptColor = tintColor
} else {
targetTintColor = targetView.tintColor
backgroundPromptColor = targetView.tintColor
}
}
/// Sets a UIBarButtonItem as target
@objc public func setTargetView(button: UIButton, tapThrough: Bool = false) {
targetView = button
let tintColor = button.titleColor(for: .normal)
targetTintColor = tintColor
backgroundPromptColor = tintColor
if tapThrough {
onTapThrough = { button.sendActions(for: .touchUpInside) }
}
}
/// Sets a UIBarButtonItem as target
@objc public func setTargetView(barButtonItem: UIBarButtonItem, tapThrough: Bool = false) {
if let view = (barButtonItem.value(forKey: "view") as? UIView)?.subviews.first {
targetView = view
if tapThrough {
onTapThrough = { _ = barButtonItem.target?.perform(barButtonItem.action, with: nil) }
}
}
}
/// Sets a UITabBar Item as target
@objc public func setTargetView(tabBar: UITabBar, itemIndex: Int, tapThrough: Bool = false) {
let tabBarItems = orderedTabBarItemViews(of: tabBar)
if itemIndex < tabBarItems.count {
targetView = tabBarItems[itemIndex]
targetTintColor = tabBar.tintColor
backgroundPromptColor = tabBar.tintColor
if tapThrough {
onTapThrough = { tabBar.selectedItem = tabBar.items?[itemIndex] }
}
} else {
print ("The tab bar item index is out of range")
}
}
/// Sets a UITableViewCell as target
@objc public func setTargetView(tableView: UITableView, section: Int, row: Int) {
let indexPath = IndexPath(row: row, section: section)
targetView = tableView.cellForRow(at: indexPath)?.contentView
// for table viewcell, we do not need target holder (circle view)
// therefore, set its radius = 0
targetHolderRadius = 0
}
/// Sets a UICollectionViewCell as target
@objc public func setTargetView(collectionView: UICollectionView, section: Int, item: Int) {
let indexPath = IndexPath(item: item, section: section)
targetView = collectionView.cellForItem(at: indexPath)
// for table viewcell, we do not need target holder (circle view)
// therefore, set its radius = 0
targetHolderRadius = 0
}
@objc func dismissTutorialButtonDidTouch() {
skipButton?()
}
/// Shows it over current screen after completing setup process
@objc public func show(animated: Bool = true,hasShadow: Bool = true, hasSkipButton: Bool = false, completion handler: (()-> Void)?) {
initViews()
alpha = 0.0
containerView.addSubview(self)
layoutIfNeeded()
let scale = TARGET_HOLDER_RADIUS / (backgroundView.frame.width / 2)
let center = backgroundView.center
backgroundView.transform = CGAffineTransform(scaleX: scale, y: scale) // Initial set to support animation
backgroundView.center = targetHolderView.center
if hasSkipButton {
closeButton = UIButton()
if skipButtonType == .text, !skipButtonTitle.isEmpty {
closeButton.setTitle(skipButtonTitle, for: .normal)
closeButton.setBorderColor(primaryTextColor, width: SKIP_BUTTON_BORDER_WIDTH)
closeButton.setCornerRadius(SKIP_BUTTON_CORNER_RADIUS)
closeButton.contentEdgeInsets = UIEdgeInsets(top: SKIP_BUTTON_CONTENT_INSET, left: SKIP_BUTTON_CONTENT_INSET, bottom: SKIP_BUTTON_CONTENT_INSET, right: SKIP_BUTTON_CONTENT_INSET)
} else {
closeButton.setImage(UIImage(named: skipButtonImage), for: .normal)
}
addSubview(closeButton)
closeButton.addTarget(self, action: #selector(dismissTutorialButtonDidTouch), for: .touchUpInside)
if #available(iOS 9.0, *) {
let margins = layoutMarginsGuide
closeButton.translatesAutoresizingMaskIntoConstraints = false
switch skipButtonPosition {
case .topRight:
setupCloseButtonForEdges()
closeButton.topAnchor.constraint(equalTo: margins.topAnchor, constant: 0).isActive = true
closeButton.rightAnchor.constraint(equalTo: margins.rightAnchor, constant: -8).isActive = true
case .topLeft:
setupCloseButtonForEdges()
closeButton.topAnchor.constraint(equalTo: margins.topAnchor, constant: 0).isActive = true
closeButton.leftAnchor.constraint(equalTo: margins.leftAnchor, constant: 8).isActive = true
case .bottomLeft:
closeButton.bottomAnchor.constraint(equalTo: margins.bottomAnchor, constant: 0).isActive = true
closeButton.leftAnchor.constraint(equalTo: margins.leftAnchor, constant: 8).isActive = true
case .bottomRight:
closeButton.bottomAnchor.constraint(equalTo: margins.bottomAnchor, constant: 0).isActive = true
closeButton.rightAnchor.constraint(equalTo: margins.rightAnchor, constant: -8).isActive = true
case .belowInstruction:
closeButton.topAnchor.constraint(equalTo: instructionView.bottomAnchor, constant: SKIP_BUTTON_MARGIN).isActive = true
closeButton.leftAnchor.constraint(equalTo: instructionView.leftAnchor, constant: SKIP_BUTTON_MARGIN).isActive = true
}
} else {
// Fallback on earlier versions
}
}
if hasShadow {
backgroundView.layer.shadowColor = UIColor.black.cgColor
backgroundView.layer.shadowRadius = 5.0
backgroundView.layer.shadowOpacity = 0.5
backgroundView.layer.shadowOffset = .zero
backgroundView.clipsToBounds = false
}
if animated {
UIView.animate(withDuration: aniComeInDuration, animations: {
self.targetHolderView.transform = CGAffineTransform(scaleX: 1, y: 1)
self.backgroundView.transform = CGAffineTransform(scaleX: 1, y: 1)
self.backgroundView.center = center
self.alpha = self.backgroundAlpha
}, completion: { _ in
self.startAnimations()
})
} else {
alpha = backgroundAlpha
}
// Handler user's action after showing.
handler?()
}
}
// MARK: - Utility API
extension MaterialShowcase {
/// Returns the current showcases displayed on screen.
/// It will return null if no showcase exists.
public static func presentedShowcases() -> [MaterialShowcase]? {
guard let window = UIApplication.shared.keyWindow else {
return nil
}
return window.subviews.filter({ (view) -> Bool in
return view is MaterialShowcase
}) as? [MaterialShowcase]
}
}
// MARK: - Setup views internally
extension MaterialShowcase {
/// Initializes default view properties
func configure() {
backgroundColor = UIColor.clear
guard let window = UIApplication.shared.keyWindow else {
return
}
containerView = window
setDefaultProperties()
}
func setDefaultProperties() {
// Background
backgroundPromptColor = BACKGROUND_DEFAULT_COLOR
backgroundPromptColorAlpha = BACKGROUND_PROMPT_ALPHA
// Target view
targetTintColor = BACKGROUND_DEFAULT_COLOR
targetHolderColor = TARGET_HOLDER_COLOR
targetHolderRadius = TARGET_HOLDER_RADIUS
// Text
primaryText = MaterialShowcaseInstructionView.PRIMARY_DEFAULT_TEXT
secondaryText = MaterialShowcaseInstructionView.SECONDARY_DEFAULT_TEXT
primaryTextColor = MaterialShowcaseInstructionView.PRIMARY_TEXT_COLOR
secondaryTextColor = MaterialShowcaseInstructionView.SECONDARY_TEXT_COLOR
primaryTextSize = MaterialShowcaseInstructionView.PRIMARY_TEXT_SIZE
secondaryTextSize = MaterialShowcaseInstructionView.SECONDARY_TEXT_SIZE
// Animation
aniComeInDuration = ANI_COMEIN_DURATION
aniGoOutDuration = ANI_GOOUT_DURATION
aniRippleAlpha = ANI_RIPPLE_ALPHA
aniRippleColor = ANI_RIPPLE_COLOR
aniRippleScale = ANI_RIPPLE_SCALE
}
func startAnimations() {
let options: UIView.KeyframeAnimationOptions = [.curveEaseInOut, .repeat]
UIView.animateKeyframes(withDuration: 1, delay: 0, options: options, animations: {
UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.5, animations: {
self.targetRippleView.alpha = self.ANI_RIPPLE_ALPHA
self.targetHolderView.transform = CGAffineTransform(scaleX: 1.1, y: 1.1)
self.targetRippleView.transform = CGAffineTransform(scaleX: 1.1, y: 1.1)
})
UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.5, animations: {
self.targetHolderView.transform = CGAffineTransform.identity
self.targetRippleView.alpha = 0
self.targetRippleView.transform = CGAffineTransform(scaleX: self.aniRippleScale, y: self.aniRippleScale)
})
}, completion: nil)
}
func initViews() {
let center = calculateCenter(at: targetView, to: containerView)
addTargetRipple(at: center)
addTargetHolder(at: center)
// if color is not UIColor.clear, then add the target snapshot
if targetHolderColor != .clear {
addTarget(at: center)
}
addBackground()
addInstructionView(at: center)
instructionView.layoutIfNeeded()
// Disable subview interaction to let users click to general view only
subviews.forEach({$0.isUserInteractionEnabled = false})
if isTapRecognizerForTargetView {
//Add gesture recognizer for targetCopyView
hiddenTargetHolderView.addGestureRecognizer(tapGestureRecoganizer())
hiddenTargetHolderView.isUserInteractionEnabled = true
} else {
// Add gesture recognizer for both container and its subview
addGestureRecognizer(tapGestureRecoganizer())
hiddenTargetHolderView.addGestureRecognizer(tapGestureRecoganizer())
hiddenTargetHolderView.isUserInteractionEnabled = true
}
}
/// Add background which is a big circle
private func addBackground() {
switch self.backgroundViewType {
case .circle:
let radius: CGFloat
if backgroundRadius < 0 {
radius = getDefaultBackgroundRadius()
} else {
radius = backgroundRadius
}
let center = targetRippleView.center
backgroundView = UIView(frame: CGRect(x: 0, y: 0, width: radius * 2,height: radius * 2))
backgroundView.center = center
backgroundView.asCircle()
case .full:
backgroundView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width,height: UIScreen.main.bounds.height))
}
backgroundView.backgroundColor = backgroundPromptColor.withAlphaComponent(backgroundPromptColorAlpha)
insertSubview(backgroundView, belowSubview: targetRippleView)
addBackgroundMask(with: targetHolderRadius, in: backgroundView)
}
private func getDefaultBackgroundRadius() -> CGFloat {
var radius: CGFloat = 0.0
if UIDevice.current.userInterfaceIdiom == .pad {
radius = 300.0
} else {
radius = 400.0
}
return radius
}
private func addBackgroundMask(with radius: CGFloat, in view: UIView) {
let center = backgroundViewType == .circle ? view.bounds.center : targetRippleView.center
let mutablePath = CGMutablePath()
mutablePath.addRect(view.bounds)
mutablePath.addArc(center: center, radius: radius, startAngle: 0.0, endAngle: 2 * .pi, clockwise: false)
let mask = CAShapeLayer()
mask.path = mutablePath
mask.fillRule = CAShapeLayerFillRule.evenOdd
view.layer.mask = mask
}
/// A background view which add ripple animation when showing target view
private func addTargetRipple(at center: CGPoint) {
targetRippleView = UIView(frame: CGRect(x: 0, y: 0, width: targetHolderRadius * 2,height: targetHolderRadius * 2))
targetRippleView.center = center
targetRippleView.backgroundColor = aniRippleColor
targetRippleView.alpha = 0.0 //set it invisible
targetRippleView.asCircle()
addSubview(targetRippleView)
}
/// A circle-shape background view of target view
private func addTargetHolder(at center: CGPoint) {
hiddenTargetHolderView = UIView()
hiddenTargetHolderView.backgroundColor = .clear
targetHolderView = UIView(frame: CGRect(x: 0, y: 0, width: targetHolderRadius * 2,height: targetHolderRadius * 2))
targetHolderView.center = center
targetHolderView.backgroundColor = targetHolderColor
targetHolderView.asCircle()
hiddenTargetHolderView.frame = targetHolderView.frame
targetHolderView.transform = CGAffineTransform(scaleX: 1/ANI_TARGET_HOLDER_SCALE, y: 1/ANI_TARGET_HOLDER_SCALE) // Initial set to support animation
addSubview(hiddenTargetHolderView)
addSubview(targetHolderView)
}
/// Create a copy view of target view
/// It helps us not to affect the original target view
private func addTarget(at center: CGPoint) {
targetCopyView = targetView.snapshotView(afterScreenUpdates: true)
if shouldSetTintColor {
targetCopyView.setTintColor(targetTintColor, recursive: true)
if let button = targetView as? UIButton,
let buttonCopy = targetCopyView as? UIButton {
buttonCopy.setImage(button.image(for: .normal)?.withRenderingMode(.alwaysTemplate), for: .normal)
buttonCopy.setTitleColor(targetTintColor, for: .normal)
buttonCopy.isEnabled = true
} else if let imageView = targetView as? UIImageView,
let imageViewCopy = targetCopyView as? UIImageView {
imageViewCopy.image = imageView.image?.withRenderingMode(.alwaysTemplate)
} else if let imageViewCopy = targetCopyView.subviews.first as? UIImageView,
let labelCopy = targetCopyView.subviews.last as? UILabel,
let imageView = targetView.subviews.first as? UIImageView {
imageViewCopy.image = imageView.image?.withRenderingMode(.alwaysTemplate)
labelCopy.textColor = targetTintColor
} else if let label = targetCopyView as? UILabel {
label.textColor = targetTintColor
}
}
let width = targetCopyView.frame.width
let height = targetCopyView.frame.height
targetCopyView.frame = CGRect(x: 0, y: 0, width: width, height: height)
targetCopyView.center = center
targetCopyView.translatesAutoresizingMaskIntoConstraints = true
addSubview(targetCopyView)
}
/// Configures and adds primary label view
private func addInstructionView(at center: CGPoint) {
instructionView = MaterialShowcaseInstructionView()
instructionView.primaryTextAlignment = primaryTextAlignment
instructionView.primaryTextFont = primaryTextFont
instructionView.primaryTextSize = primaryTextSize
instructionView.primaryTextColor = primaryTextColor
instructionView.primaryText = primaryText
instructionView.secondaryTextAlignment = secondaryTextAlignment
instructionView.secondaryTextFont = secondaryTextFont
instructionView.secondaryTextSize = secondaryTextSize
instructionView.secondaryTextColor = secondaryTextColor
instructionView.secondaryText = secondaryText
// Calculate x position
var xPosition = LABEL_MARGIN
// Calculate y position
var yPosition: CGFloat!
// Calculate instructionView width
var width : CGFloat
if UIDevice.current.userInterfaceIdiom == .pad {
backgroundView.addSubview(instructionView)
} else {
addSubview(instructionView)
}
instructionView.layoutIfNeeded()
if UIDevice.current.userInterfaceIdiom == .pad {
width = backgroundView.frame.width - 2 * xPosition
if backgroundView.frame.origin.x < 0 {
xPosition = abs(backgroundView.frame.origin.x) + xPosition
} else if (backgroundView.frame.origin.x + backgroundView.frame.size.width >
UIScreen.main.bounds.width) {
xPosition = 2 * LABEL_MARGIN
width = backgroundView.frame.size.width - (backgroundView.frame.maxX - UIScreen.main.bounds.width) - xPosition - LABEL_MARGIN
}
if xPosition + width > backgroundView.frame.size.width {
width = backgroundView.frame.size.width - xPosition - (LABEL_MARGIN * 2)
}
//Updates horizontal parameters
instructionView.frame = CGRect(x: xPosition,
y: instructionView.frame.origin.y,
width: width,
height: 0)
instructionView.layoutIfNeeded()
if getTargetPosition(target: targetView, container: containerView) == .above {
yPosition = (backgroundView.frame.size.height/2) + TEXT_CENTER_OFFSET
} else {
yPosition = (backgroundView.frame.size.height/2) - TEXT_CENTER_OFFSET - instructionView.frame.height
}
} else {
width = containerView.frame.size.width - (xPosition*2)
if backgroundView.frame.center.x - targetHolderRadius < 0 {
width = width - abs(backgroundView.frame.origin.x)
} else if (backgroundView.frame.center.x + targetHolderRadius >
UIScreen.main.bounds.width) {
width = width - abs(backgroundView.frame.origin.x)
xPosition = xPosition + abs(backgroundView.frame.origin.x)
}
//Updates horizontal parameters
instructionView.frame = CGRect(x: xPosition,
y: instructionView.frame.origin.y,
width: width ,
height: 0)
instructionView.layoutIfNeeded()
if getTargetPosition(target: targetView, container: containerView) == .above {
yPosition = center.y + TARGET_PADDING + (targetView.bounds.height / 2 > targetHolderRadius ? targetView.bounds.height / 2 : targetHolderRadius)
} else {
yPosition = center.y - TEXT_CENTER_OFFSET - max(instructionView.frame.height,LABEL_DEFAULT_HEIGHT * 2)
}
}
instructionView.frame = CGRect(x: xPosition,
y: yPosition,
width: width ,
height: 0)
}
/// Handles user's tap
private func tapGestureRecoganizer() -> UIGestureRecognizer {
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(MaterialShowcase.tapGestureSelector))
tapGesture.numberOfTapsRequired = 1
tapGesture.numberOfTouchesRequired = 1
return tapGesture
}
@objc private func tapGestureSelector(tapGesture:UITapGestureRecognizer) {
completeShowcase(didTapTarget: tapGesture.view === hiddenTargetHolderView)
}
/// Default action when dimissing showcase
/// Notifies delegate, removes views, and handles out-going animation
@objc public func completeShowcase(animated: Bool = true, didTapTarget: Bool = false) {
if delegate != nil && delegate?.showCaseDidDismiss != nil {
delegate?.showCaseWillDismiss?(showcase: self, didTapTarget: didTapTarget)
}
if animated {
targetRippleView.removeFromSuperview()
UIView.animateKeyframes(withDuration: aniGoOutDuration, delay: 0, options: [.calculationModeLinear], animations: {
UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 3/5, animations: {
self.targetHolderView.transform = CGAffineTransform(scaleX: 0.4, y: 0.4)
self.backgroundView.transform = CGAffineTransform(scaleX: 1.3, y: 1.3)
self.backgroundView.alpha = 0
})
UIView.addKeyframe(withRelativeStartTime: 3/5, relativeDuration: 2/5, animations: {
self.alpha = 0
})
}, completion: { (success) in
// Recycle subviews
self.recycleSubviews()
// Remove it from current screen
self.removeFromSuperview()
})
} else {
// Recycle subviews
self.recycleSubviews()
// Remove it from current screen
self.removeFromSuperview()
}
if delegate != nil && delegate?.showCaseDidDismiss != nil {
delegate?.showCaseDidDismiss?(showcase: self, didTapTarget: didTapTarget)
}
if didTapTarget {
onTapThrough?()
}
}
private func recycleSubviews() {
subviews.forEach({$0.removeFromSuperview()})
}
/// Set constaint width, height for `closeButton`
private func setupCloseButtonForEdges() {
closeButton.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 0.13).isActive = true
closeButton.heightAnchor.constraint(equalTo: closeButton.widthAnchor, multiplier: 1.0/1.0).isActive = true
}
}
// MARK: - Private helper methods
extension MaterialShowcase {
/// Defines the position of target view
/// which helps to place texts at suitable positions
enum TargetPosition {
case above // at upper screen part
case below // at lower screen part
}
/// Detects the position of target view relative to its container
func getTargetPosition(target: UIView, container: UIView) -> TargetPosition {
let center = calculateCenter(at: targetView, to: container)
if center.y < container.frame.height / 2 {
return .above
} else {
return .below
}
}
// Calculates the center point based on targetview
func calculateCenter(at targetView: UIView, to containerView: UIView) -> CGPoint {
let targetRect = targetView.convert(targetView.bounds , to: containerView)
return targetRect.center
}
// Gets all UIView from TabBarItem.
func orderedTabBarItemViews(of tabBar: UITabBar) -> [UIView] {
let interactionViews = tabBar.subviews.filter({$0.isUserInteractionEnabled})
return interactionViews.sorted(by: {$0.frame.minX < $1.frame.minX})
}
}
| 37.694286 | 186 | 0.702607 |
6231db3e2bb8ee82ccef4c50d32b154ffbc4e554 | 1,704 | // Telegrammer - Telegram Bot Swift SDK.
// This file is autogenerated by API/generate_wrappers.rb script.
import HTTP
public extension Bot {
/// Parameters container struct for `setStickerPositionInSet` method
public struct SetStickerPositionInSetParams: JSONEncodable {
/// File identifier of the sticker
var sticker: String
/// New sticker position in the set, zero-based
var position: Int
/// Custom keys for coding/decoding `SetStickerPositionInSetParams` struct
enum CodingKeys: String, CodingKey {
case sticker = "sticker"
case position = "position"
}
public init(sticker: String, position: Int) {
self.sticker = sticker
self.position = position
}
}
/**
Use this method to move a sticker in a set created by the bot to a specific position . Returns True on success.
SeeAlso Telegram Bot API Reference:
[SetStickerPositionInSetParams](https://core.telegram.org/bots/api#setstickerpositioninset)
- Parameters:
- params: Parameters container, see `SetStickerPositionInSetParams` struct
- Throws: Throws on errors
- Returns: Future of `Bool` type
*/
@discardableResult
public func setStickerPositionInSet(params: SetStickerPositionInSetParams) throws -> Future<Bool> {
let body = try httpBody(for: params)
let headers = httpHeaders(for: params)
let response: Future<TelegramContainer<Bool>>
response = try client.respond(endpoint: "setStickerPositionInSet", body: body, headers: headers)
return response.flatMap(to: Bool.self) { try self.wrap($0) }
}
}
| 34.08 | 116 | 0.670188 |
908aa5257448558b7d4e588957c819eb72f2a08b | 14,070 | //
// GEOSwiftTests.swift
//
// Created by Andrea Cremaschi on 21/05/15.
// Copyright (c) 2015 andreacremaschi. All rights reserved.
//
import Foundation
import XCTest
import GEOSwift
// swiftlint:disable:next type_body_length
class GEOSwiftTests: XCTestCase {
var waypoint: Waypoint!
var lineString: LineString!
var linearRing: LinearRing!
var polygon: Polygon!
var geometryCollection: GeometryCollection<Geometry>!
var multiPoint: MultiPoint<Waypoint>!
override func setUp() {
super.setUp()
waypoint = Waypoint(latitude: 9, longitude: 45)
lineString = LineString(points: [Coordinate(x: 3, y: 4),
Coordinate(x: 10, y: 50),
Coordinate(x: 20, y: 25)])
linearRing = LinearRing(points: [Coordinate(x: 35, y: 10),
Coordinate(x: 45, y: 45),
Coordinate(x: 15, y: 40),
Coordinate(x: 10, y: 20),
Coordinate(x: 35, y: 10)])
polygon = Polygon(shell: linearRing,
holes: [LinearRing(points: [Coordinate(x: 20, y: 30),
Coordinate(x: 35, y: 35),
Coordinate(x: 30, y: 20),
Coordinate(x: 20, y: 30)])!])
geometryCollection = GeometryCollection(geometries: [waypoint, lineString])
multiPoint = MultiPoint(points: [waypoint])
}
override func tearDown() {
multiPoint = nil
geometryCollection = nil
polygon = nil
linearRing = nil
lineString = nil
waypoint = nil
super.tearDown()
}
func testInitPointFromWKT() {
guard let testWaypoint = Waypoint(WKT: "POINT(45 9)") else {
XCTFail("WKT parse failed")
return
}
XCTAssertEqual(testWaypoint, waypoint)
XCTAssertEqual(testWaypoint.coordinate.x, 45)
XCTAssertEqual(testWaypoint.coordinate.y, 9)
}
func testInitLinestringFromWKT() {
guard let testLineString = LineString(WKT: "LINESTRING(3 4,10 50,20 25)") else {
XCTFail("WKT parse failed")
return
}
XCTAssertEqual(testLineString, lineString)
}
func testInitLinearRingFromWKT() {
guard let testLinearRing = LinearRing(WKT: "LINEARRING(35 10,45 45,15 40,10 20,35 10)") else {
XCTFail("WKT parse failed")
return
}
XCTAssertEqual(testLinearRing, linearRing)
}
func testInitPolygonFromWKT() {
let WKT = "POLYGON((35 10, 45 45, 15 40, 10 20, 35 10),(20 30, 35 35, 30 20, 20 30))"
guard let testPolygon = Polygon(WKT: WKT) else {
XCTFail("WKT parse failed")
return
}
XCTAssertEqual(testPolygon, polygon)
}
func testInitGeometryCollectionFromWKT() {
let WKT = "GEOMETRYCOLLECTION(POINT(45 9),LINESTRING(3 4,10 50,20 25))"
guard let testGeometryCollection = GeometryCollection(WKT: WKT) else {
XCTFail("WKT parse failed")
return
}
XCTAssertEqual(testGeometryCollection, geometryCollection)
}
func testInitMultiPointFromWKT() {
guard let testMultiPoint = MultiPoint(WKT: "MULTIPOINT(45 9)") else {
XCTFail("WKT parse failed")
return
}
XCTAssertEqual(testMultiPoint, multiPoint)
}
func testCreatePointFromWKT() {
guard let testWaypoint = Geometry.create("POINT(45 9)") as? Waypoint else {
XCTFail("WKT parse failed (expected to receive a POINT)")
return
}
XCTAssertEqual(testWaypoint, waypoint)
XCTAssertEqual(testWaypoint.coordinate.x, 45)
XCTAssertEqual(testWaypoint.coordinate.y, 9)
}
func testCreateLinestringFromWKT() {
guard let testLineString = Geometry.create("LINESTRING(3 4,10 50,20 25)") as? LineString else {
XCTFail("WKT parse failed (expected to receive a LINESTRING)")
return
}
XCTAssertEqual(testLineString, lineString)
}
func testCreateLinearRingFromWKT() {
guard let testLinearRing = Geometry.create("LINEARRING(35 10,45 45,15 40,10 20,35 10)") as? LinearRing else {
XCTFail("WKT parse failed (expected to receive a LINEARRING)")
return
}
XCTAssertEqual(testLinearRing, linearRing)
}
func testCreatePolygonFromWKT() {
let WKT = "POLYGON((35 10, 45 45, 15 40, 10 20, 35 10),(20 30, 35 35, 30 20, 20 30))"
guard let testPolygon = Geometry.create(WKT) as? Polygon else {
XCTFail("WKT parse failed (expected to receive a POLYGON)")
return
}
XCTAssertEqual(testPolygon, polygon)
}
func testCreateGeometryCollectionFromWKT() {
let WKT = "GEOMETRYCOLLECTION(POINT(45 9),LINESTRING(3 4,10 50,20 25))"
guard let testGeometryCollection = Geometry.create(WKT) as? GeometryCollection else {
XCTFail("WKT parse failed (expected to receive a GEOMETRYCOLLECTION)")
return
}
XCTAssertEqual(testGeometryCollection, geometryCollection)
}
func testCreateMultiPointFromWKT() {
guard let testMultiPoint = Geometry.create("MULTIPOINT(45 9)") as? MultiPoint else {
XCTFail("WKT parse failed (expected to receive a MULTIPOINT)")
return
}
XCTAssertEqual(testMultiPoint, multiPoint)
}
func testCreateWKBFromPolygon() {
guard let wkb = polygon.WKB else {
XCTFail("Failed to generate WKB")
return
}
XCTAssertFalse(wkb.isEmpty)
guard let generatedPolygon = Geometry.create(wkb, size: wkb.count) else {
XCTFail("Failed to create Polygon from generated WKB")
return
}
XCTAssertEqual(polygon, generatedPolygon, "Polygon round-tripped via WKB is not equal")
}
// Test case for Issue #37
// https://github.com/GEOSwift/GEOSwift/issues/37
func testCreatePolygonFromLinearRing() {
let lr = LinearRing(points: [Coordinate(x: -10, y: 10),
Coordinate(x: 10, y: 10),
Coordinate(x: 10, y: -10),
Coordinate(x: -10, y: -10),
Coordinate(x: -10, y: 10)])
XCTAssertNotNil(lr, "Failed to create LinearRing")
if let lr = lr {
let polygon1 = Polygon(shell: lr, holes: nil)
XCTAssertNotNil(polygon1, "Failed to create polygon from LinearRing")
}
}
func testCreateEnvelopeFromCoordinates() {
let env = Envelope(p1: Coordinate(x: -10, y: 10), p2: Coordinate(x: 10, y: -10))
XCTAssertNotNil(env, "Failed to create Envelope")
let geom = env!.envelope()
XCTAssertEqual(env, geom)
}
func testCreateEnvelopeByExpanding() {
let env = Envelope(p1: Coordinate(x: -10, y: 10), p2: Coordinate(x: 10, y: -10))
XCTAssertNotNil(env, "Failed to create Envelope")
let newEnv = Envelope.byExpanding(env!, toInclude: Waypoint(latitude: 11, longitude: 11)!)
XCTAssertNotNil(env, "Failed to expand Envelope")
XCTAssertEqual(newEnv!, Envelope(p1: Coordinate(x: -10, y: 11), p2: Coordinate(x: 11, y: -10))!)
}
func testCreateEnvelopeFromWaypoint() {
let wp = Waypoint(latitude: -10, longitude: 10)!
let env = wp.envelope()
XCTAssertNotNil(env, "Failed to create Envelope")
// Equatable on constructed Envelopes doesn’t seem to be working properly
XCTAssertEqual(env!.topLeft, wp.coordinate)
XCTAssertEqual(env!.bottomRight, wp.coordinate)
}
func testCreateEnvelopeFromMultipoint() {
let mp = MultiPoint(points: [Waypoint(latitude: -10, longitude: 10)!, Waypoint(latitude: 10, longitude: -10)!])!
let env = mp.envelope()
XCTAssertNotNil(env, "Failed to create Envelope")
XCTAssertEqual(env!, Envelope(p1: Coordinate(x: -10, y: 10), p2: Coordinate(x: 10, y: -10)))
}
func testCreateEnvelopeFromLineString() {
let ls = LineString(points: [Coordinate(x: 10, y: -10), Coordinate(x: -10, y: 10)])!
let env = ls.envelope()
XCTAssertNotNil(env, "Failed to create Envelope")
XCTAssertEqual(env!, Envelope(p1: Coordinate(x: -10, y: 10), p2: Coordinate(x: 10, y: -10)))
}
func testGeoJSON() {
let bundle = Bundle(for: GEOSwiftTests.self)
if let geojsons = bundle.urls(forResourcesWithExtension: "geojson", subdirectory: nil) {
for geoJSONURL in geojsons {
if case .some(.some) = try? Features.fromGeoJSON(geoJSONURL) {
XCTAssert(true, "GeoJSON correctly parsed")
} else {
XCTAssert(false, "Can't extract geometry from GeoJSON: \(geoJSONURL.lastPathComponent)")
}
}
}
}
func testNearestPoints() {
let polygonWKT = "POLYGON((35 10, 45 45, 15 40, 10 20, 35 10),(20 30, 35 35, 30 20, 20 30))"
let point = Geometry.create("POINT(45 9)") as! Waypoint
let polygon = Geometry.create(polygonWKT) as! Polygon
let arrNearestPoints = point.nearestPoints(polygon)
XCTAssertNotNil(arrNearestPoints, "Failed to get nearestPoints array between the two geometries")
XCTAssertEqual(arrNearestPoints.count, 2, "Number of expected points is 2")
XCTAssertEqual(arrNearestPoints[0].x, point.nearestPoint(polygon).x)
XCTAssertEqual(arrNearestPoints[0].y, point.nearestPoint(polygon).y)
}
func testArea() {
let point = Geometry.create("POINT(45 9)") as! Waypoint
XCTAssertEqual(0, point.area())
let lr = LinearRing(points: [Coordinate(x: 0, y: 0),
Coordinate(x: 1, y: 0),
Coordinate(x: 1, y: 1),
Coordinate(x: 0, y: 1),
Coordinate(x: 0, y: 0)])!
let polygon = Polygon(shell: lr, holes: nil)!
XCTAssertEqual(1, polygon.area())
}
// swiftlint:disable:next function_body_length
func testIsEqual() {
let lhs = LineString(points: [Coordinate(x: 0, y: 0),
Coordinate(x: 1, y: 0),
Coordinate(x: 0, y: 1),
Coordinate(x: 0, y: 0)])!
// Same instance
var rhs: Geometry = lhs
XCTAssertTrue(lhs == rhs)
XCTAssertTrue(rhs == lhs)
XCTAssertTrue(lhs.isEqual(rhs))
XCTAssertTrue(rhs.isEqual(lhs))
// Distinct, but equivalent instance
rhs = LineString(points: [Coordinate(x: 0, y: 0),
Coordinate(x: 1, y: 0),
Coordinate(x: 0, y: 1),
Coordinate(x: 0, y: 0)])!
XCTAssertTrue(lhs == rhs)
XCTAssertTrue(rhs == lhs)
XCTAssertTrue(lhs.isEqual(rhs))
XCTAssertTrue(rhs.isEqual(lhs))
// Non-equivalent instance
rhs = LineString(points: [Coordinate(x: 0, y: 0),
Coordinate(x: 2, y: 0),
Coordinate(x: 0, y: 2),
Coordinate(x: 0, y: 0)])!
XCTAssertFalse(lhs == rhs)
XCTAssertFalse(rhs == lhs)
XCTAssertFalse(lhs.isEqual(rhs))
XCTAssertFalse(rhs.isEqual(lhs))
// Other type of object
XCTAssertFalse(lhs.isEqual(NSObject()))
// Equivalent subclass
rhs = LinearRing(points: [Coordinate(x: 0, y: 0),
Coordinate(x: 1, y: 0),
Coordinate(x: 0, y: 1),
Coordinate(x: 0, y: 0)])!
XCTAssertTrue(lhs == rhs)
XCTAssertTrue(rhs == lhs)
XCTAssertTrue(lhs.isEqual(rhs))
XCTAssertTrue(rhs.isEqual(lhs))
// Non-equivalent subclass
rhs = LinearRing(points: [Coordinate(x: 0, y: 0),
Coordinate(x: 2, y: 0),
Coordinate(x: 0, y: 2),
Coordinate(x: 0, y: 0)])!
XCTAssertFalse(lhs == rhs)
XCTAssertFalse(rhs == lhs)
XCTAssertFalse(lhs.isEqual(rhs))
XCTAssertFalse(rhs.isEqual(lhs))
}
// Test case for Issue #85
// https://github.com/GEOSwift/GEOSwift/issues/85
func testStorageManagement() {
func getLineStringFromCollection() -> LineString? {
// Define the GeometryCollection in a separate scope, so that it is
// deallocated before the returned LineString is used.
let geometryCollection = GeometryCollection(geometries: [lineString])
return geometryCollection?.geometries[0] as? LineString
}
guard let element = getLineStringFromCollection() else {
XCTFail("Element creation failed")
return
}
// Since the LineString depends on the underlying storage of the
// GeometryCollection we need to ensure that the storage persists even
// when the collection itself is destroyed. The following equality check
// would crash when accessing the LineString storage.
XCTAssertEqual(element, lineString)
}
func testCoordinatesCollection() {
let collection = lineString.points
XCTAssertEqual(collection.startIndex, 0)
XCTAssertEqual(collection.endIndex, collection.count)
XCTAssertEqual(collection.index(after: 0), 1)
XCTAssertEqual(collection.index(after: 1), 2)
XCTAssertEqual(collection.index(after: 2), 3)
}
}
| 39.411765 | 120 | 0.571286 |
9b813da782f373856f09f18fcb0f75f19640734f | 892 | #!/usr/bin/env xcrun swift
import Foundation
// Module Based on Mass - roundDown(mass/3) - 2
func parseInput() -> [String]? {
let file = CommandLine.arguments[1]
guard let data = try? Data(contentsOf: URL(fileURLWithPath: file)) else { return nil }
let input = String(data: data, encoding: .utf8)!
return input.split { $0.isNewline }.map{ String($0) }
}
func calculateFuel(for mass: Double) -> Int {
Int((mass/3).rounded(.down) - 2)
}
func calculateFuelUntilZero(for mass: Double) -> Double {
var fuel = mass
var sum = 0.0
while fuel >= 0 {
fuel = (fuel/3).rounded(.down) - 2
if fuel <= 0 { break }
sum += fuel
}
return sum
}
guard let lines = parseInput() else { fatalError() }
let c = lines.map{ calculateFuelUntilZero(for: Double($0) as! Double) }.reduce(0, +)
print(c)
// print(calculateFuelUntilZero(for: 100756))
| 24.108108 | 90 | 0.631166 |
efc637e5452bac8d20f10090e13fdd6e9823dc12 | 2,826 | //
// ShareMainViewModel.swift
// MooyahoApp
//
// Created sudo.park on 2021/10/28.
// Copyright © 2021 ParkHyunsoo. All rights reserved.
//
import Foundation
import RxSwift
import RxRelay
import Domain
import CommonPresenting
// MARK: - ShareMainViewModel
public protocol ShareMainViewModel: AnyObject {
// interactor
func showEditScene(_ url: String)
// presenter
var finishSharing: Observable<Void> { get }
}
// MARK: - ShareMainViewModelImple
public final class ShareMainViewModelImple: ShareMainViewModel {
private let authUsecase: AuthUsecase
private let readItemSyncUsecase: ReadItemSyncUsecase
private let router: ShareMainRouting
private weak var listener: ShareMainSceneListenable?
public init(authUsecase: AuthUsecase,
readItemSyncUsecase: ReadItemSyncUsecase,
router: ShareMainRouting,
listener: ShareMainSceneListenable?) {
self.authUsecase = authUsecase
self.readItemSyncUsecase = readItemSyncUsecase
self.router = router
self.listener = listener
}
deinit {
LeakDetector.instance.expectDeallocate(object: self.router)
LeakDetector.instance.expectDeallocate(object: self.subjects)
}
fileprivate final class Subjects {
let sharingFinished = PublishSubject<Void>()
}
private let subjects = Subjects()
private let disposeBag = DisposeBag()
}
// MARK: - ShareMainViewModelImple Interactor
extension ShareMainViewModelImple {
public func showEditScene(_ url: String) {
let authPrepared: (Auth?) -> Void = { [weak self] _ in
self?.router.showEditScene(url)
}
let prepareAuthWithoutError = self.authUsecase.loadLastSignInAccountInfo()
.map { $0.auth }
.mapAsOptional()
.catchAndReturn(nil)
prepareAuthWithoutError
.observe(on: MainScheduler.instance)
.subscribe(onSuccess: authPrepared)
.disposed(by: self.disposeBag)
}
}
extension ShareMainViewModelImple: EditLinkItemSceneListenable {
public func editReadLink(didEdit item: ReadLink) {
let parentCollectionID = item.parentID ?? ReadCollection.rootID
let newIDs = self.readItemSyncUsecase.reloadNeedCollectionIDs
.filter { $0 != parentCollectionID }
+ [parentCollectionID]
self.readItemSyncUsecase.reloadNeedCollectionIDs = newIDs
}
public func editReadLinkDidDismissed() {
self.subjects.sharingFinished.onNext()
}
}
// MARK: - ShareMainViewModelImple Presenter
extension ShareMainViewModelImple {
public var finishSharing: Observable<Void> {
return self.subjects.sharingFinished.asObservable()
}
}
| 25.926606 | 82 | 0.676575 |
dbff6cae312b7b6840cc8cb75b46e66ba26cbd73 | 2,089 | //
// ViewController.swift
// XCAssertNoLeakSample
//
// Created by tarunon on 2019/03/13.
// Copyright © 2019 tarunon. All rights reserved.
//
import UIKit
class ViewControllerNoLeak: UIViewController {
let button = UIButton()
let slider = UISlider()
override func viewDidLoad() {
super.viewDidLoad()
button.addTarget(self, action: #selector(tapped(_:)), for: .touchUpInside)
slider.addTarget(self, action: #selector(changed(_:)), for: .valueChanged)
}
@objc func tapped(_ sender: UIButton) {
}
@objc func changed(_ sender: UISlider) {
}
}
class ViewControllerLeaked: UIViewController {
lazy var observer = NotificationCenter.default.addObserver(forName: UIApplication.didBecomeActiveNotification, object: nil, queue: nil, using: leakedMethod(_:))
init() {
super.init(nibName: nil, bundle: nil)
_ = observer
}
deinit {
NotificationCenter.default.removeObserver(observer)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func leakedMethod(_ notification: Notification) {
}
}
class ViewControllerLeakedViewDidAppear: UIViewController {
class Button: UIButton {
var handler: (() -> ())? {
didSet {
addTarget(self, action: #selector(handle(_:)), for: .touchUpInside)
}
}
@objc func handle(_ sender: Any) {
handler?()
}
}
class Logic {
var updateTitle: ((String) -> ())?
func buttonTitle(_ f: @escaping (String) -> ()) {
self.updateTitle = f
}
func tapped() {
}
}
lazy var button = Button()
lazy var logic = Logic()
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
view.addSubview(button)
logic.buttonTitle { [button] in button.setTitle($0, for: .normal) }
button.handler = logic.tapped
}
}
| 24.576471 | 164 | 0.587841 |
0e38652544af5a7d5ad7df653235a790474f8186 | 5,439 | // Copyright (c) 2015 Felix Jendrusch. All rights reserved.
import Quick
import Nimble
import Marionette
class BasicAnimationSpec: QuickSpec {
override func spec() {
describe("a range operator") {
context("with two operands") {
it("should create a basic animation with from and to values") {
let animation: BasicAnimation<Int> = 0...1
expect(animation.fromValue).to(equal(0))
expect(animation.toValue).to(equal(1))
expect(animation.byValue).to(beNil())
}
}
context("with a single right-hands side operand") {
it("should create a basic animation with a to value") {
let animation: BasicAnimation<Int> = ...1
expect(animation.fromValue).to(beNil())
expect(animation.toValue).to(equal(1))
expect(animation.byValue).to(beNil())
}
}
context("with a single left-hands side operand") {
it("should create a basic animation with a from value") {
let animation: BasicAnimation<Int> = 0...
expect(animation.fromValue).to(equal(0))
expect(animation.toValue).to(beNil())
expect(animation.byValue).to(beNil())
}
}
}
describe("a timing function operator") {
context("with a value operand") {
it("should create a basic animation with a to values as well as a timing function") {
let animation: BasicAnimation<Int> = 1 ~ .EaseInEaseOut
expect(animation.fromValue).to(beNil())
expect(animation.toValue).to(equal(1))
expect(animation.byValue).to(beNil())
expect(animation.timingFunction).to(equal(MediaTimingFunction.EaseInEaseOut))
}
}
context("with a range operand") {
it("should create a basic animation with from and to values as well as a timing function") {
let animation: BasicAnimation<Int> = Range(start: 0, end: 2) ~ .EaseInEaseOut
expect(animation.fromValue).to(equal(0))
expect(animation.toValue).to(equal(1))
expect(animation.byValue).to(beNil())
expect(animation.timingFunction).to(equal(MediaTimingFunction.EaseInEaseOut))
}
}
context("with a closed interval operand") {
it("should create a basic animation with from and to values as well as a timing function") {
let animation: BasicAnimation<Int> = ClosedInterval(0, 1) ~ .EaseInEaseOut
expect(animation.fromValue).to(equal(0))
expect(animation.toValue).to(equal(1))
expect(animation.byValue).to(beNil())
expect(animation.timingFunction).to(equal(MediaTimingFunction.EaseInEaseOut))
}
}
context("with a half open interval operand") {
it("should create a basic animation with from and to values as well as a timing function") {
let animation: BasicAnimation<Int> = HalfOpenInterval(0, 2) ~ .EaseInEaseOut
expect(animation.fromValue).to(equal(0))
expect(animation.toValue).to(equal(1))
expect(animation.byValue).to(beNil())
expect(animation.timingFunction).to(equal(MediaTimingFunction.EaseInEaseOut))
}
}
}
describe("a property animation operator") {
context("with a value operand") {
it("should create a basic animation with a to value") {
var animation: CABasicAnimation!
animate(CALayer()) { layer in
animation = layer.opacity ~= 1
}
expect(animation.keyPath).to(equal("opacity"))
expect(animation.fromValue).to(beNil())
expect(animation.toValue as? Float).to(equal(1))
expect(animation.byValue).to(beNil())
}
}
// Cannot test a property animation operator with a range operand
// because no property conforms to protocol ForwardIndexType.
xcontext("with a range operand") {}
context("with a closed interval operand") {
it("should create a basic animation with from and to values") {
var animation: CABasicAnimation!
animate(CALayer()) { layer in
animation = layer.opacity ~= ClosedInterval(0, 1)
}
expect(animation.keyPath).to(equal("opacity"))
expect(animation.fromValue as? Float).to(equal(0))
expect(animation.toValue as? Float).to(equal(1))
expect(animation.byValue).to(beNil())
}
}
// Cannot test a property animation operator with a range operand
// because no property conforms to protocol ForwardIndexType.
xcontext("with a half open interval operand") {}
}
}
}
| 44.581967 | 108 | 0.534106 |
1e5dd1ae3c31df31990dc58e19dabec05c42b175 | 790 | //
// ConfigArgumentParserError.swift
// ConfigArgumentParser
//
// Created by Braden Scothern on 8/29/20.
// Copyright © 2020-2021 Braden Scothern. All rights reserved.
//
/// The errors that can be raised while attempting to run a command with a config file.
@usableFromInline
enum ConfigArgumentParserError: Error, CustomStringConvertible {
case noConfigFilesInAutoPaths([String])
case unableToFindConfig(file: String)
@usableFromInline
var description: String {
switch self {
case let .noConfigFilesInAutoPaths(paths):
return "There were no config files found in the searched paths: \(paths.joined(separator: ", "))"
case let .unableToFindConfig(file):
return "Unable to find config file: \(file)"
}
}
}
| 31.6 | 109 | 0.693671 |
ab8840ec12e8d58171f5c2fb8b8e2cb87482a14f | 19,028 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
// swift-tools-version:4.0
//
// swift-tools-version:4.0
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if canImport(Network)
import XCTest
import NIO
import NIOTransportServices
import Foundation
import Network
func assertNoThrowWithValue<T>(_ body: @autoclosure () throws -> T, defaultValue: T? = nil, message: String? = nil, file: StaticString = #file, line: UInt = #line) throws -> T {
do {
return try body()
} catch {
XCTFail("\(message.map { $0 + ": " } ?? "")unexpected error \(error) thrown", file: file, line: line)
if let defaultValue = defaultValue {
return defaultValue
} else {
throw error
}
}
}
final class EchoHandler: ChannelInboundHandler {
typealias InboundIn = Any
typealias OutboundOut = Any
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
context.write(data, promise: nil)
}
func channelReadComplete(context: ChannelHandlerContext) {
context.flush()
}
}
final class ReadExpecter: ChannelInboundHandler {
typealias InboundIn = ByteBuffer
struct DidNotReadError: Error { }
private var readPromise: EventLoopPromise<Void>?
private var cumulationBuffer: ByteBuffer?
private let expectedRead: ByteBuffer
var readFuture: EventLoopFuture<Void>? {
return self.readPromise?.futureResult
}
init(expecting: ByteBuffer) {
self.expectedRead = expecting
}
func handlerAdded(context: ChannelHandlerContext) {
self.readPromise = context.eventLoop.makePromise()
}
func handlerRemoved(context: ChannelHandlerContext) {
if let promise = self.readPromise {
promise.fail(DidNotReadError())
}
}
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
var bytes = self.unwrapInboundIn(data)
if self.cumulationBuffer == nil {
self.cumulationBuffer = bytes
} else {
self.cumulationBuffer!.writeBuffer(&bytes)
}
self.maybeFulfillPromise()
}
private func maybeFulfillPromise() {
if let promise = self.readPromise, self.cumulationBuffer! == self.expectedRead {
promise.succeed(())
self.readPromise = nil
}
}
}
final class CloseOnActiveHandler: ChannelInboundHandler {
typealias InboundIn = Never
typealias OutboundOut = Never
func channelActive(context: ChannelHandlerContext) {
context.close(promise: nil)
}
}
final class HalfCloseHandler: ChannelInboundHandler {
typealias InboundIn = Never
typealias InboundOut = Never
private let halfClosedPromise: EventLoopPromise<Void>
private var alreadyHalfClosed = false
private var closed = false
init(_ halfClosedPromise: EventLoopPromise<Void>) {
self.halfClosedPromise = halfClosedPromise
}
func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
switch event {
case ChannelEvent.inputClosed:
XCTAssertFalse(self.alreadyHalfClosed)
XCTAssertFalse(self.closed)
self.alreadyHalfClosed = true
self.halfClosedPromise.succeed(())
context.close(mode: .output, promise: nil)
default:
break
}
context.fireUserInboundEventTriggered(event)
}
func channelInactive(context: ChannelHandlerContext) {
XCTAssertTrue(self.alreadyHalfClosed)
XCTAssertFalse(self.closed)
self.closed = true
}
}
final class FailOnHalfCloseHandler: ChannelInboundHandler {
typealias InboundIn = Any
func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
switch event {
case ChannelEvent.inputClosed:
XCTFail("Must not receive half-closure")
context.close(promise: nil)
default:
break
}
context.fireUserInboundEventTriggered(event)
}
}
extension Channel {
/// Expect that the given bytes will be received.
func expectRead(_ bytes: ByteBuffer) -> EventLoopFuture<Void> {
let expecter = ReadExpecter(expecting: bytes)
return self.pipeline.addHandler(expecter).flatMap {
return expecter.readFuture!
}
}
}
extension ByteBufferAllocator {
func bufferFor(string: String) -> ByteBuffer {
var buffer = self.buffer(capacity: string.count)
buffer.writeString(string)
return buffer
}
}
@available(OSX 10.14, iOS 12.0, tvOS 12.0, *)
class NIOTSEndToEndTests: XCTestCase {
private var group: NIOTSEventLoopGroup!
override func setUp() {
self.group = NIOTSEventLoopGroup()
}
override func tearDown() {
XCTAssertNoThrow(try self.group.syncShutdownGracefully())
}
func testSimpleListener() throws {
let listener = try NIOTSListenerBootstrap(group: self.group)
.childChannelInitializer { channel in channel.pipeline.addHandler(EchoHandler())}
.bind(host: "localhost", port: 0).wait()
defer {
XCTAssertNoThrow(try listener.close().wait())
}
let connection = try NIOTSConnectionBootstrap(group: self.group).connect(to: listener.localAddress!).wait()
defer {
XCTAssertNoThrow(try connection.close().wait())
}
let buffer = connection.allocator.bufferFor(string: "hello, world!")
let completeFuture = connection.expectRead(buffer)
connection.writeAndFlush(buffer, promise: nil)
XCTAssertNoThrow(try completeFuture.wait())
}
func testMultipleConnectionsOneListener() throws {
let listener = try NIOTSListenerBootstrap(group: self.group)
.childChannelInitializer { channel in channel.pipeline.addHandler(EchoHandler())}
.bind(host: "localhost", port: 0).wait()
defer {
XCTAssertNoThrow(try listener.close().wait())
}
let bootstrap = NIOTSConnectionBootstrap(group: self.group)
let completeFutures: [EventLoopFuture<Void>] = (0..<10).map { _ in
return bootstrap.connect(to: listener.localAddress!).flatMap { channel -> EventLoopFuture<Void> in
let buffer = channel.allocator.bufferFor(string: "hello, world!")
let completeFuture = channel.expectRead(buffer)
channel.writeAndFlush(buffer, promise: nil)
return completeFuture
}
}
let allDoneFuture = EventLoopFuture<Void>.andAllComplete(completeFutures, on: self.group.next())
XCTAssertNoThrow(try allDoneFuture.wait())
}
func testBasicConnectionTeardown() throws {
let listener = try NIOTSListenerBootstrap(group: self.group)
.childChannelInitializer { channel in channel.pipeline.addHandler(CloseOnActiveHandler())}
.bind(host: "localhost", port: 0).wait()
defer {
XCTAssertNoThrow(try listener.close().wait())
}
let bootstrap = NIOTSConnectionBootstrap(group: self.group)
let closeFutures: [EventLoopFuture<Void>] = (0..<10).map { _ in
bootstrap.connect(to: listener.localAddress!).flatMap { channel in
channel.closeFuture
}
}
let allClosed = EventLoopFuture<Void>.andAllComplete(closeFutures, on: self.group.next())
XCTAssertNoThrow(try allClosed.wait())
}
func testCloseFromClientSide() throws {
// This test is a little bit dicey, but we need 20 futures in this list.
let closeFutureSyncQueue = DispatchQueue(label: "closeFutureSyncQueue")
let closeFutureGroup = DispatchGroup()
var closeFutures: [EventLoopFuture<Void>] = []
let listener = try NIOTSListenerBootstrap(group: self.group)
.childChannelInitializer { channel in
closeFutureSyncQueue.sync {
closeFutures.append(channel.closeFuture)
}
closeFutureGroup.leave()
return channel.eventLoop.makeSucceededFuture(())
}
.bind(host: "localhost", port: 0).wait()
defer {
XCTAssertNoThrow(try listener.close().wait())
}
let bootstrap = NIOTSConnectionBootstrap(group: self.group).channelInitializer { channel in
channel.pipeline.addHandler(CloseOnActiveHandler())
}
for _ in (0..<10) {
// Each connection attempt needs to enter the group twice: each end will leave it once
// for us.
closeFutureGroup.enter(); closeFutureGroup.enter()
bootstrap.connect(to: listener.localAddress!).whenSuccess { channel in
closeFutureSyncQueue.sync {
closeFutures.append(channel.closeFuture)
}
closeFutureGroup.leave()
}
}
closeFutureGroup.wait()
let allClosed = closeFutureSyncQueue.sync {
return EventLoopFuture<Void>.andAllComplete(closeFutures, on: self.group.next())
}
XCTAssertNoThrow(try allClosed.wait())
}
func testAgreeOnRemoteLocalAddresses() throws {
let serverSideConnectionPromise: EventLoopPromise<Channel> = self.group.next().makePromise()
let listener = try NIOTSListenerBootstrap(group: self.group)
.childChannelInitializer { channel in
serverSideConnectionPromise.succeed(channel)
return channel.pipeline.addHandler(EchoHandler())
}
.bind(host: "localhost", port: 0).wait()
defer {
XCTAssertNoThrow(try listener.close().wait())
}
let connection = try NIOTSConnectionBootstrap(group: self.group).connect(to: listener.localAddress!).wait()
defer {
XCTAssertNoThrow(try connection.close().wait())
}
let serverSideConnection = try serverSideConnectionPromise.futureResult.wait()
XCTAssertEqual(connection.remoteAddress, listener.localAddress)
XCTAssertEqual(connection.remoteAddress, serverSideConnection.localAddress)
XCTAssertEqual(connection.localAddress, serverSideConnection.remoteAddress)
}
func testHalfClosureSupported() throws {
let halfClosedPromise: EventLoopPromise<Void> = self.group.next().makePromise()
let listener = try NIOTSListenerBootstrap(group: self.group)
.childChannelInitializer { channel in
channel.pipeline.addHandler(EchoHandler()).flatMap { _ in
channel.pipeline.addHandler(HalfCloseHandler(halfClosedPromise))
}
}
.childChannelOption(ChannelOptions.allowRemoteHalfClosure, value: true)
.bind(host: "localhost", port: 0).wait()
defer {
XCTAssertNoThrow(try listener.close().wait())
}
let connection = try NIOTSConnectionBootstrap(group: self.group)
.channelOption(ChannelOptions.allowRemoteHalfClosure, value: true)
.connect(to: listener.localAddress!).wait()
// First check the channel is working.
let buffer = connection.allocator.bufferFor(string: "hello, world!")
let completeFuture = connection.expectRead(buffer)
connection.writeAndFlush(buffer, promise: nil)
XCTAssertNoThrow(try completeFuture.wait())
// Ok, now half-close. This should propagate to the remote peer, which should also
// close its end, leading to complete shutdown of the connection.
XCTAssertNoThrow(try connection.close(mode: .output).wait())
XCTAssertNoThrow(try halfClosedPromise.futureResult.wait())
XCTAssertNoThrow(try connection.closeFuture.wait())
}
func testDisabledHalfClosureCausesFullClosure() throws {
let listener = try NIOTSListenerBootstrap(group: self.group)
.childChannelInitializer { channel in
channel.pipeline.addHandler(EchoHandler()).flatMap { _ in
channel.pipeline.addHandler(FailOnHalfCloseHandler())
}
}
.bind(host: "localhost", port: 0).wait()
defer {
XCTAssertNoThrow(try listener.close().wait())
}
let connection = try NIOTSConnectionBootstrap(group: self.group)
.channelOption(ChannelOptions.allowRemoteHalfClosure, value: true)
.connect(to: listener.localAddress!).wait()
// First check the channel is working.
let buffer = connection.allocator.bufferFor(string: "hello, world!")
let completeFuture = connection.expectRead(buffer)
connection.writeAndFlush(buffer, promise: nil)
XCTAssertNoThrow(try completeFuture.wait())
// Ok, now half-close. This should propagate to the remote peer, which should also
// close its end, leading to complete shutdown of the connection.
XCTAssertNoThrow(try connection.close(mode: .output).wait())
XCTAssertNoThrow(try connection.closeFuture.wait())
}
func testHalfClosingTwiceFailsTheSecondTime() throws {
let listener = try NIOTSListenerBootstrap(group: self.group)
.childChannelOption(ChannelOptions.allowRemoteHalfClosure, value: true)
.bind(host: "localhost", port: 0).wait()
defer {
XCTAssertNoThrow(try listener.close().wait())
}
let connection = try NIOTSConnectionBootstrap(group: self.group)
.connect(to: listener.localAddress!).wait()
// Ok, now half-close. First one should be fine.
XCTAssertNoThrow(try connection.close(mode: .output).wait())
// Second one won't be.
do {
try connection.close(mode: .output).wait()
XCTFail("Did not throw")
} catch ChannelError.outputClosed {
// ok
} catch {
XCTFail("Threw unexpected error \(error)")
}
}
func testHalfClosingInboundSideIsRejected() throws {
let listener = try NIOTSListenerBootstrap(group: self.group)
.childChannelOption(ChannelOptions.allowRemoteHalfClosure, value: true)
.bind(host: "localhost", port: 0).wait()
defer {
XCTAssertNoThrow(try listener.close().wait())
}
let connection = try NIOTSConnectionBootstrap(group: self.group)
.channelOption(ChannelOptions.allowRemoteHalfClosure, value: true)
.connect(to: listener.localAddress!).wait()
// Ok, now try to half-close the input.
do {
try connection.close(mode: .input).wait()
XCTFail("Did not throw")
} catch ChannelError.operationUnsupported {
// ok
} catch {
XCTFail("Threw unexpected error \(error)")
}
}
func testBasicUnixSockets() throws {
// We don't use FileManager here because this code round-trips through sockaddr_un, and
// sockaddr_un cannot hold paths as long as the true temporary directories used by
// FileManager.
let udsPath = "/tmp/\(UUID().uuidString)_testBasicUnixSockets.sock"
let listener = try NIOTSListenerBootstrap(group: self.group)
.childChannelInitializer { channel in channel.pipeline.addHandler(EchoHandler())}
.bind(unixDomainSocketPath: udsPath).wait()
defer {
XCTAssertNoThrow(try listener.close().wait())
}
let connection = try NIOTSConnectionBootstrap(group: self.group)
.connect(unixDomainSocketPath: udsPath).wait()
defer {
XCTAssertNoThrow(try connection.close().wait())
}
XCTAssertEqual(listener.localAddress, connection.remoteAddress)
XCTAssertNil(connection.localAddress)
let buffer = connection.allocator.bufferFor(string: "hello, world!")
let completeFuture = connection.expectRead(buffer)
connection.writeAndFlush(buffer, promise: nil)
XCTAssertNoThrow(try completeFuture.wait())
}
func testFancyEndpointSupport() throws {
// This test validates that we can use NWEndpoints properly by doing something core NIO
// cannot: setting up and connecting to a Bonjour service. To avoid the risk of multiple
// users running this test on the same network at the same time and getting in each others
// way we use a UUID to distinguish the service.
let name = UUID().uuidString
let serviceEndpoint = NWEndpoint.service(name: name, type: "_niots._tcp", domain: "local", interface: nil)
let listener = try NIOTSListenerBootstrap(group: self.group)
.childChannelInitializer { channel in channel.pipeline.addHandler(EchoHandler())}
.bind(endpoint: serviceEndpoint).wait()
defer {
XCTAssertNoThrow(try listener.close().wait())
}
let connection = try NIOTSConnectionBootstrap(group: self.group)
.connectTimeout(.hours(1))
.connect(endpoint: serviceEndpoint).wait()
defer {
XCTAssertNoThrow(try connection.close().wait())
}
XCTAssertNotNil(connection.localAddress)
XCTAssertNotNil(connection.remoteAddress)
XCTAssertNil(listener.localAddress)
XCTAssertNil(listener.remoteAddress)
let buffer = connection.allocator.bufferFor(string: "hello, world!")
let completeFuture = connection.expectRead(buffer)
connection.writeAndFlush(buffer, promise: nil)
XCTAssertNoThrow(try completeFuture.wait())
}
func testBasicConnectionTimeout() throws {
let listener = try NIOTSListenerBootstrap(group: self.group)
.serverChannelOption(ChannelOptions.socket(SOL_SOCKET, SO_REUSEADDR), value: 0)
.serverChannelOption(ChannelOptions.socket(SOL_SOCKET, SO_REUSEPORT), value: 0)
.childChannelInitializer { channel in channel.pipeline.addHandler(CloseOnActiveHandler())}
.bind(host: "localhost", port: 0).wait()
let address = listener.localAddress!
// let's close the server socket, we disable SO_REUSEPORT/SO_REUSEADDR so that nobody can bind this for a
// while.
XCTAssertNoThrow(try listener.close().wait())
// this should now definitely time out.
XCTAssertThrowsError(try NIOTSConnectionBootstrap(group: self.group)
.connectTimeout(.milliseconds(10))
.connect(to: address)
.wait()) { error in
print(error)
}
}
}
#endif
| 37.236791 | 177 | 0.643998 |
ed77236d723f2dcbac7570a758110952df2d01b9 | 4,475 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
let kCFPropertyListOpenStepFormat = CFPropertyListFormat.openStepFormat
let kCFPropertyListXMLFormat_v1_0 = CFPropertyListFormat.xmlFormat_v1_0
let kCFPropertyListBinaryFormat_v1_0 = CFPropertyListFormat.binaryFormat_v1_0
extension PropertyListSerialization {
public struct MutabilityOptions : OptionSet {
public let rawValue : UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
public static let mutableContainers = MutabilityOptions(rawValue: 1)
public static let mutableContainersAndLeaves = MutabilityOptions(rawValue: 2)
}
public enum PropertyListFormat : UInt {
case openStep = 1
case xml = 100
case binary = 200
}
public typealias ReadOptions = MutabilityOptions
public typealias WriteOptions = Int
}
open class PropertyListSerialization : NSObject {
open class func propertyList(_ plist: Any, isValidFor format: PropertyListFormat) -> Bool {
let fmt = CFPropertyListFormat(rawValue: CFIndex(format.rawValue))!
let plistObj = __SwiftValue.store(plist)
return CFPropertyListIsValid(plistObj, fmt)
}
open class func data(fromPropertyList plist: Any, format: PropertyListFormat, options opt: WriteOptions) throws -> Data {
var error: Unmanaged<CFError>? = nil
let result = withUnsafeMutablePointer(to: &error) { (outErr: UnsafeMutablePointer<Unmanaged<CFError>?>) -> CFData? in
let fmt = CFPropertyListFormat(rawValue: CFIndex(format.rawValue))!
let options = CFOptionFlags(opt)
let plistObj = __SwiftValue.store(plist)
let d = CFPropertyListCreateData(kCFAllocatorSystemDefault, plistObj, fmt, options, outErr)
return d?.takeRetainedValue()
}
if let res = result {
return res._swiftObject
} else {
throw error!.takeRetainedValue()._nsObject
}
}
open class func propertyList(from data: Data, options opt: ReadOptions = [], format: UnsafeMutablePointer<PropertyListFormat>?) throws -> Any {
var fmt = kCFPropertyListBinaryFormat_v1_0
var error: Unmanaged<CFError>? = nil
let decoded = withUnsafeMutablePointer(to: &fmt) { (outFmt: UnsafeMutablePointer<CFPropertyListFormat>) -> NSObject? in
withUnsafeMutablePointer(to: &error) { (outErr: UnsafeMutablePointer<Unmanaged<CFError>?>) -> NSObject? in
return unsafeBitCast(CFPropertyListCreateWithData(kCFAllocatorSystemDefault, data._cfObject, CFOptionFlags(CFIndex(opt.rawValue)), outFmt, outErr), to: NSObject.self)
}
}
format?.pointee = PropertyListFormat(rawValue: UInt(fmt.rawValue))!
if let err = error {
throw err.takeUnretainedValue()._nsObject
} else {
return __SwiftValue.fetch(nonOptional: decoded!)
}
}
internal class func propertyList(with stream: CFReadStream, options opt: ReadOptions, format: UnsafeMutablePointer <PropertyListFormat>?) throws -> Any {
var fmt = kCFPropertyListBinaryFormat_v1_0
var error: Unmanaged<CFError>? = nil
let decoded = withUnsafeMutablePointer(to: &fmt) { (outFmt: UnsafeMutablePointer<CFPropertyListFormat>) -> NSObject? in
withUnsafeMutablePointer(to: &error) { (outErr: UnsafeMutablePointer<Unmanaged<CFError>?>) -> NSObject? in
return unsafeBitCast(CFPropertyListCreateWithStream(kCFAllocatorSystemDefault, stream, 0, CFOptionFlags(CFIndex(opt.rawValue)), outFmt, outErr), to: NSObject.self)
}
}
format?.pointee = PropertyListFormat(rawValue: UInt(fmt.rawValue))!
if let err = error {
throw err.takeUnretainedValue()._nsObject
} else {
return __SwiftValue.fetch(nonOptional: decoded!)
}
}
open class func propertyList(with stream: InputStream, options opt: ReadOptions = [], format: UnsafeMutablePointer<PropertyListFormat>?) throws -> Any {
return try propertyList(with: stream._stream, options: opt, format: format)
}
}
| 46.134021 | 182 | 0.695196 |
7a2f211a1ef28ceb34a897a092cc97cfca69b578 | 3,720 | //
// CatViewPresenter.swift
//
// Created by R. Fogash, V. Ahosta
// Copyright (c) 2017 Thinkmobiles
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import UIKit
protocol LoadCatPresenterProtocol: Presenter {
func load()
func cancel()
func updateUI()
func edit()
var loadCatInteractor: LocadCatInteractor! { get set }
}
class LoadCatPresenter: LoadCatPresenterProtocol, LoadCatInteractorOutput, EditCatPresenterDelegate {
//
// Internal state
//
weak var view: LoadCatViewProtocol!
var loadCatInteractor: LocadCatInteractor!
var wireframe: LoadCatViewWireframe!
//
// View state
//
var isLoading: Bool
var image: UIImage?
var imageTitle: String?
init() {
isLoading = false
image = nil
imageTitle = nil
}
func installView(_ view: View) {
self.view = view as! LoadCatViewProtocol
}
public func load() {
guard !isLoading else { return }
isLoading = true
image = nil
imageTitle = nil
updateUI()
loadCatInteractor.loadCat()
}
public func cancel() {
loadCatInteractor.cancelLoad()
}
public func updateUI() {
view.updateLoadingState(isLoading)
view.updateTitle(imageTitle)
view.updateImage(image)
}
func edit() {
wireframe.presentEditScene(withImage: image!, delegate: self)
}
//MARK: LoadCatInteractorOutput
func didLoadCatURL(_ catURL: NSURL?, success: Bool, cancelled: Bool) {
imageTitle = catURL?.absoluteString
isLoading = success
if !success {
if cancelled {
imageTitle = Constants.cancelledString
} else {
imageTitle = Constants.errorSrting
}
}
updateUI()
}
func didLoadCatImage(_ image: Data?, success: Bool, cancelled: Bool) {
isLoading = false
if success {
if let imageData = image {
self.image = UIImage(data: imageData)
}
} else {
if cancelled {
imageTitle = Constants.cancelledString
} else {
imageTitle = Constants.errorSrting
}
}
updateUI()
}
// MARK: EditCatPresenterDelegate
func finished() {
view.finishEditing()
}
}
// MARK: Constants
extension LoadCatPresenter {
enum Constants {
static let cancelledString = "Cancelled"
static let errorSrting = "Error"
}
}
| 26.571429 | 101 | 0.616398 |
4b2f09cb6f74307184ba387eaed431cdb612dec1 | 1,798 | //
// UIViewControllerExtensions.swift
// Photos
//
// Created by ZHOU DENGFENG on 5/8/17.
// Copyright © 2017 ZHOU DENGFENG DEREK. All rights reserved.
//
import UIKit
public enum AlertControllerStyle {
case alert
case actionSheetFromView(UIView)
case actionSheetFromBarButtonItem(UIBarButtonItem)
}
extension UIViewController {
public func alertController(title: String? = nil, message: String? = nil, actions: [UIAlertAction], style: UIAlertController.Style) -> UIAlertController {
let alert = UIAlertController(title: title, message: message, preferredStyle: style)
actions.forEach { alert.addAction($0) }
return alert
}
public func showAlert(title: String? = nil, message: String? = nil, actions: [UIAlertAction], style: AlertControllerStyle) {
switch style {
case .alert:
let alert = alertController(title: title, message: message, actions: actions, style: .alert)
present(alert, animated: true, completion: nil)
case .actionSheetFromView(let view):
let alert = alertController(title: title, message: message, actions: actions, style: .actionSheet)
if let popover = alert.popoverPresentationController {
popover.sourceView = view
popover.sourceRect = view.bounds
}
present(alert, animated: true, completion: nil)
case .actionSheetFromBarButtonItem(let barButtonItem):
let alert = alertController(title: title, message: message, actions: actions, style: .actionSheet)
if let popover = alert.popoverPresentationController {
popover.barButtonItem = barButtonItem
}
present(alert, animated: true, completion: nil)
}
}
}
| 39.955556 | 158 | 0.661846 |
fe67ce6cd89d06d01954fa3fb4634836f5362d3a | 3,588 | #if os(macOS)
import AppKit
#else
import UIKit
#endif
public protocol Titleable: AnyObject {
#if !os(macOS)
@discardableResult
func titleChangeTransition(_ value: UIView.AnimationOptions) -> Self
#endif
@discardableResult
func title(_ value: LocalizedString...) -> Self
@discardableResult
func title(_ value: [LocalizedString]) -> Self
@discardableResult
func title(_ value: AnyString...) -> Self
@discardableResult
func title(_ value: [AnyString]) -> Self
@discardableResult
func title<A: AnyString>(_ state: State<A>) -> Self
@discardableResult
func title(@AnyStringBuilder stateString: @escaping AnyStringBuilder.Handler) -> Self
}
protocol _Titleable: Titleable {
var _statedTitle: AnyStringBuilder.Handler? { get set }
#if !os(macOS)
var _titleChangeTransition: UIView.AnimationOptions? { get set }
#endif
func _setTitle(_ v: NSAttributedString?)
}
extension _Titleable {
func _changeTitle(to newValue: NSAttributedString) {
#if os(macOS)
_setTitle(newValue)
#else
guard let transition = _titleChangeTransition else {
_setTitle(newValue)
return
}
if let view = self as? _ViewTransitionable {
view._transition(0.25, transition) {
self._setTitle(newValue)
}
} else {
_setTitle(newValue)
}
#endif
}
}
extension Titleable {
@discardableResult
public func title(_ value: LocalizedString...) -> Self {
title(String(value))
}
@discardableResult
public func title(_ value: [LocalizedString]) -> Self {
title(String(value))
}
@discardableResult
public func title(_ value: AnyString...) -> Self {
title(value)
}
@discardableResult
public func title<A: AnyString>(_ state: State<A>) -> Self {
title(state.wrappedValue)
state.listen { [weak self] in
self?.title($0)
}
return self
}
}
@available(iOS 13.0, *)
extension Titleable {
#if !os(macOS)
@discardableResult
public func titleChangeTransition(_ value: UIView.AnimationOptions) -> Self {
(self as? _Titleable)?._titleChangeTransition = value
return self
}
#endif
@discardableResult
public func title(_ value: [AnyString]) -> Self {
guard let s = self as? _Titleable else { return self }
value.onUpdate { [weak s] in
s?._changeTitle(to: $0)
}
s._changeTitle(to: value.attributedString)
return self
}
@discardableResult
public func title(@AnyStringBuilder stateString: @escaping AnyStringBuilder.Handler) -> Self {
(self as? _Titleable)?._statedTitle = stateString
return title(stateString())
}
}
// for iOS lower than 13
extension _Titleable {
#if !os(macOS)
@discardableResult
public func titleChangeTransition(_ value: UIView.AnimationOptions) -> Self {
_titleChangeTransition = value
return self
}
#endif
@discardableResult
public func title(_ value: [AnyString]) -> Self {
value.onUpdate { [weak self] in
self?._changeTitle(to: $0)
}
_changeTitle(to: value.attributedString)
return self
}
@discardableResult
public func title(@AnyStringBuilder stateString: @escaping AnyStringBuilder.Handler) -> Self {
_statedTitle = stateString
return title(stateString())
}
}
| 25.81295 | 98 | 0.621516 |
d6e560fd8543c870cceffa70c2c139ce12963d1f | 504 | //
// AspectRatioTests.swift
// App
//
// Created by Alvin Choo on 24/5/17.
// Copyright © 2017 Pointwelve. All rights reserved.
//
@testable import Bitpal
import XCTest
class AspectRatioTests: XCTestCase {
func testAspectRatioWidth() {
let sample = AspectRatio(x: 3.0, y: 2.0)
XCTAssertTrue(sample.widthMultiplier == 2.0 / 3.0)
}
func testAspectRatioHeight() {
let sample = AspectRatio(x: 3.0, y: 2.0)
XCTAssertTrue(sample.heightMultiplier == 3.0 / 2.0)
}
}
| 20.16 | 57 | 0.654762 |
64b8c96be70922a664acf628e5d07f8c39a3089b | 585 | //
// Speech.swift
// Clock
//
// Created by 张润良 on 2017/5/6.
// Copyright © 2017年 Zhangrunliang. All rights reserved.
//
import Foundation
import Speech
class Speech {
let dateFormatter = DateFormatter()
let speechSynthesizer = AVSpeechSynthesizer()
let speechSynthesisVoice = AVSpeechSynthesisVoice(language: "zh_CN")
func speck(string: String) {
let speechUtterance = AVSpeechUtterance(string: string)
speechUtterance.voice = speechSynthesisVoice
speechUtterance.rate = 0.5
speechSynthesizer.speak(speechUtterance)
}
}
| 24.375 | 72 | 0.702564 |
f8676fa2d0dba83400bc49d62381268043626921 | 398 | //
// Copyright © 2021 DHSC. All rights reserved.
//
import Foundation
import Interface
import UIKit
struct RiskyVenueInformationInteractor: RiskyVenueInformationViewController.Interacting {
private var _goHomeTapped: () -> Void
init(goHomeTapped: @escaping () -> Void) {
_goHomeTapped = goHomeTapped
}
func goHomeTapped() {
_goHomeTapped()
}
}
| 18.952381 | 89 | 0.673367 |
084cfbda7f58ace9e98b8e1845b8586acc37629e | 3,448 | //
// BRAPIClientTests.swift
// breadwallet
//
// Created by Samuel Sutch on 12/7/16.
// Copyright © 2016-2019 Breadwinner AG. All rights reserved.
//
import XCTest
@testable import breadwallet
import WalletKit
private var authenticator: WalletAuthenticator { return keyStore as WalletAuthenticator }
private var client: BRAPIClient!
private var keyStore: KeyStore!
// This test will test against the live API at api.breadwallet.com
class BRAPIClientTests: XCTestCase {
override class func setUp() {
super.setUp()
clearKeychain()
keyStore = try! KeyStore.create()
_ = setupNewAccount(keyStore: keyStore) // each test will get its own account
client = BRAPIClient(authenticator: authenticator)
}
override class func tearDown() {
super.tearDown()
client = nil
clearKeychain()
keyStore.destroy()
}
func testPublicKeyEncoding() {
guard let pubKey1 = client.authKey?.encodeAsPublic.hexToData?.base58 else {
return XCTFail()
}
let b = pubKey1.base58DecodedData()
XCTAssertNotNil(b)
let b2 = b!.base58
XCTAssertEqual(pubKey1, b2) // sanity check on our base58 functions
let key = Key.createFromString(asPublic: client.authKey!.encodeAsPublic)
XCTAssertEqual(pubKey1, key?.encodeAsPublic.hexToData?.base58) // the key decoded from our encoded key is the same
}
func testHandshake() {
// test that we can get a token and access /me
let req = URLRequest(url: client.url("/me"))
let exp = expectation(description: "auth")
client.dataTaskWithRequest(req, authenticated: true, retryCount: 0) { (data, resp, err) in
XCTAssertEqual(resp?.statusCode, 200)
exp.fulfill()
}.resume()
waitForExpectations(timeout: 30, handler: nil)
}
func testBlockchainDBAuthentication() {
let baseUrl = "https://api.blockset.com"
let authClient = AuthenticationClient(baseURL: URL(string: baseUrl)!,
urlSession: URLSession.shared)
//let deviceId = UUID().uuidString
let exp = expectation(description: "auth")
authenticator.authenticateWithBlockchainDB(client: authClient) { result in
switch result {
case .success(let jwt):
XCTAssertFalse(jwt.isExpired)
let token = jwt.token
// test authenticated request
var req = URLRequest(url: URL(string: "\(baseUrl)/blockchains")!)
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
req.setValue("application/json", forHTTPHeaderField: "Accept")
req.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
URLSession.shared.dataTask(with: req) { (data, response, error) in
XCTAssertNil(error)
XCTAssertEqual((response as? HTTPURLResponse)?.statusCode ?? 0, 200)
print("response: \(data != nil ? String(data: data!, encoding: .utf8)! : "none")")
exp.fulfill()
}.resume()
case .failure(let error):
XCTFail("BDB authentication error: \(error)")
exp.fulfill()
}
}
waitForExpectations(timeout: 30, handler: nil)
}
}
| 37.89011 | 122 | 0.608759 |
8767f39a5786dcb1633b964b61c8d445e126fd4d | 10,562 | //
// EnvVarDecoder.swift
// SAuthNIOLib
//
// Created by Kyle Jessup on 2020-03-11.
//
import Foundation
public struct EnvDecoderError: Error, CustomStringConvertible {
public let description: String
init(description: String) {
self.description = description
}
init(missingKey key: String) {
self.description = "Missing required config key \(key)"
}
}
struct EnvKey: CodingKey{
let stringValue: String
let intValue: Int?
init?(stringValue: String) {
self.stringValue = stringValue
self.intValue = nil
}
init?(intValue: Int) {
self.stringValue = "\(intValue)"
self.intValue = intValue
}
}
public class EnvVarDecoder: Decoder {
public var codingPath: [CodingKey]
public var userInfo: [CodingUserInfoKey : Any]
static let env = ProcessInfo.processInfo.environment
static let envKeys = Set(env.keys)
public init(codingPath: [CodingKey] = [], userInfo: [CodingUserInfoKey : Any] = [:]) {
self.codingPath = codingPath
self.userInfo = userInfo
}
public func decode<C: Decodable>(_ type: C.Type) throws -> C {
return try C.init(from: self)
}
public func container<KKey>(keyedBy type: KKey.Type) throws -> KeyedDecodingContainer<KKey> where KKey : CodingKey {
return KeyedDecodingContainer(ObjectReader(codingPath: codingPath))
}
public func unkeyedContainer() throws -> UnkeyedDecodingContainer {
return ObjectArrayReader(codingPath: codingPath)
}
public func singleValueContainer() throws -> SingleValueDecodingContainer {
return ObjectPropertyReader(codingPath: codingPath)
}
}
fileprivate func joinKeys(codingPath: [CodingKey]) -> String {
return codingPath.map { $0.stringValue }.joined(separator: "_")
}
fileprivate func value(forKey: String) -> String? {
let value = EnvVarDecoder.env[forKey]
// print("k:v \(forKey):\(value)")
return value
}
fileprivate func tvalue(forKey: String) throws -> String {
guard let value = value(forKey: forKey) else {
throw EnvDecoderError(missingKey: forKey)
}
return value
}
class ObjectReader<K : CodingKey>: KeyedDecodingContainerProtocol {
typealias Key = K
let allKeys: [K] = []
let codingPath: [CodingKey]
init(codingPath: [CodingKey]) {
self.codingPath = codingPath
// print("codingPath \(codingPath.map { $0.stringValue })")
}
func contains(_ key: K) -> Bool {
var path = joinKeys(codingPath: codingPath + [key])
if nil != value(forKey: path) {
return true
}
path += "_"
return nil != EnvVarDecoder.env.keys.first(where: { $0.hasPrefix(path) })
}
func decodeNil(forKey key: K) throws -> Bool {
return !contains(key)
}
func decode(_ type: Bool.Type, forKey key: K) throws -> Bool {
return Bool(try tvalue(forKey: joinKeys(codingPath: codingPath + [key])) ) ?? false
}
func decode(_ type: String.Type, forKey key: K) throws -> String {
return try tvalue(forKey: joinKeys(codingPath: codingPath + [key]))
}
func decode(_ type: Double.Type, forKey key: K) throws -> Double {
return Double(try tvalue(forKey: joinKeys(codingPath: codingPath + [key])) ) ?? 0
}
func decode(_ type: Float.Type, forKey key: K) throws -> Float {
return Float(try tvalue(forKey: joinKeys(codingPath: codingPath + [key])) ) ?? 0
}
func decode(_ type: Int.Type, forKey key: K) throws -> Int {
return Int(try tvalue(forKey: joinKeys(codingPath: codingPath + [key])) ) ?? 0
}
func decode(_ type: Int8.Type, forKey key: K) throws -> Int8 {
return Int8(try tvalue(forKey: joinKeys(codingPath: codingPath + [key])) ) ?? 0
}
func decode(_ type: Int16.Type, forKey key: K) throws -> Int16 {
return Int16(try tvalue(forKey: joinKeys(codingPath: codingPath + [key])) ) ?? 0
}
func decode(_ type: Int32.Type, forKey key: K) throws -> Int32 {
return Int32(try tvalue(forKey: joinKeys(codingPath: codingPath + [key])) ) ?? 0
}
func decode(_ type: Int64.Type, forKey key: K) throws -> Int64 {
return Int64(try tvalue(forKey: joinKeys(codingPath: codingPath + [key])) ) ?? 0
}
func decode(_ type: UInt.Type, forKey key: K) throws -> UInt {
return UInt(try tvalue(forKey: joinKeys(codingPath: codingPath + [key])) ) ?? 0
}
func decode(_ type: UInt8.Type, forKey key: K) throws -> UInt8 {
return UInt8(try tvalue(forKey: joinKeys(codingPath: codingPath + [key])) ) ?? 0
}
func decode(_ type: UInt16.Type, forKey key: K) throws -> UInt16 {
return UInt16(try tvalue(forKey: joinKeys(codingPath: codingPath + [key])) ) ?? 0
}
func decode(_ type: UInt32.Type, forKey key: K) throws -> UInt32 {
return UInt32(try tvalue(forKey: joinKeys(codingPath: codingPath + [key])) ) ?? 0
}
func decode(_ type: UInt64.Type, forKey key: K) throws -> UInt64 {
return UInt64(try tvalue(forKey: joinKeys(codingPath: codingPath + [key])) ) ?? 0
}
func decode<T>(_ type: T.Type, forKey key: K) throws -> T where T : Decodable {
return try T.init(from: EnvVarDecoder(codingPath: codingPath + [key], userInfo: [:]))
}
func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: K) throws -> KeyedDecodingContainer<NestedKey> where NestedKey : CodingKey {
let newks: [NestedKey] = (codingPath + [key]).compactMap { NestedKey(stringValue: $0.stringValue) }
return KeyedDecodingContainer(ObjectReader<NestedKey>(codingPath: newks))
}
func nestedUnkeyedContainer(forKey key: K) throws -> UnkeyedDecodingContainer {
return ObjectArrayReader(codingPath: codingPath + [key])
}
func superDecoder() throws -> Decoder {
fatalError()
}
func superDecoder(forKey key: K) throws -> Decoder {
fatalError()
}
}
class ObjectArrayReader: UnkeyedDecodingContainer {
var count: Int? = 0
var isAtEnd: Bool { count! <= currentIndex }
var currentIndex: Int = 0
let codingPath: [CodingKey]
let ids: [(String, [String])]
// a_b_0_foo=1
// a_b_0_bar=2
// a_b_1_foo=3
// a_b_1_bar=4
//
// a_b_NAME2_foo=3
// a_b_NAME2_bar=4
init(codingPath: [CodingKey]) {
self.codingPath = codingPath
let pathStr = joinKeys(codingPath: codingPath) + "_"
let validKeys = EnvVarDecoder.envKeys.filter { $0.hasPrefix(pathStr) }.sorted()
var dict: [String:[String]] = [:]
for key in validKeys {
let splt = key.split(separator: "_").map(String.init)
guard splt.count > codingPath.count else {
continue
}
let n = splt[codingPath.count]
let exists = dict[n] ?? []
dict[n] = exists + [key]
}
ids = dict.map { $0 }.sorted(by: { $0.0 < $1.0 })
count = ids.count
// print("codingPath \(codingPath.map { $0.stringValue })")
// print("ids \(ids)")
}
func grp() -> (String, [String]) {
let grp = ids[currentIndex]
currentIndex += 1
return grp
}
func sgrpval() throws -> String {
return try tvalue(forKey: grp().1[0])
}
func decodeNil() throws -> Bool {
false
}
func decode(_ type: Bool.Type) throws -> Bool {
return Bool(try sgrpval() ) ?? false
}
func decode(_ type: String.Type) throws -> String {
return String(try sgrpval() )
}
func decode(_ type: Double.Type) throws -> Double {
return Double(try sgrpval() ) ?? 0
}
func decode(_ type: Float.Type) throws -> Float {
return Float(try sgrpval() ) ?? 0
}
func decode(_ type: Int.Type) throws -> Int {
return Int(try sgrpval() ) ?? 0
}
func decode(_ type: Int8.Type) throws -> Int8 {
return Int8(try sgrpval() ) ?? 0
}
func decode(_ type: Int16.Type) throws -> Int16 {
return Int16(try sgrpval() ) ?? 0
}
func decode(_ type: Int32.Type) throws -> Int32 {
return Int32(try sgrpval() ) ?? 0
}
func decode(_ type: Int64.Type) throws -> Int64 {
return Int64(try sgrpval() ) ?? 0
}
func decode(_ type: UInt.Type) throws -> UInt {
return UInt(try sgrpval() ) ?? 0
}
func decode(_ type: UInt8.Type) throws -> UInt8 {
return UInt8(try sgrpval() ) ?? 0
}
func decode(_ type: UInt16.Type) throws -> UInt16 {
return UInt16(try sgrpval() ) ?? 0
}
func decode(_ type: UInt32.Type) throws -> UInt32 {
return UInt32(try sgrpval() ) ?? 0
}
func decode(_ type: UInt64.Type) throws -> UInt64 {
return UInt64(try sgrpval() ) ?? 0
}
func decode<T>(_ type: T.Type) throws -> T where T : Decodable {
let g = grp()
return try T.init(from: EnvVarDecoder(codingPath: codingPath + [EnvKey(stringValue: g.0)!], userInfo: [:]))
}
func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer<NestedKey> where NestedKey : CodingKey {
let grp = ids[currentIndex] // ?? increment ??
let newks: [NestedKey] = (codingPath + [EnvKey(stringValue: grp.0)!]).compactMap { NestedKey(stringValue: $0.stringValue) }
return KeyedDecodingContainer(ObjectReader<NestedKey>(codingPath: newks))
}
func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer {
let grp = ids[currentIndex] // ?? increment ??
return ObjectArrayReader(codingPath: codingPath + [EnvKey(stringValue: grp.0)!])
}
func superDecoder() throws -> Decoder {
fatalError()
}
}
class ObjectPropertyReader: SingleValueDecodingContainer {
let codingPath: [CodingKey]
init(codingPath: [CodingKey]) {
self.codingPath = codingPath
// print("codingPath \(codingPath.map { $0.stringValue })")
}
var env: String? { EnvVarDecoder.env[joinKeys(codingPath: codingPath)] }
func decodeNil() -> Bool {
return nil == env
}
func decode(_ type: Bool.Type) throws -> Bool {
return Bool(env ?? "false") ?? false
}
func decode(_ type: String.Type) throws -> String {
return env ?? ""
}
func decode(_ type: Double.Type) throws -> Double {
return Double(env ?? "0") ?? 0
}
func decode(_ type: Float.Type) throws -> Float {
return Float(env ?? "0") ?? 0
}
func decode(_ type: Int.Type) throws -> Int {
return Int(env ?? "0") ?? 0
}
func decode(_ type: Int8.Type) throws -> Int8 {
return Int8(env ?? "0") ?? 0
}
func decode(_ type: Int16.Type) throws -> Int16 {
return Int16(env ?? "0") ?? 0
}
func decode(_ type: Int32.Type) throws -> Int32 {
return Int32(env ?? "0") ?? 0
}
func decode(_ type: Int64.Type) throws -> Int64 {
return Int64(env ?? "0") ?? 0
}
func decode(_ type: UInt.Type) throws -> UInt {
return UInt(env ?? "0") ?? 0
}
func decode(_ type: UInt8.Type) throws -> UInt8 {
return UInt8(env ?? "0") ?? 0
}
func decode(_ type: UInt16.Type) throws -> UInt16 {
return UInt16(env ?? "0") ?? 0
}
func decode(_ type: UInt32.Type) throws -> UInt32 {
return UInt32(env ?? "0") ?? 0
}
func decode(_ type: UInt64.Type) throws -> UInt64 {
return UInt64(env ?? "0") ?? 0
}
func decode<T>(_ type: T.Type) throws -> T where T : Decodable {
return try T.init(from: EnvVarDecoder(codingPath: codingPath, userInfo: [:]))
}
}
| 28.090426 | 151 | 0.670801 |
46bc367ad7487c54423e52b3c9832134ab94d75b | 877 | // File created from ScreenTemplate
// $ createScreen.sh Rooms/ShowDirectory ShowDirectory
/*
Copyright 2020 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
/// ShowDirectoryViewController view state
enum ShowDirectoryViewState {
case loading
case loadedWithoutUpdate
case loaded(_ sections: [ShowDirectorySection])
case error(Error)
}
| 31.321429 | 73 | 0.775371 |
c179418039dbd020f610f59d83e3e82e24a3429e | 1,440 | //
// SourcesListView.swift
// NewsApp With SwiftUI Framework
//
// Created by Алексей Воронов on 15.06.2019.
// Copyright © 2019 Алексей Воронов. All rights reserved.
//
import SwiftUI
struct SourcesListView : View {
@ObservedObject var viewModel = SourcesListViewModel()
var body: some View {
NavigationView(content: {
VStack {
if viewModel.sources.isEmpty {
ActivityIndicator()
.frame(width: UIScreen.main.bounds.width,
height: 50,
alignment: .center)
} else {
List(viewModel.sources, id: \.self) { source in
NavigationLink(
destination: ArticlesFromSourceView(source: source)
.navigationBarTitle(Text(source.name)),
label: {
Text(source.name)
}
)
}
.listStyle(GroupedListStyle())
.environment(\.horizontalSizeClass, .regular)
.animation(.spring())
}
}
.onAppear {
self.viewModel.getSources()
}
.navigationBarTitle(Text("Sources".localized()), displayMode: .large)
})
}
}
| 32.727273 | 81 | 0.456944 |
e64e53d85855a661518f6a4df704c95bf109bb39 | 8,729 | /*
Copyright (c) 2019, Apple Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder(s) nor the names of any contributors
may be used to endorse or promote products derived from this software without
specific prior written permission. No license is granted to the trademarks of
the copyright holders even if such marks are included in this software.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import CareKitStore
import Foundation
import ModelsDSTU2
extension ModelsDSTU2.Timing: OCKFHIRResource {
public typealias Release = DSTU2
}
struct OCKDSTU2ScheduleCoder: OCKFHIRResourceCoder {
typealias Resource = Timing
typealias Entity = OCKSchedule
func convert(resource: Timing) throws -> OCKSchedule {
// There could be any of 3 kinds of schedules: Timing, Period, String.
// For now we're only considering the Timing case.
guard
let timing = resource.repeat,
let periodUnit = timing.periodUnits?.value,
let periodCount = timing.period.map({ Int(truncating: $0.value!.decimal as NSNumber) })
else { throw OCKFHIRCodingError.missingRequiredField("schedule") }
// Make sure the activity has a valid start date.
guard
case let .period(period) = timing.bounds,
let start = period.start?.value?.foundationDate else {
throw OCKFHIRCodingError.unrepresentableContent(
"A FHIR CarePlanActivity with no start date cannot be represented in CareKit.")
}
// A valid end date is not required in CareKit.
let end: Date? = period.end?.value?.foundationDate
let targets: [OCKOutcomeValue] = []
let text: String? = timing.when?.value?.string
let interval = try makeInterval(units: periodUnit, count: periodCount)
let duration = try makeDuration(units: timing.durationUnits?.value, count: timing.duration?.value)
let element = OCKScheduleElement(
start: start, end: end,
interval: interval, text: text,
targetValues: targets, duration: duration)
return OCKSchedule(composing: [element])
}
func convert(entity: OCKSchedule) throws -> Timing {
// Verify that the schedule can be represented in FHIR format.
// There must be only 1 schedule element and its interval must have only 1 component.
guard let element = entity.elements.first else {
throw OCKFHIRCodingError.corruptData("OCKSchedule didn't have any elements.")
}
guard entity.elements.count == 1 else {
throw OCKFHIRCodingError.unrepresentableContent("OCKSchedules with more than 1 element cannot be represented in FHIR.")
}
var nonZeroComponentCount = 0
let keypaths: [KeyPath<DateComponents, Int?>] = [\.second, \.minute, \.hour, \.day, \.weekOfYear, \.month, \.year]
for path in keypaths {
if element.interval[keyPath: path] != nil && element.interval[keyPath: path] != 0 {
nonZeroComponentCount += 1
}
}
guard nonZeroComponentCount == 1 else {
throw OCKFHIRCodingError.unrepresentableContent("""
OCKScheduleElements with intervals containing more than 1 component cannot be represented in FHIR.
""")
}
// Reject components not support by FHIR.
if element.interval.year != nil && element.interval.year != 0 {
throw OCKFHIRCodingError.unrepresentableContent("OCKScheduleElements with an interval in units of years are not supported in FHIR.")
}
// Build out the FHIR schedule
let repetition = TimingRepeat(element: element)
let start = FHIRPrimitive(entity.startDate().dstu2FHIRDateTime)
let end = FHIRPrimitive(entity.endDate()?.dstu2FHIRDateTime)
repetition.bounds = .period(Period(end: end, start: start))
repetition.frequency = FHIRPrimitive(1)
let timing = Timing()
timing.repeat = repetition
return timing
}
private func makeInterval(units: FHIRString, count: Int) throws -> DateComponents {
switch units {
case Calendar.Component.second.dstu2FHIRUnitString.value: return DateComponents(second: count)
case Calendar.Component.minute.dstu2FHIRUnitString.value: return DateComponents(minute: count)
case Calendar.Component.hour.dstu2FHIRUnitString.value: return DateComponents(hour: count)
case Calendar.Component.day.dstu2FHIRUnitString.value: return DateComponents(day: count)
case Calendar.Component.weekOfYear.dstu2FHIRUnitString.value: return DateComponents(weekOfYear: count)
case Calendar.Component.month.dstu2FHIRUnitString.value: return DateComponents(month: count)
default: throw OCKFHIRCodingError.corruptData("Unrecognized time units: \(units.string)")
}
}
private func makeDuration(units: FHIRString?, count: FHIRDecimal?) throws -> OCKScheduleElement.Duration {
guard let units = units, let count = count else { return .seconds(0) }
let doubleValue = Double(truncating: count.decimal as NSNumber)
// Treat units of days with duration of 1 as the special case `.allDay`.
if units == Calendar.Component.day.dstu2FHIRUnitString && count == FHIRDecimal(1) {
return .allDay
}
switch units {
case Calendar.Component.second.dstu2FHIRUnitString.value: return .seconds(doubleValue)
case Calendar.Component.minute.dstu2FHIRUnitString.value: return .minutes(doubleValue)
case Calendar.Component.hour.dstu2FHIRUnitString.value: return .hours(doubleValue)
default: throw OCKFHIRCodingError.corruptData("Unrecognized time unitss: \(units.string)")
}
}
}
private extension TimingRepeat {
convenience init(element: OCKScheduleElement) {
self.init()
switch element.duration {
case .allDay:
durationUnits = Calendar.Component.day.dstu2FHIRUnitString
duration = FHIRPrimitive(FHIRDecimal(Decimal(1)))
case .seconds(let secs):
durationUnits = Calendar.Component.second.dstu2FHIRUnitString
duration = FHIRPrimitive(FHIRDecimal(Decimal(secs)))
}
if let seconds = element.interval.second {
periodUnits = Calendar.Component.second.dstu2FHIRUnitString
period = FHIRPrimitive(FHIRDecimal(Decimal(seconds)))
} else if let minutes = element.interval.minute {
periodUnits = Calendar.Component.minute.dstu2FHIRUnitString
period = FHIRPrimitive(FHIRDecimal(Decimal(minutes)))
} else if let hours = element.interval.hour {
periodUnits = Calendar.Component.hour.dstu2FHIRUnitString
period = FHIRPrimitive(FHIRDecimal(Decimal(hours)))
} else if let days = element.interval.day {
periodUnits = Calendar.Component.day.dstu2FHIRUnitString
period = FHIRPrimitive(FHIRDecimal(Decimal(days)))
} else if let weeks = element.interval.weekOfYear {
periodUnits = Calendar.Component.weekOfYear.dstu2FHIRUnitString
period = FHIRPrimitive(FHIRDecimal(Decimal(weeks)))
} else if let months = element.interval.month {
periodUnits = Calendar.Component.month.dstu2FHIRUnitString
period = FHIRPrimitive(FHIRDecimal(Decimal(months)))
} else {
fatalError("Missing case")
}
}
}
| 46.185185 | 144 | 0.69481 |
61d760125995d31dd268aed8b0c9bbd6dff3dca9 | 738 | import SwiftUI
struct KeyboardShortcutKey<Content: View>: View {
@Environment(\.colorScheme) var colorScheme: ColorScheme
let content: Content
init(@ViewBuilder content: () -> Content) {
self.content = content()
}
var body: some View {
content
.font(.system(size: 14, weight: .semibold, design: .rounded))
.padding(.vertical, 3.0)
.padding(.horizontal, 7.0)
.border(colorScheme == .light ? Color.gray.opacity(0.5) : Color.gray.opacity(0.5), width: 1)
.cornerRadius(2)
}
}
struct KeyboardShortcutKey_Previews: PreviewProvider {
static var previews: some View {
KeyboardShortcutKey {
Text("L")
}
}
}
| 26.357143 | 104 | 0.596206 |
ff5ad73702e5a2ea2734e64ca76a389cf7f0b9f0 | 6,685 | // The MIT License (MIT)
//
// Copyright (c) 2016 Suyeol Jeon (xoul.kr)
//
// 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.
// MARK: if
public func if_<Value>(condition: Bool, _ then: () -> Value) -> Value? {
if condition {
return then()
}
return nil
}
// MARK: if let
public func if_let_<Optional, Value>(optional: Optional?, _ then: Optional -> Value) -> Value? {
return if_let_(optional, where_: true, then)
}
public func if_let_<Optional, Value>(optional: Optional?,
@autoclosure where_: () -> Bool,
_ then: Optional -> Value) -> Value? {
return if_let_(optional, where_: { _ in true }, then)
}
public func if_let_<Optional, Value>(optional: Optional?,
where_: Optional -> Bool,
_ then: Optional -> Value) -> Value? {
if let wrapped = optional where where_(wrapped) {
return then(wrapped)
}
return nil
}
// MARK: if let 2
public func if_let_<Optional1, Optional2, T>(optional1: Optional1?,
_ optional2: Optional2?,
_ then: (Optional1, Optional2) -> T) -> T? {
return if_let_(optional1, optional2, where_: true, then)
}
public func if_let_<Optional1, Optional2, T>(optional1: Optional1?,
_ optional2: Optional2?,
@autoclosure where_: () -> Bool,
_ then: (Optional1, Optional2) -> T) -> T? {
return if_let_(optional1, optional2, where_: { _ in true }, then)
}
public func if_let_<Optional1, Optional2, T>(optional1: Optional1?,
_ optional2: Optional2?,
where_: (Optional1, Optional2) -> Bool,
_ then: (Optional1, Optional2) -> T) -> T? {
if let wrapped1 = optional1, wrapped2 = optional2 where where_((wrapped1, wrapped2)) {
return then((wrapped1, wrapped2))
}
return nil
}
// MARK: if let 3
public func if_let_<Optional1, Optional2, Optional3, T>(optional1: Optional1?,
_ optional2: Optional2?,
_ optional3: Optional3?,
_ then: (Optional1, Optional2, Optional3) -> T) -> T? {
return if_let_(optional1, optional2, optional3, where_: true, then)
}
public func if_let_<Optional1, Optional2, Optional3, T>(optional1: Optional1?,
_ optional2: Optional2?,
_ optional3: Optional3?,
@autoclosure where_: () -> Bool,
_ then: (Optional1, Optional2, Optional3) -> T) -> T? {
return if_let_(optional1, optional2, optional3, where_: { _ in true }, then)
}
public func if_let_<Optional1, Optional2, Optional3, T>(optional1: Optional1?,
_ optional2: Optional2?,
_ optional3: Optional3?,
where_: (Optional1, Optional2, Optional3) -> Bool,
_ then: (Optional1, Optional2, Optional3) -> T) -> T? {
if let wrapped1 = optional1, wrapped2 = optional2, wrapped3 = optional3
where where_((wrapped1, wrapped2, wrapped3)) {
return then((wrapped1, wrapped2, wrapped3))
}
return nil
}
// MARK: -
extension Optional {
// MARK: else if
public func else_if_(condition: Bool, _ then: () -> Wrapped) -> Wrapped? {
if case .None = self where condition {
return then()
}
return self
}
// MARK: else if let
public func else_if_let_<Optional>(optional: Optional?, _ then: Optional -> Wrapped) -> Wrapped? {
if case .None = self, let wrapped = optional {
return then(wrapped)
}
return self
}
// MARK: else if let 2
public func else_if_let_<Optional1, Optional2>(optional1: Optional1?,
_ optional2: Optional2?,
_ then: (Optional1, Optional2) -> Wrapped) -> Wrapped? {
if case .None = self, let wrapped1 = optional1, wrapped2 = optional2 {
return then((wrapped1, wrapped2))
}
return self
}
// MARK: else if let 3
public func else_if_let_<Optional1, Optional2, Optional3>(optional1: Optional1?,
_ optional2: Optional2?,
_ optional3: Optional3?,
_ then: (Optional1, Optional2, Optional3) -> Wrapped)
-> Wrapped? {
if case .None = self, let wrapped1 = optional1, wrapped2 = optional2, wrapped3 = optional3 {
return then((wrapped1, wrapped2, wrapped3))
}
return self
}
// MARK: else
public func else_(then: () -> Wrapped) -> Wrapped {
switch self {
case .None:
return then()
case .Some(let wrapped):
return wrapped
}
}
}
| 38.641618 | 115 | 0.52012 |
22c7d60bd33f6d9e1e675f41ec0f00f49c11696d | 3,864 | //
// TLAuthorizedManager.swift
// TLStoryCamera
//
// Created by garry on 2017/5/26.
// Copyright © 2017年 com.garry. All rights reserved.
//
import UIKit
import Photos
typealias AuthorizedCallback = (TLAuthorizedManager.AuthorizedType, Bool) -> Void
class TLAuthorizedManager: NSObject {
public enum AuthorizedType {
case mic
case camera
case album
}
public static func requestAuthorization(with type:AuthorizedType, callback:@escaping AuthorizedCallback) {
if type == .mic {
self.requestMicAuthorizationStatus(callback)
}
if type == .camera {
self.requestCameraAuthorizationStatus(callback)
}
if type == .album {
self.requestAlbumAuthorizationStatus(callback)
}
}
public static func checkAuthorization(with type:AuthorizedType) -> Bool {
if type == .mic {
return AVAudioSession.sharedInstance().recordPermission() == .granted
}
if type == .camera {
return AVCaptureDevice.authorizationStatus(for: AVMediaType.video) == .authorized
}
if type == .album {
return PHPhotoLibrary.authorizationStatus() == .authorized
}
return false
}
public static func openAuthorizationSetting() {
if #available(iOS 10.0, *) {
UIApplication.shared.open(URL.init(string: UIApplicationOpenSettingsURLString)!, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(URL.init(string: UIApplicationOpenSettingsURLString)!)
}
}
fileprivate static func requestMicAuthorizationStatus(_ callabck:@escaping AuthorizedCallback) {
let status = AVAudioSession.sharedInstance().recordPermission()
if status == .granted {
DispatchQueue.main.async {
callabck(.mic, true)
}
}else if status == .denied {
DispatchQueue.main.async {
callabck(.mic, false)
}
self.openAuthorizationSetting()
}else{
AVAudioSession.sharedInstance().requestRecordPermission({ granted in
DispatchQueue.main.async {
callabck(.mic, granted)
}
})
}
}
fileprivate static func requestCameraAuthorizationStatus(_ callabck:@escaping AuthorizedCallback) {
let status = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
if status == .authorized {
DispatchQueue.main.async {
callabck(.camera, true)
}
}else if status == .notDetermined {
AVCaptureDevice.requestAccess(for: AVMediaType.video, completionHandler: { granted in
DispatchQueue.main.async {
callabck(.camera, granted)
}
})
}else if (status == .denied) {
DispatchQueue.main.async {
callabck(.camera, false)
self.openAuthorizationSetting()
}
}
}
fileprivate static func requestAlbumAuthorizationStatus(_ callabck:@escaping AuthorizedCallback) {
let status = PHPhotoLibrary.authorizationStatus()
if status == .authorized {
DispatchQueue.main.async {
callabck(.album, true)
}
}else if status == .notDetermined {
PHPhotoLibrary.requestAuthorization({ (granted) in
DispatchQueue.main.async {
callabck(.album, granted == .authorized)
}
})
}else if status == .denied || status == .restricted {
DispatchQueue.main.async {
callabck(.album, false)
}
self.openAuthorizationSetting()
}
}
}
| 33.894737 | 130 | 0.583592 |
eb62e2f7101a3c407e6a59b67d333f70d40b8b66 | 7,647 | //
// Color.swift
// Jokes
//
// Created by Alex Littlejohn on 10/07/2020.
// Copyright © 2020 zero. All rights reserved.
//
import Swift
import SwiftUI
extension Color {
public static var almostClear: Color {
Color.black.opacity(0.0001)
}
}
extension Color {
/// A color for placeholder text in controls or text fields or text views.
public static var placeholderText: Color {
#if os(iOS) || os(macOS) || os(tvOS)
return .init(.placeholderText)
#else
return .gray // FIXME
#endif
}
}
#if os(iOS) || os(macOS) || os(tvOS)
extension Color {
public static var systemRed: Color {
return .init(.systemRed)
}
public static var systemGreen: Color {
return .init(.systemGreen)
}
public static var systemBlue: Color {
return .init(.systemBlue)
}
public static var systemOrange: Color {
return .init(.systemOrange)
}
public static var systemYellow: Color {
return .init(.systemYellow)
}
public static var systemPink: Color {
return .init(.systemPink)
}
public static var systemPurple: Color {
return .init(.systemPurple)
}
public static var systemTeal: Color {
return .init(.systemTeal)
}
public static var systemIndigo: Color {
return .init(.systemIndigo)
}
public static var systemGray: Color {
return .init(.systemGray)
}
}
#endif
#if os(iOS) || targetEnvironment(macCatalyst)
extension Color {
public static var systemGray2: Color {
return .init(.systemGray2)
}
public static var systemGray3: Color {
return .init(.systemGray3)
}
public static var systemGray4: Color {
return .init(.systemGray4)
}
public static var systemGray5: Color {
return .init(.systemGray5)
}
public static var systemGray6: Color {
return .init(.systemGray6)
}
}
/// Foreground colors for static text and related elements.
extension Color {
public static var label: Color {
return .init(.label)
}
public static var secondaryLabel: Color {
return .init(.secondaryLabel)
}
public static var tertiaryLabel: Color {
return .init(.tertiaryLabel)
}
public static var quaternaryLabel: Color {
return .init(.quaternaryLabel)
}
}
extension Color {
/// A foreground color for standard system links.
public static var link: Color {
return .init(.link)
}
/// A forground color for separators (thin border or divider lines).
public static var separator: Color {
return .init(.separator)
}
/// A forground color intended to look similar to `Color.separated`, but is guaranteed to be opaque, so it will.
public static var opaqueSeparator: Color {
return .init(.opaqueSeparator)
}
}
extension Color {
public static var systemBackground: Color {
return .init(.systemBackground)
}
public static var secondarySystemBackground: Color {
return .init(.secondarySystemBackground)
}
public static var tertiarySystemBackground: Color {
return .init(.tertiarySystemBackground)
}
public static var systemGroupedBackground: Color {
return .init(.systemGroupedBackground)
}
public static var secondarySystemGroupedBackground: Color {
return .init(.secondarySystemGroupedBackground)
}
public static var tertiarySystemGroupedBackground: Color {
return .init(.tertiarySystemGroupedBackground)
}
}
/// Fill colors for UI elements.
/// These are meant to be used over the background colors, since their alpha component is less than 1.
extension Color {
/// A color appropriate for filling thin and small shapes.
///
/// Example: The track of a slider.
public static var systemFill: Color {
return .init(.systemFill)
}
/// A color appropriate for filling medium-size shapes.
///
/// Example: The background of a switch.
public static var secondarySystemFill: Color {
return .init(.secondarySystemFill)
}
/// A color appropriate for filling large shapes.
///
/// Examples: Input fields, search bars, buttons.
public static var tertiarySystemFill: Color {
return .init(.tertiarySystemFill)
}
/// A color appropriate for filling large areas containing complex content.
///
/// Example: Expanded table cells.
public static var quaternarySystemFill: Color {
return .init(.quaternarySystemFill)
}
}
#endif
#if os(iOS) || os(tvOS) || targetEnvironment(macCatalyst)
extension Color {
/// Creates a color from a hexadecimal color code.
///
/// - Parameter hexadecimal: A hexadecimal representation of the color.
///
/// - Returns: A `Color` from the given color code. Returns `nil` if the code is invalid.
public init!(hexadecimal string: String) {
var string: String = string.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
if string.hasPrefix("#") {
_ = string.removeFirst()
}
if !string.count.isMultiple(of: 2), let last = string.last {
string.append(last)
}
if string.count > 8 {
string = String(string.prefix(8))
}
let scanner = Scanner(string: string)
var color: UInt64 = 0
scanner.scanHexInt64(&color)
if string.count == 2 {
let mask = 0xFF
let g = Int(color) & mask
let gray = Double(g) / 255.0
self.init(.sRGB, red: gray, green: gray, blue: gray, opacity: 1)
} else if string.count == 4 {
let mask = 0x00FF
let g = Int(color >> 8) & mask
let a = Int(color) & mask
let gray = Double(g) / 255.0
let alpha = Double(a) / 255.0
self.init(.sRGB, red: gray, green: gray, blue: gray, opacity: alpha)
} else if string.count == 6 {
let mask = 0x0000FF
let r = Int(color >> 16) & mask
let g = Int(color >> 8) & mask
let b = Int(color) & mask
let red = Double(r) / 255.0
let green = Double(g) / 255.0
let blue = Double(b) / 255.0
self.init(.sRGB, red: red, green: green, blue: blue, opacity: 1)
} else if string.count == 8 {
let mask = 0x000000FF
let r = Int(color >> 24) & mask
let g = Int(color >> 16) & mask
let b = Int(color >> 8) & mask
let a = Int(color) & mask
let red = Double(r) / 255.0
let green = Double(g) / 255.0
let blue = Double(b) / 255.0
let alpha = Double(a) / 255.0
self.init(.sRGB, red: red, green: green, blue: blue, opacity: alpha)
} else {
return nil
}
}
/// Creates a color from a 6-digit hexadecimal color code.
public init(hexadecimal6: Int) {
let red = Double((hexadecimal6 & 0xFF0000) >> 16) / 255.0
let green = Double((hexadecimal6 & 0x00FF00) >> 8) / 255.0
let blue = Double(hexadecimal6 & 0x0000FF) / 255.0
self.init(red: red, green: green, blue: blue)
}
}
#endif
| 26.644599 | 116 | 0.576174 |
284d969c2c781e0101dcab39ab004bfc9171d96a | 198 | //
// This file (and all other Swift source files in the Sources directory of this playground) will be precompiled into a framework which is automatically made available to MapReduce.playground.
//
| 49.5 | 191 | 0.792929 |
cc8481bc905d42cd7f8b9daf4984088a4a28a3c9 | 4,946 | //
// Copyright (C) 2016-present Instructure, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
extension NSError {
public var shouldRecordInCrashlytics: Bool {
switch (domain, code) {
case (NSCocoaErrorDomain, 13): fallthrough // NSCocoaErrorDomain 13 NSUnderlyingException: error during SQL execution : database or disk is full
case (NSURLErrorDomain, NSURLErrorNotConnectedToInternet): fallthrough
case (NSURLErrorDomain, NSURLErrorTimedOut): fallthrough
case (NSURLErrorDomain, NSURLErrorNetworkConnectionLost): fallthrough
case (NSURLErrorDomain, NSURLErrorDataNotAllowed):
return false
default:
return true
}
}
public struct AlertDetails {
public let title: String
public let description: String
public let actions: [UIAlertAction]
}
private var dismissAction: UIAlertAction {
return UIAlertAction(title: NSLocalizedString("Dismiss", tableName: "Localizable", bundle: .core, comment: "Dismiss button for error messages"), style: .default, handler: nil)
}
private func reportAction(action: @escaping (() -> ())) -> UIAlertAction {
return UIAlertAction(title: NSLocalizedString("Report", tableName: "Localizable", bundle: .core, comment: "Button to report an error"), style: .default, handler: { _ in action() })
}
public func alertDetails(reportAction: (() -> ())? = nil) -> AlertDetails? {
let networkErrorTitle = NSLocalizedString("Network Error", tableName: "Localizable", bundle: .core, comment: "Error alert title for network error")
let reportOrDismiss: [UIAlertAction]
if let report = reportAction.map({ self.reportAction(action: $0)}) {
reportOrDismiss = [report, dismissAction]
} else {
reportOrDismiss = [dismissAction]
}
let justDismiss = [dismissAction]
switch (domain, code) {
case (NSCocoaErrorDomain, 13): // NSCocoaErrorDomain 13 NSUnderlyingException: error during SQL execution : database or disk is full
let title = NSLocalizedString("Disk Error", tableName: "Localizable", bundle: .core, comment: "Error title to alert user their device is out of storage space")
let description = NSLocalizedString("Your device is out of storage space. Please free up space and try again.", comment: "Error description for file out of space")
return AlertDetails(title: title, description: description, actions: justDismiss)
case (NSURLErrorDomain, NSURLErrorNotConnectedToInternet): fallthrough
case (NSURLErrorDomain, NSURLErrorTimedOut): fallthrough
case (NSURLErrorDomain, NSURLErrorNetworkConnectionLost): fallthrough
case (NSURLErrorDomain, NSURLErrorDataNotAllowed):
// This error is now handled on the react native side
return nil;
case (NSURLErrorDomain, NSURLErrorServerCertificateUntrusted):
return AlertDetails(title: networkErrorTitle, description: localizedDescription, actions: reportOrDismiss)
case ("com.instructure.canvas", 90211): // push channel error. no idea where 90211 comes from.
let title = NSLocalizedString("Notification Error", tableName: "Localizable", bundle: .core, comment: "Error title for push notification registration error")
let description = NSLocalizedString("There was a problem registering your device for push notifications.", tableName: "Localizable", bundle: .core, comment: "Error description for Push Notifications registration error.")
return AlertDetails(title: title, description: description, actions: reportOrDismiss)
default:
if var description = userInfo[NSLocalizedDescriptionKey] as? String, description != "" {
if let reason = localizedFailureReason {
description += "\n\n" + reason
}
let title = NSLocalizedString("Unknown Error", tableName: "Localizable", bundle: .core, comment: "An unknown error title")
return AlertDetails(title: title, description: description, actions: reportOrDismiss)
}
return nil
}
}
}
| 52.063158 | 232 | 0.667004 |
20e6a3ba75991ef97a6483295b91217b19abffd2 | 981 | //
// Snapchat_MenuTests.swift
// Snapchat MenuTests
//
// Created by Allen on 16/1/10.
// Copyright © 2016年 Allen. All rights reserved.
//
import XCTest
@testable import Snapchat_Menu
class Snapchat_MenuTests: 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.513514 | 111 | 0.637105 |
9c80406dde39a87c2472dcb4b71c8b1db9d90d50 | 506 | //
// BJProtocol.swift
// BJCollection
//
// Created by Sovannra on 29/12/21.
//
import UIKit
public protocol BJDelegate {
func didSelect(_ type: BJActionType, _ comment: BJCommentViewModel)
func didLongPress(_ comment: BJCommentViewModel)
}
public enum BJActionType {
case profile
case caption
case reply
}
public class BJLongGesture: UILongPressGestureRecognizer {
var type: BJLongGestureType = .caption
}
public enum BJLongGestureType {
case caption
case image
}
| 17.448276 | 71 | 0.727273 |
c13df7a064ead9e6e2791e96ae24afaaafb43a86 | 4,207 | /// 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.
///
/// This project and source code may use libraries or frameworks that are
/// released under various Open-Source licenses. Use of those libraries and
/// frameworks are governed by their own individual licenses.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
import SwiftUI
struct AwardsView: View {
@EnvironmentObject var flightNavigation: AppEnvironment
@State var selectedAward: AwardInformation?
@Namespace var cardNamespace
var awardArray: [AwardInformation] {
flightNavigation.awardList
}
var activeAwards: [AwardInformation] {
awardArray.filter { $0.awarded }
}
var inactiveAwards: [AwardInformation] {
awardArray.filter { !$0.awarded }
}
var awardColumns: [GridItem] {
[GridItem(.adaptive(minimum: 150, maximum: 170))]
}
var body: some View {
ZStack {
if let award = selectedAward {
AwardDetails(award: award)
.background(Color.white)
.shadow(radius: 5.0)
.clipShape(RoundedRectangle(cornerRadius: 20.0))
.onTapGesture {
withAnimation {
selectedAward = nil
}
}
.matchedGeometryEffect(id: award.hashValue, in: cardNamespace, anchor: .topLeading)
} else {
ScrollView {
LazyVGrid(columns: awardColumns, pinnedViews: .sectionHeaders) {
AwardGrid(
title: "Awarded",
awards: activeAwards,
selected: $selectedAward,
namespace: cardNamespace
)
AwardGrid(
title: "Not Awarded",
awards: inactiveAwards,
selected: $selectedAward,
namespace: cardNamespace
)
}
}
}
}
.padding()
.background(
Image("background-view")
.resizable()
.frame(maxWidth: .infinity, maxHeight: .infinity)
)
.navigationTitle("Your Awards")
}
}
struct AwardsView_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
AwardsView()
}.navigationViewStyle(StackNavigationViewStyle())
.environmentObject(AppEnvironment())
}
}
| 38.953704 | 103 | 0.606846 |
2946bab010b3140a9365c6868ce3f93697acbfcf | 890 | //
// BitriseCLITests.swift
// Bitrise-GUI-OSX
//
// Created by Viktor Benei on 07/11/15.
// Copyright © 2015 bitrise. All rights reserved.
//
import XCTest
@testable import Bitrise_GUI_OSX
class BitriseCLITests: 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 testVersion() {
XCTAssertEqual("1.2.4", BitriseCLI().version())
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
| 24.722222 | 111 | 0.624719 |
09eca7e2658d3188c944b4c6a0c2182f8f90a98f | 1,236 | import Foundation
public protocol FavoriteAPIv1 {
/// https://developer.twitter.com/en/docs/twitter-api/v1/tweets/post-and-engage/api-reference/post-favorites-create
func postFavorite(
_ request: PostFavoriteRequestV1
) -> TwitterAPISessionJSONTask
/// https://developer.twitter.com/en/docs/twitter-api/v1/tweets/post-and-engage/api-reference/post-favorites-destroy
func postUnFavorite(
_ request: PostUnFavoriteRequestV1
) -> TwitterAPISessionJSONTask
/// https://developer.twitter.com/en/docs/twitter-api/v1/tweets/post-and-engage/api-reference/get-favorites-list
func getFavorites(
_ request: GetFavoritesRequestV1
) -> TwitterAPISessionJSONTask
}
extension TwitterAPIKit.TwitterAPIImplV1: FavoriteAPIv1 {
public func getFavorites(
_ request: GetFavoritesRequestV1
) -> TwitterAPISessionJSONTask {
return session.send(request)
}
public func postFavorite(
_ request: PostFavoriteRequestV1
) -> TwitterAPISessionJSONTask {
return session.send(request)
}
public func postUnFavorite(
_ request: PostUnFavoriteRequestV1
) -> TwitterAPISessionJSONTask {
return session.send(request)
}
}
| 30.146341 | 120 | 0.716828 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.