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
ef44b67995e4ca731df651637e1324d4f4d3cc3c
1,607
import Foundation public extension String { func appendingPathComponent(_ component: String) -> String { return (self as NSString).appendingPathComponent(component) } func deletingPathExtension() -> String { return (self as NSString).deletingPathExtension } func deletingLastPathComponent() -> String { return (self as NSString).deletingLastPathComponent } func pathComponents() -> [String] { return (self as NSString).pathComponents } func pathExtension() -> String { return (self as NSString).pathExtension } func lastPathComponent() -> String { return (self as NSString).lastPathComponent } func appendingPathExtension(_ pathExtension: String) -> String { guard let result = (self as NSString).appendingPathExtension(pathExtension) else { return "\(self).\(pathExtension)" } return result } static func path(withComponents components: [String]) -> String { return NSString.path(withComponents: components) } func relativePath(to rootPath: String) -> String? { let rootComponents = rootPath.pathComponents() let components = pathComponents() var equalIndex = 0 for (index, rootComponent) in rootComponents.enumerated() { if components[index] == rootComponent { equalIndex = index } else { return nil } } return String.path(withComponents: Array(components.dropFirst(equalIndex))) } }
30.320755
90
0.621655
46c858b4796cd4102967a57e869b23a46f7b78e1
1,115
// 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: "FoundationWithNetworking", products: [ // Products define the executables and libraries produced by a package, and make them visible to other packages. .library( name: "FoundationWithNetworking", targets: ["FoundationWithNetworking"]), ], dependencies: [ // Dependencies declare other packages that this package depends on. // .package(url: /* package url */, from: "1.0.0"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages which this package depends on. .target( name: "FoundationWithNetworking", dependencies: []), .testTarget( name: "FoundationWithNetworkingTests", dependencies: ["FoundationWithNetworking"]), ] )
38.448276
122
0.651121
bb09767c0fe52be993fa0979eaf4c2df1f744937
7,636
// // RequestFactory.swift // ExponeaSDK // // Created by Ricardo Tokashiki on 09/04/2018. // Copyright © 2018 Exponea. All rights reserved. // import Foundation /// Path route with projectId struct RequestFactory { public var baseUrl: String public var projectToken: String public var route: Routes public init(baseUrl: String, projectToken: String, route: Routes) { self.baseUrl = baseUrl self.projectToken = projectToken self.route = route } public var path: String { switch self.route { case .identifyCustomer: return baseUrl + "/track/v2/projects/\(projectToken)/customers" case .customEvent: return baseUrl + "/track/v2/projects/\(projectToken)/customers/events" case .customerRecommendation: return baseUrl + "/data/v2/projects/\(projectToken)/customers/attributes" case .customerAttributes: return baseUrl + "/data/v2/projects/\(projectToken)/customers/attributes" case .customerEvents: return baseUrl + "/data/v2/projects/\(projectToken)/customers/events" case .banners: return baseUrl + "/data/v2/projects/\(projectToken)/configuration/banners" case .consents: return baseUrl + "/data/v2/projects/\(projectToken)/consent/categories" case .personalization: return baseUrl + "/data/v2/projects/\(projectToken)/customers/personalisation/show-banners" case .campaignClick: return baseUrl + "/track/v2/projects/\(projectToken)/campaigns/clicks" } } } extension RequestFactory { func prepareRequest(authorization: Authorization, parameters: RequestParametersType? = nil, customerIds: [String: JSONValue]? = nil) -> URLRequest { var request = URLRequest(url: URL(string: path)!) // Create the basic request request.httpMethod = route.method.rawValue request.addValue(Constants.Repository.contentType, forHTTPHeaderField: Constants.Repository.headerContentType) request.addValue(Constants.Repository.contentType, forHTTPHeaderField: Constants.Repository.headerAccept) // Add authorization if it was provided switch authorization { case .none: break case .token(let token): request.addValue("Token \(token)", forHTTPHeaderField: Constants.Repository.headerAuthorization) } // Add parameters as request body in JSON format, if we have any if let parameters = parameters?.requestParameters { var params = parameters // Add customer ids if separate if let customerIds = customerIds { params["customer_ids"] = customerIds.mapValues({ $0.jsonConvertible }) } do { request.httpBody = try JSONSerialization.data(withJSONObject: params, options: []) } catch { Exponea.logger.log(.error, message: "Failed to serialise request body into JSON: \(error.localizedDescription)") Exponea.logger.log(.verbose, message: "Request parameters: \(params)") } } // Log request if necessary if Exponea.logger.logLevel == .verbose { Exponea.logger.log(.verbose, message: "Created request: \n\(request.description)") } return request } typealias CompletionHandler = ((Data?, URLResponse?, Error?) -> Void) func handler<T: ErrorInitialisable>(with completion: @escaping ((EmptyResult<T>) -> Void)) -> CompletionHandler { return { (data, response, error) in self.process(response, data: data, error: error, resultAction: { (result) in switch result { case .success: DispatchQueue.main.async { completion(.success) } case .failure(let error): DispatchQueue.main.async { let error = T.create(from: error) completion(.failure(error)) } } }) } } func handler<T: Decodable>(with completion: @escaping ((Result<T>) -> Void)) -> CompletionHandler { return { (data, response, error) in self.process(response, data: data, error: error, resultAction: { (result) in switch result { case .success(let data): do { let object = try JSONDecoder().decode(T.self, from: data) DispatchQueue.main.async { completion(.success(object)) } } catch { DispatchQueue.main.async { completion(.failure(error)) } } case .failure(let error): DispatchQueue.main.async { completion(.failure(error)) } } }) } } func process(_ response: URLResponse?, data: Data?, error: Error?, resultAction: @escaping ((Result<Data>) -> Void)) { // Check if we have any response at all guard let response = response else { DispatchQueue.main.async { resultAction(.failure(RepositoryError.connectionError)) } return } // Log response if needed if Exponea.logger.logLevel == .verbose { Exponea.logger.log(.verbose, message: """ Response received: \(response.description(with: data, error: error)) """) } // Make sure we got the correct response type guard let httpResponse = response as? HTTPURLResponse else { DispatchQueue.main.async { resultAction(.failure(RepositoryError.invalidResponse(response))) } return } if let error = error { //handle server errors switch httpResponse.statusCode { case 500..<600: resultAction(.failure(RepositoryError.serverError(nil))) default: resultAction(.failure(error)) } } else if let data = data { let decoder = JSONDecoder() // Switch on status code switch httpResponse.statusCode { case 400, 405..<500: let text = String(data: data, encoding: .utf8) resultAction(.failure(RepositoryError.missingData(text ?? httpResponse.description))) case 401: let response = try? decoder.decode(ErrorResponse.self, from: data) resultAction(.failure(RepositoryError.notAuthorized(response))) case 404: let errorResponse = try? decoder.decode(MultipleErrorResponse.self, from: data) resultAction(.failure(RepositoryError.urlNotFound(errorResponse))) case 500...Int.max: let errorResponse = try? decoder.decode(MultipleErrorResponse.self, from: data) resultAction(.failure(RepositoryError.serverError(errorResponse))) default: // We assume all other status code are a success resultAction(.success(data)) } } else { resultAction(.failure(RepositoryError.invalidResponse(response))) } } }
39.158974
120
0.566265
56e7becc1af51ef7e1b717d8549f2bf0bff4a929
11,402
// Project Synchrosphere // Copyright 2021, Framework Labs. import Pappe /// Provides the robots functionality as activities. final class SpheroController { private let context: ControllerContext var endpoint: Endpoint! init(context: ControllerContext) { self.context = context } func makeModule(imports: [Module.Import]) -> Module { return Module(imports: imports) { name in // MARK: Power activity (name.Wake_, []) { val in exec { self.context.logInfo("Wake") val.id = self.endpoint.send(PowerCommand.wake, to: 1) } `await` { self.endpoint.hasResponse(for: val.id) } } activity (name.Sleep_, []) { val in exec { self.context.logInfo("Sleep") val.id = self.endpoint.send(PowerCommand.sleep, to: 1) } `await` { self.endpoint.hasResponse(for: val.id) } } activity (Syncs.GetBatteryState, []) { val in exec { self.context.logInfo("GetBatteryState") val.id = self.endpoint.send(PowerCommand.getBatteryState, to: 1) } `await` { self.endpoint.hasResponse(for: val.id) { response in do { let state = try parseGetBatteryStateResponse(response) val.state = state self.context.logInfo("GetBatteryState = \(state)") } catch { val.state = nil as SyncsBatteryState? self.context.logError("GetBatteryState failed with: \(error)") } } } `return` { val.state } } // MARK: IO activity (Syncs.SetMainLED, [name.color]) { val in exec { let color: SyncsColor = val.color self.context.logInfo("SetMainLED \(color)") if self.context.config.deviceSelector == .anyRVR { val.id = self.endpoint.send(SetAllLEDsRequest(mapping: [SyncsRVRLEDs.all: color])) } else { val.id = self.endpoint.send(SetMainLEDRequest(color: color)) } } `await` { self.endpoint.hasResponse(for: val.id) } } activity (Syncs.SetBackLED, [name.brightness]) { val in exec { let brightness: SyncsBrightness = val.brightness self.context.logInfo("SetLBackLED \(brightness)") if self.context.config.deviceSelector == .anyRVR { val.id = self.endpoint.send(SetAllLEDsRequest(mapping: [.breaklight: SyncsColor(brightness: brightness)])) } else { val.id = self.endpoint.send(SetBackLEDRequest(brightness: brightness)) } } `await` { self.endpoint.hasResponse(for: val.id) } } activity (Syncs.SetRVRLEDs, [name.mapping]) { val in exec { let mapping: [SyncsRVRLEDs: SyncsColor] = val.mapping self.context.logInfo("SetRVRLEDs") val.id = self.endpoint.send(SetAllLEDsRequest(mapping: mapping)) } `await` { self.endpoint.hasResponse(for: val.id) } } // MARK: Drive activity (Syncs.ResetHeading, []) { val in exec { self.context.logInfo("ResetHeading") val.id = self.endpoint.send(DriveCommand.resetHeading, to: 2) } `await` { self.endpoint.hasResponse(for: val.id) } } activity (Syncs.Roll, [name.speed, name.heading, name.dir]) { val in exec { let speed: SyncsSpeed = val.speed let heading: SyncsHeading = val.heading let dir: SyncsDir = val.dir self.context.logInfo("Roll speed: \(speed) heading: \(heading) dir: \(dir)") val.id = self.endpoint.send(RollRequest(speed: speed, heading: heading, dir: dir)) } `await` { self.endpoint.hasResponse(for: val.id) } } activity (Syncs.RollForSeconds, [name.speed, name.heading, name.dir, name.seconds]) { val in exec { self.context.logInfo("RollForSeconds \(val.seconds as Int)s") } cobegin { with { run (Syncs.WaitSeconds, [val.seconds]) } with (.weak) { `repeat` { run (Syncs.Roll, [val.speed, val.heading, val.dir]) run (Syncs.WaitSeconds, [1]) // The control timeout is 2s - so we are safe with 1 } } } run (Syncs.StopRoll, [val.heading]) } activity (Syncs.StopRoll, [name.heading]) { val in exec { let heading: SyncsHeading = val.heading self.context.logInfo("StopRoll") val.id = self.endpoint.send(RollRequest(speed: SyncsSpeed(0), heading: heading, dir: .forward)) } `await` { self.endpoint.hasResponse(for: val.id) } } // MARK: Sensor activity (Syncs.ResetLocator, []) { val in exec { self.context.logInfo("ResetLocator") val.id = self.endpoint.send(SensorCommand.resetLocator, to: 2) } `await` { self.endpoint.hasResponse(for: val.id) } } activity (Syncs.SetLocatorFlags, [name.flags]) { val in exec { let flags: SyncsLocatorFlags = val.flags self.context.logInfo("SetLocatorFlags \(flags)") val.id = self.endpoint.send(SensorCommand.setLocatorFlags, with: [flags.rawValue], to: 2) } `await` { self.endpoint.hasResponse(for: val.id) } } activity (name.SensorStreamerRVR_, [name.frequency, name.sensors], [name.sample]) { val in exec { let sensors: SyncsSensors = val.sensors val.id = self.endpoint.send(ConfigureStreamingServiceRequest(sensors: sensors)) } `await` { self.endpoint.hasResponse(for: val.id) } exec { let frequency: Int = val.frequency let period: UInt16 = UInt16(1000) / UInt16(frequency) val.id = self.endpoint.send(StartStreamingServiceRequest(period: period)) } `await` { self.endpoint.hasResponse(for: val.id) } `defer` { self.context.requests_.stopSensorStreaming() } `repeat` { `await` { self.endpoint.hasResponse(for: RequestID(command: SensorCommand.streamingServiceDataNotify, sequenceNr: sensorDataSequenceNr)) { response in do { let timestamp = self.context.clock.counter let sensors: SyncsSensors = val.sensors val.sample = try parseStreamingServiceDataNotifyResponse(response, timestamp: timestamp, sensors: sensors) } catch { self.context.logError("getting streaming sample failed with: \(error)V") } } } } } activity (name.SensorStreamerMini_, [name.frequency, name.sensors], [name.sample]) { val in exec { let frequency: Int = val.frequency let period: UInt16 = UInt16(1000) / UInt16(frequency) let sensors: SyncsSensors = val.sensors self.context.logInfo("SensorStreamer \(frequency)hz \(sensors)") val.id = self.endpoint.send(StartSensorStreamingRequest(period: period, sensors: sensors)) } `await` { self.endpoint.hasResponse(for: val.id) } `defer` { self.context.requests_.stopSensorStreaming() } `repeat` { `await` { self.endpoint.hasResponse(for: RequestID(command: SensorCommand.notifySensorData, sequenceNr: sensorDataSequenceNr)) { response in do { let timestamp = self.context.clock.counter let sensors: SyncsSensors = val.sensors val.sample = try parseStreamedSampleResponse(response, timestamp: timestamp, sensors: sensors) } catch { self.context.logError("getting streaming sample failed with: \(error)V") } } } } } activity (Syncs.SensorStreamer, [name.frequency, name.sensors], [name.sample]) { val in `if` { self.context.config.deviceSelector == .anyRVR } then: { run (name.SensorStreamerRVR_, [val.frequency, val.sensors], [val.loc.sample]) } else: { run (name.SensorStreamerMini_, [val.frequency, val.sensors], [val.loc.sample]) } } activity (name.StopSensorStreamingRVR_, []) { val in exec { self.context.logInfo("StopSensorStreaming") val.id = self.endpoint.send(SensorCommand.stopStreamingService, to: 2) } `await` { self.endpoint.hasResponse(for: val.id) } exec { val.id = self.endpoint.send(SensorCommand.clearStreamingService, to: 2) } `await` { self.endpoint.hasResponse(for: val.id) } } activity (name.StopSensorStreamingMini_, []) { val in exec { self.context.logInfo("StopSensorStreaming") val.id = self.endpoint.send(StopSensorStreamingRequest()) } `await` { self.endpoint.hasResponse(for: val.id) } } activity (name.StopSensorStreaming_, []) { val in `if` { self.context.config.deviceSelector == .anyRVR } then: { run (name.StopSensorStreamingRVR_, []) } else: { run (name.StopSensorStreamingMini_, []) } } } } }
44.365759
164
0.472286
ac1a19cf158b185b575643daace3b9509671275e
20,935
// This file was automatically generated and should not be edited. import XCTest import CommonMark final class CommonMarkSpecHtmlBlocksTests: XCTestCase { func testExample118() throws { let markdown = #######""" <table><tr><td> <pre> **Hello**, _world_. </pre> </td></tr></table> """####### let html = #######""" <table><tr><td> <pre> **Hello**, <p><em>world</em>. </pre></p> </td></tr></table> """####### let document = try Document(markdown) let actual = document.render(format: .html, options: [.unsafe]) let expected = html XCTAssertEqual(actual, expected) } func testExample119() throws { let markdown = #######""" <table> <tr> <td> hi </td> </tr> </table> okay. """####### let html = #######""" <table> <tr> <td> hi </td> </tr> </table> <p>okay.</p> """####### let document = try Document(markdown) let actual = document.render(format: .html, options: [.unsafe]) let expected = html XCTAssertEqual(actual, expected) } func testExample120() throws { let markdown = #######""" <div> *hello* <foo><a> """####### let html = #######""" <div> *hello* <foo><a> """####### let document = try Document(markdown) let actual = document.render(format: .html, options: [.unsafe]) let expected = html XCTAssertEqual(actual, expected) } func testExample121() throws { let markdown = #######""" </div> *foo* """####### let html = #######""" </div> *foo* """####### let document = try Document(markdown) let actual = document.render(format: .html, options: [.unsafe]) let expected = html XCTAssertEqual(actual, expected) } func testExample122() throws { let markdown = #######""" <DIV CLASS="foo"> *Markdown* </DIV> """####### let html = #######""" <DIV CLASS="foo"> <p><em>Markdown</em></p> </DIV> """####### let document = try Document(markdown) let actual = document.render(format: .html, options: [.unsafe]) let expected = html XCTAssertEqual(actual, expected) } func testExample123() throws { let markdown = #######""" <div id="foo" class="bar"> </div> """####### let html = #######""" <div id="foo" class="bar"> </div> """####### let document = try Document(markdown) let actual = document.render(format: .html, options: [.unsafe]) let expected = html XCTAssertEqual(actual, expected) } func testExample124() throws { let markdown = #######""" <div id="foo" class="bar baz"> </div> """####### let html = #######""" <div id="foo" class="bar baz"> </div> """####### let document = try Document(markdown) let actual = document.render(format: .html, options: [.unsafe]) let expected = html XCTAssertEqual(actual, expected) } func testExample125() throws { let markdown = #######""" <div> *foo* *bar* """####### let html = #######""" <div> *foo* <p><em>bar</em></p> """####### let document = try Document(markdown) let actual = document.render(format: .html, options: [.unsafe]) let expected = html XCTAssertEqual(actual, expected) } func testExample126() throws { let markdown = #######""" <div id="foo" *hi* """####### let html = #######""" <div id="foo" *hi* """####### let document = try Document(markdown) let actual = document.render(format: .html, options: [.unsafe]) let expected = html XCTAssertEqual(actual, expected) } func testExample127() throws { let markdown = #######""" <div class foo """####### let html = #######""" <div class foo """####### let document = try Document(markdown) let actual = document.render(format: .html, options: [.unsafe]) let expected = html XCTAssertEqual(actual, expected) } func testExample128() throws { let markdown = #######""" <div *???-&&&-<--- *foo* """####### let html = #######""" <div *???-&&&-<--- *foo* """####### let document = try Document(markdown) let actual = document.render(format: .html, options: [.unsafe]) let expected = html XCTAssertEqual(actual, expected) } func testExample129() throws { let markdown = #######""" <div><a href="bar">*foo*</a></div> """####### let html = #######""" <div><a href="bar">*foo*</a></div> """####### let document = try Document(markdown) let actual = document.render(format: .html, options: [.unsafe]) let expected = html XCTAssertEqual(actual, expected) } func testExample130() throws { let markdown = #######""" <table><tr><td> foo </td></tr></table> """####### let html = #######""" <table><tr><td> foo </td></tr></table> """####### let document = try Document(markdown) let actual = document.render(format: .html, options: [.unsafe]) let expected = html XCTAssertEqual(actual, expected) } func testExample131() throws { let markdown = #######""" <div></div> ``` c int x = 33; ``` """####### let html = #######""" <div></div> ``` c int x = 33; ``` """####### let document = try Document(markdown) let actual = document.render(format: .html, options: [.unsafe]) let expected = html XCTAssertEqual(actual, expected) } func testExample132() throws { let markdown = #######""" <a href="foo"> *bar* </a> """####### let html = #######""" <a href="foo"> *bar* </a> """####### let document = try Document(markdown) let actual = document.render(format: .html, options: [.unsafe]) let expected = html XCTAssertEqual(actual, expected) } func testExample133() throws { let markdown = #######""" <Warning> *bar* </Warning> """####### let html = #######""" <Warning> *bar* </Warning> """####### let document = try Document(markdown) let actual = document.render(format: .html, options: [.unsafe]) let expected = html XCTAssertEqual(actual, expected) } func testExample134() throws { let markdown = #######""" <i class="foo"> *bar* </i> """####### let html = #######""" <i class="foo"> *bar* </i> """####### let document = try Document(markdown) let actual = document.render(format: .html, options: [.unsafe]) let expected = html XCTAssertEqual(actual, expected) } func testExample135() throws { let markdown = #######""" </ins> *bar* """####### let html = #######""" </ins> *bar* """####### let document = try Document(markdown) let actual = document.render(format: .html, options: [.unsafe]) let expected = html XCTAssertEqual(actual, expected) } func testExample136() throws { let markdown = #######""" <del> *foo* </del> """####### let html = #######""" <del> *foo* </del> """####### let document = try Document(markdown) let actual = document.render(format: .html, options: [.unsafe]) let expected = html XCTAssertEqual(actual, expected) } func testExample137() throws { let markdown = #######""" <del> *foo* </del> """####### let html = #######""" <del> <p><em>foo</em></p> </del> """####### let document = try Document(markdown) let actual = document.render(format: .html, options: [.unsafe]) let expected = html XCTAssertEqual(actual, expected) } func testExample138() throws { let markdown = #######""" <del>*foo*</del> """####### let html = #######""" <p><del><em>foo</em></del></p> """####### let document = try Document(markdown) let actual = document.render(format: .html, options: [.unsafe]) let expected = html XCTAssertEqual(actual, expected) } func testExample139() throws { let markdown = #######""" <pre language="haskell"><code> import Text.HTML.TagSoup main :: IO () main = print $ parseTags tags </code></pre> okay """####### let html = #######""" <pre language="haskell"><code> import Text.HTML.TagSoup main :: IO () main = print $ parseTags tags </code></pre> <p>okay</p> """####### let document = try Document(markdown) let actual = document.render(format: .html, options: [.unsafe]) let expected = html XCTAssertEqual(actual, expected) } func testExample140() throws { let markdown = #######""" <script type="text/javascript"> // JavaScript example document.getElementById("demo").innerHTML = "Hello JavaScript!"; </script> okay """####### let html = #######""" <script type="text/javascript"> // JavaScript example document.getElementById("demo").innerHTML = "Hello JavaScript!"; </script> <p>okay</p> """####### let document = try Document(markdown) let actual = document.render(format: .html, options: [.unsafe]) let expected = html XCTAssertEqual(actual, expected) } func testExample141() throws { let markdown = #######""" <style type="text/css"> h1 {color:red;} p {color:blue;} </style> okay """####### let html = #######""" <style type="text/css"> h1 {color:red;} p {color:blue;} </style> <p>okay</p> """####### let document = try Document(markdown) let actual = document.render(format: .html, options: [.unsafe]) let expected = html XCTAssertEqual(actual, expected) } func testExample142() throws { let markdown = #######""" <style type="text/css"> foo """####### let html = #######""" <style type="text/css"> foo """####### let document = try Document(markdown) let actual = document.render(format: .html, options: [.unsafe]) let expected = html XCTAssertEqual(actual, expected) } func testExample143() throws { let markdown = #######""" > <div> > foo bar """####### let html = #######""" <blockquote> <div> foo </blockquote> <p>bar</p> """####### let document = try Document(markdown) let actual = document.render(format: .html, options: [.unsafe]) let expected = html XCTAssertEqual(actual, expected) } func testExample144() throws { let markdown = #######""" - <div> - foo """####### let html = #######""" <ul> <li> <div> </li> <li>foo</li> </ul> """####### let document = try Document(markdown) let actual = document.render(format: .html, options: [.unsafe]) let expected = html XCTAssertEqual(actual, expected) } func testExample145() throws { let markdown = #######""" <style>p{color:red;}</style> *foo* """####### let html = #######""" <style>p{color:red;}</style> <p><em>foo</em></p> """####### let document = try Document(markdown) let actual = document.render(format: .html, options: [.unsafe]) let expected = html XCTAssertEqual(actual, expected) } func testExample146() throws { let markdown = #######""" <!-- foo -->*bar* *baz* """####### let html = #######""" <!-- foo -->*bar* <p><em>baz</em></p> """####### let document = try Document(markdown) let actual = document.render(format: .html, options: [.unsafe]) let expected = html XCTAssertEqual(actual, expected) } func testExample147() throws { let markdown = #######""" <script> foo </script>1. *bar* """####### let html = #######""" <script> foo </script>1. *bar* """####### let document = try Document(markdown) let actual = document.render(format: .html, options: [.unsafe]) let expected = html XCTAssertEqual(actual, expected) } func testExample148() throws { let markdown = #######""" <!-- Foo bar baz --> okay """####### let html = #######""" <!-- Foo bar baz --> <p>okay</p> """####### let document = try Document(markdown) let actual = document.render(format: .html, options: [.unsafe]) let expected = html XCTAssertEqual(actual, expected) } func testExample149() throws { let markdown = #######""" <?php echo '>'; ?> okay """####### let html = #######""" <?php echo '>'; ?> <p>okay</p> """####### let document = try Document(markdown) let actual = document.render(format: .html, options: [.unsafe]) let expected = html XCTAssertEqual(actual, expected) } func testExample150() throws { let markdown = #######""" <!DOCTYPE html> """####### let html = #######""" <!DOCTYPE html> """####### let document = try Document(markdown) let actual = document.render(format: .html, options: [.unsafe]) let expected = html XCTAssertEqual(actual, expected) } func testExample151() throws { let markdown = #######""" <![CDATA[ function matchwo(a,b) { if (a < b && a < 0) then { return 1; } else { return 0; } } ]]> okay """####### let html = #######""" <![CDATA[ function matchwo(a,b) { if (a < b && a < 0) then { return 1; } else { return 0; } } ]]> <p>okay</p> """####### let document = try Document(markdown) let actual = document.render(format: .html, options: [.unsafe]) let expected = html XCTAssertEqual(actual, expected) } func testExample152() throws { let markdown = #######""" <!-- foo --> <!-- foo --> """####### let html = #######""" <!-- foo --> <pre><code>&lt;!-- foo --&gt; </code></pre> """####### let document = try Document(markdown) let actual = document.render(format: .html, options: [.unsafe]) let expected = html XCTAssertEqual(actual, expected) } func testExample153() throws { let markdown = #######""" <div> <div> """####### let html = #######""" <div> <pre><code>&lt;div&gt; </code></pre> """####### let document = try Document(markdown) let actual = document.render(format: .html, options: [.unsafe]) let expected = html XCTAssertEqual(actual, expected) } func testExample154() throws { let markdown = #######""" Foo <div> bar </div> """####### let html = #######""" <p>Foo</p> <div> bar </div> """####### let document = try Document(markdown) let actual = document.render(format: .html, options: [.unsafe]) let expected = html XCTAssertEqual(actual, expected) } func testExample155() throws { let markdown = #######""" <div> bar </div> *foo* """####### let html = #######""" <div> bar </div> *foo* """####### let document = try Document(markdown) let actual = document.render(format: .html, options: [.unsafe]) let expected = html XCTAssertEqual(actual, expected) } func testExample156() throws { let markdown = #######""" Foo <a href="bar"> baz """####### let html = #######""" <p>Foo <a href="bar"> baz</p> """####### let document = try Document(markdown) let actual = document.render(format: .html, options: [.unsafe]) let expected = html XCTAssertEqual(actual, expected) } func testExample157() throws { let markdown = #######""" <div> *Emphasized* text. </div> """####### let html = #######""" <div> <p><em>Emphasized</em> text.</p> </div> """####### let document = try Document(markdown) let actual = document.render(format: .html, options: [.unsafe]) let expected = html XCTAssertEqual(actual, expected) } func testExample158() throws { let markdown = #######""" <div> *Emphasized* text. </div> """####### let html = #######""" <div> *Emphasized* text. </div> """####### let document = try Document(markdown) let actual = document.render(format: .html, options: [.unsafe]) let expected = html XCTAssertEqual(actual, expected) } func testExample159() throws { let markdown = #######""" <table> <tr> <td> Hi </td> </tr> </table> """####### let html = #######""" <table> <tr> <td> Hi </td> </tr> </table> """####### let document = try Document(markdown) let actual = document.render(format: .html, options: [.unsafe]) let expected = html XCTAssertEqual(actual, expected) } func testExample160() throws { let markdown = #######""" <table> <tr> <td> Hi </td> </tr> </table> """####### let html = #######""" <table> <tr> <pre><code>&lt;td&gt; Hi &lt;/td&gt; </code></pre> </tr> </table> """####### let document = try Document(markdown) let actual = document.render(format: .html, options: [.unsafe]) let expected = html XCTAssertEqual(actual, expected) } }
19.277164
72
0.424122
4b0fee6cddcb70d5b1031f5dbce38ebb83e5e7e8
8,465
// // QuoteViewController.swift // Stoic Daily // // Created by Justin Kuepper on 11/8/18. // Copyright © 2018 Justin Kuepper. All rights reserved. // import UIKit import UserNotifications import CoreData class QuoteViewController: UIViewController { @IBOutlet weak var quoteLabel: UILabel! @IBOutlet weak var dateButton: UIButton! @IBOutlet weak var bylineLabel: UILabel! @IBOutlet weak var shareButton: UIButton! struct Quote: Decodable { var id: String var date: String var title: String var quote: String var byline: String var detail: String } override func viewDidLoad() { super.viewDidLoad() // Set or retrieve the daily quote. let quote = getQuote() // Set styling for the quote text. let attString = NSMutableAttributedString(string: quote!.quote) let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineSpacing = 10 attString.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range:NSMakeRange(0, attString.length)) quoteLabel.attributedText = attString quoteLabel.font = UIFont(name: "Hiragino Mincho ProN W3", size: 30) // Set date and byline strings. dateButton.setTitle(getDateString(), for: .normal) bylineLabel.text = quote!.byline // Size the quote text to fit height. quoteLabel.resizeToFitHeight() // Fade in the quote and byline text. quoteLabel.alpha = 0 bylineLabel.alpha = 0 quoteLabel.fadeIn() bylineLabel.fadeIn() // Style quote button. // This is a future button that will change the date when there's a quote for every day. shareButton.layer.borderWidth = 0.8 shareButton.layer.borderColor = UIColor.lightGray.cgColor shareButton.layer.cornerRadius = 5 // Detect tap to show details. let tapAction = UITapGestureRecognizer() self.view.isUserInteractionEnabled = true self.view.addGestureRecognizer(tapAction) tapAction.addTarget(self, action: #selector(actionTapped(_:))) } // Retrieves and formats the current date. func getDate() -> String { let date = Date() let formatter = DateFormatter() formatter.dateFormat = "MM/dd" let result = formatter.string(from: date) return result } // Retrieves and formats the current date string. func getDateString() -> String { let date = Date() let formatter = DateFormatter() formatter.dateFormat = "MMMM d" let result = formatter.string(from: date).uppercased() return result } // Retrieves or sets a quote for the day. func getQuote() -> Quote? { let currentDate = getDateString() let appDelegate = UIApplication.shared.delegate as! AppDelegate let context = appDelegate.persistentContainer.viewContext let fetchQuote = NSFetchRequest<NSFetchRequestResult>(entityName: "Quotes") fetchQuote.predicate = NSPredicate(format: "quoteDate == %@", currentDate) fetchQuote.fetchLimit = 1 let existingQuotes = try! context.fetch(fetchQuote) as! [NSManagedObject] print(existingQuotes) if existingQuotes.count > 0 { do { let db = Bundle.main.url(forResource: "quotes", withExtension: "json")! let decoder = JSONDecoder() let data = try Data(contentsOf: db) let quotes = try decoder.decode([Quote].self, from: data) let existingQuote = existingQuotes.first!.value(forKey: "quoteId") as! String let quote = quotes.filter{ $0.id == existingQuote } return quote[0] } catch { print(error) return nil } } else { do { clearQuotes() let db = Bundle.main.url(forResource: "quotes", withExtension: "json")! let decoder = JSONDecoder() let data = try Data(contentsOf: db) let quotes = try decoder.decode([Quote].self, from: data) let quote = quotes.randomElement()! let quoteEntity = NSEntityDescription.entity(forEntityName: "Quotes", in: context)! let savedQuote = NSManagedObject(entity: quoteEntity, insertInto: context) savedQuote.setValue(quote.id, forKey: "quoteId") savedQuote.setValue(currentDate, forKey: "quoteDate") do { try context.save() } catch let error as NSError { print("Could not save. \(error), \(error.userInfo)") } return quote } catch { print(error) return nil } } } // Clear all previous quotes to save space. func clearQuotes() { let appDelegate = UIApplication.shared.delegate as! AppDelegate let context = appDelegate.persistentContainer.viewContext let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Quotes") request.returnsObjectsAsFaults = false do { let result = try context.fetch(request) for data in result as! [NSManagedObject] { context.delete(data) } } catch { print("Failed to delete data.") } } // Handle the tap to show detail view. @objc func actionTapped(_ sender: UITapGestureRecognizer) { let vc = self.storyboard?.instantiateViewController(withIdentifier: "detailView") as! DetailViewController vc.modalTransitionStyle = .flipHorizontal vc.quoteTitle = getQuote()!.title vc.quoteDetails = getQuote()!.detail self.present(vc, animated: true, completion: nil) } // Open dialog to share quote. @IBAction func shareQuote(_ sender: Any) { let quote = getQuote()!.quote let shareObject = [quote] let activityVC = UIActivityViewController(activityItems: shareObject as [Any], applicationActivities: nil) activityVC.popoverPresentationController?.sourceView = sender as? UIView self.present(activityVC, animated: true, completion: nil) } // This could eventually be used to change the date. @IBAction func changeDate(_ sender: UIButton) { } // Change the title of the button and update quote. @objc func dateChanged(_ sender: UIDatePicker) { } } // Extention to fade in and out text. extension UIView { func fadeIn(duration: TimeInterval = 1.0, delay: TimeInterval = 0.0, completion: @escaping ((Bool) -> Void) = {(finished: Bool) -> Void in}) { UIView.animate(withDuration: duration, delay: delay, options: UIView.AnimationOptions.curveEaseIn, animations: { self.alpha = 1.0 }, completion: completion) } func fadeOut(duration: TimeInterval = 1.0, delay: TimeInterval = 3.0, completion: @escaping (Bool) -> Void = {(finished: Bool) -> Void in}) { UIView.animate(withDuration: duration, delay: delay, options: UIView.AnimationOptions.curveEaseIn, animations: { self.alpha = 0.0 }, completion: completion) } } // Extension to resize font to fit height. extension UILabel { func resizeToFitHeight(){ var currentfontSize = font.pointSize let minFontsize = CGFloat(5) let constrainedSize = CGSize(width: frame.width, height: CGFloat.greatestFiniteMagnitude) while (currentfontSize >= minFontsize){ let newFont = font.withSize(currentfontSize) let attributedText: NSAttributedString = NSAttributedString(string: text!, attributes: [NSAttributedString.Key.font: newFont]) let rect: CGRect = attributedText.boundingRect(with: constrainedSize, options: .usesLineFragmentOrigin, context: nil) let size: CGSize = rect.size if (size.height < frame.height - 10) { font = newFont break; } currentfontSize = currentfontSize - 1 } if (currentfontSize == minFontsize){ font = font.withSize(currentfontSize) } } }
38.477273
146
0.611341
c13c4a6e363ff97583f570fffc5f0e3f82fceef8
2,178
// // Number.swift // EllipticCurveKit // // Created by Alexander Cyon on 2018-07-06. // Copyright © 2018 Alexander Cyon. All rights reserved. // import Foundation import BigInt public typealias Number = BigInt public extension Number { public init(sign: Number.Sign = .plus, _ words: [Number.Word]) { let magnitude = Number.Magnitude(words: words) self.init(sign: sign, magnitude: magnitude) } public init(sign: Number.Sign = .plus, data: Data) { self.init(sign: sign, Number.Magnitude(data)) } public init(sign: Number.Sign = .plus, _ magnitude: Number.Magnitude) { self.init(sign: sign, magnitude: magnitude) } public init?(hexString: String) { var hexString = hexString if hexString.starts(with: "0x") { hexString = String(hexString.dropFirst(2)) } self.init(hexString, radix: 16) } public init?(decimalString: String) { self.init(decimalString, radix: 10) } var isEven: Bool { guard self.sign == .plus else { fatalError("what to do when negative?") } return magnitude[bitAt: 0] == false } func asHexString(uppercased: Bool = true) -> String { return toString(uppercased: uppercased, radix: 16) } func asDecimalString(uppercased: Bool = true) -> String { return toString(uppercased: uppercased, radix: 10) } func toString(uppercased: Bool = true, radix: Int) -> String { let stringRepresentation = String(self, radix: radix) guard uppercased else { return stringRepresentation } return stringRepresentation.uppercased() } func asHexStringLength64(uppercased: Bool = true) -> String { var hexString = toString(uppercased: uppercased, radix: 16) while hexString.count < 64 { hexString = "0\(hexString)" } return hexString } func as256bitLongData() -> Data { return Data(hex: asHexStringLength64()) } func asTrimmedData() -> Data { return self.magnitude.serialize() } } extension Data { func toNumber() -> Number { return Number(data: self) } }
26.560976
81
0.625344
21e19f8ac02a1dad9d7b027d8791f05c12462f57
474
// // URL+Helpers.swift // iTunesSearch // // Created by Tshaka Lekholoane on 22/06/2019. // Copyright © 2019 Caleb Hicks. All rights reserved. // import Foundation extension URL { func withQueries(_ queries: [String: String]) -> URL? { var components = URLComponents(url: self, resolvingAgainstBaseURL: true) components?.queryItems = queries.map { URLQueryItem(name: $0.0, value: $0.1) } return components?.url } }
23.7
80
0.637131
64167d2c4b14b153810205badc8b8964dd65e1c4
733
// // AnswerShippingQuery.swift // tl2swift // // Created by Code Generator // import Foundation /// Sets the result of a shipping query; for bots only public struct AnswerShippingQuery: Codable { /// An error message, empty on success public let errorMessage: String? /// Available shipping options public let shippingOptions: [ShippingOption]? /// Identifier of the shipping query public let shippingQueryId: TdInt64? public init( errorMessage: String?, shippingOptions: [ShippingOption]?, shippingQueryId: TdInt64? ) { self.errorMessage = errorMessage self.shippingOptions = shippingOptions self.shippingQueryId = shippingQueryId } }
20.942857
54
0.680764
8aec54a9ce4a798ff967c1f633d0cb1ed6eaef81
2,186
// // NoteManagement.swift // LongNguyen_NoteiOS // // Created by Long Nguyen on 7/10/17. // Copyright © 2017 Long Nguyen. All rights reserved. // import Foundation import UIKit import CoreData class NoteManagement { let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext // Create a note func createNote(title: String, content: String, isOffline: Bool) -> NoteModel { let newNote = NSEntityDescription.insertNewObject(forEntityName: "NoteModel", into: context) as! NoteModel newNote.title = title newNote.content = content newNote.isUpdate = false newNote.isDelete = false newNote.isOffline = isOffline return newNote } // Gets a note by id func getById(id: NSManagedObjectID) -> NoteModel? { return context.object(with: id) as? NoteModel } func getAll() -> [NoteModel]{ return get(withPredicate: NSPredicate(value:true)) } // Gets all that fulfill the specified predicate. func get(withPredicate queryPredicate: NSPredicate) -> [NoteModel]{ let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "NoteModel") fetchRequest.predicate = queryPredicate do { let response = try context.fetch(fetchRequest) return response as! [NoteModel] } catch let error as NSError { // failure print(error) return [NoteModel]() } } // Updates a note func update(updatedNote: NoteModel){ if let note = getById(id: updatedNote.objectID){ note.title = updatedNote.title note.content = updatedNote.content } } // Deletes a note func delete(id: NSManagedObjectID){ if let noteToDelete = getById(id: id){ context.delete(noteToDelete) } } // Saves all changes func saveChanges(){ do{ try context.save() } catch let error as NSError { // failure print(error) } } }
26.02381
114
0.591949
7af9ca39856956e9b9252a0cc275722c72aa5e21
830
// swift-tools-version:5.2 /** # Gamma16 An emulator written in Swift of a legacy version of Sigma16. Copyright (c) Yu-Sung Loyi Hsu 2021 Licensed under MIT license, see LICENSE file for more details. */ import PackageDescription let package = Package( name: "Gamma16", products: [ .library(name: "Gamma16Core", targets: ["Gamma16Core"]), .executable(name: "gamma16-cli", targets: ["Gamma16Cli"]) ], dependencies: [ .package(url: "https://github.com/apple/swift-argument-parser.git", from: "0.4.1") ], targets: [ .target(name: "Gamma16Core"), .target(name: "Gamma16Cli", dependencies: ["Gamma16Core", .product(name: "ArgumentParser", package: "swift-argument-parser")]), .testTarget(name: "Gamma16CoreTests", dependencies: ["Gamma16Core"]), ] )
29.642857
135
0.649398
fb90e7160d0fa4747a90ac362c319b3755df44e2
934
// // CollectionViewExtension.swift // EasyReader // // Created by roy on 2022/1/20. // import UIKit import SnapKit extension UIView { func showPlaceholder() { guard subviews.filter({ $0.tag == 1001 }).isEmpty else { return } guard let phView = UIStoryboard(name: "Main", bundle: nil) .instantiateViewController(withIdentifier: "ERListPlaceholderViewController") .view else { return } phView.tag = 1001 addSubview(phView) phView.translatesAutoresizingMaskIntoConstraints = false phView.snp.makeConstraints { make in make.topMargin.equalTo(self.snp.topMargin) make.leading.trailing.bottom.equalToSuperview() } } func removePlaceholder() { guard let phView = subviews.filter({ $0.tag == 1001 }).first else { return } phView.removeFromSuperview() } }
25.944444
89
0.61349
2331c9eed95a23891633c643574ab39bf60c8f5f
3,201
// // UIView+Create.swift // Pascal // // Created by Helena McGahagan on 2/12/19. // Copyright © 2019 Evidation Health, Inc. All rights reserved. // import UIKit /** Factory methods for creating views that will be laid out programatically. * The view's translatesAutoresizingMaskIntoConstraints property is automatically set to false. */ extension UIView { public static let defaultSeparatorHeight = ceil(UIScreen.main.scale * 0.5) / UIScreen.main.scale public static func createView(frame: CGRect = .zero) -> UIView { let view = self.init(frame: frame) view.translatesAutoresizingMaskIntoConstraints = false return view } public static func createHorizontalSeparationLine(color: UIColor = UIColor.gray, height: CGFloat = UIView.defaultSeparatorHeight) -> UIView { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = color view.setHeight(height) return view } public static func createVerticalSeparationLine(color: UIColor = UIColor.gray, width: CGFloat = UIView.defaultSeparatorHeight) -> UIView { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = color view.setWidth(width) return view } /// Add single border to the given edge /// - Parameter edge: Edge to add border. Only accepting top, bottom, left, and right /// - Parameter color: Color of the border /// - Parameter dimension: Height of the border if edge is top or bottom, otherwise the width of the border /// - Returns: The border view @discardableResult public func addBorder(to edge: UIRectEdge, color: UIColor, dimension: CGFloat = defaultSeparatorHeight, leftInset: CGFloat = 0) -> UIView? { switch edge { case .top, .bottom: let border = UIView.createHorizontalSeparationLine(color: color, height: dimension) self.addSubview(border) self.setEqualLeft(subview: border, padding: leftInset) self.setEqualRight(subview: border) if edge == .top { self.setEqualTop(subview: border) } else { self.setEqualBottom(subview: border) } return border case .left, .right: let border = UIView.createVerticalSeparationLine(color: color, width: dimension) self.addSubview(border) self.setEqualTop(subview: border) self.setEqualBottom(subview: border) if edge == .left { self.setEqualLeft(subview: border) } else { self.setEqualRight(subview: border) } return border default: return nil } } } extension UIButton { public static func createButton(frame: CGRect = .zero, type: UIButton.ButtonType = .custom) -> UIButton { let view = self.init(type: type) view.frame = frame view.translatesAutoresizingMaskIntoConstraints = false return view } }
34.793478
145
0.628866
5de63fdc0ab8df9238caf9384c496e1ff0fb4559
3,815
// // ___FILENAME___ // ___PROJECTNAME___ // // Created by ___FULLUSERNAME___ on ___DATE___. // ___COPYRIGHT___ // // This file was generated by Project Xcode Templates // Created by Wahyu Ady Prasetyo, // import UIKit class ZoomSlider: UISlider { private var zoomLabel: UILabel = { let label = UILabel(frame: CGRect(x: 0, y: 0, width: 34, height: 34)) label.textAlignment = .center label.font = UIFont.systemFont(ofSize: 11) label.text = "1x" label.backgroundColor = .darkGray label.textColor = .white label.layer.borderColor = UIColor.white.cgColor label.layer.borderWidth = 1.5 label.layer.cornerRadius = 17 label.clipsToBounds = true return label }() private var minusView: UILabel { let label = UILabel() label.textAlignment = .center label.text = "-" label.textColor = .white label.font = UIFont.boldSystemFont(ofSize: 20) label.sizeToFit() let maxSize = max(label.frame.size.width, label.frame.size.height) label.frame.size = CGSize(width: maxSize, height: maxSize) return label } private var plusView: UILabel { let label = UILabel() label.textAlignment = .center label.text = "+" label.textColor = .white label.font = UIFont.boldSystemFont(ofSize: 20) label.sizeToFit() let maxSize = max(label.frame.size.width, label.frame.size.height) label.frame.size = CGSize(width: maxSize, height: maxSize) return label } override var value: Float { didSet { sliderValueChanged(self) } } init() { super.init(frame: .zero) setupMethod() setupView() } override init(frame: CGRect) { super.init(frame: frame) setupMethod() setupView() } required init?(coder: NSCoder) { super.init(coder: coder) setupMethod() setupView() } private func setupView() { setThumbImage(zoomLabel.image, for: UIControl.State()) minimumValueImage = minusView.image maximumValueImage = plusView.image minimumTrackTintColor = UIColor.lightGray.withAlphaComponent(0.5) maximumTrackTintColor = UIColor.lightGray.withAlphaComponent(0.5) } private func setupMethod() { self.addTarget(self, action: #selector(sliderValueChanged(_:)), for: .valueChanged) } @objc private func sliderValueChanged(_ slider: ZoomSlider) { let text = String(format: "%.1fx", value).replacingOccurrences(of: ".0", with: "") zoomLabel.text = text setThumbImage(zoomLabel.image, for: UIControl.State()) show() } private func show() { self.alpha = 1.0 self.isHidden = false NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(hide), object: nil) self.layer.removeAllAnimations() if value > 1 { return } perform(#selector(hide), with: nil, afterDelay: 4) } @objc private func hide() { UIView.animate(withDuration: 0.5, delay: 0, options: .allowUserInteraction, animations: { self.alpha = 0.0 }) { (isFinished) in if isFinished { self.isHidden = true } } } } private extension UILabel { var image: UIImage? { UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, 0.0) self.layer.render(in: UIGraphicsGetCurrentContext()!) let img = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return img } }
28.259259
104
0.595282
e4da51047689eed381282c22ddab2d177e08cc91
190
// // APIError.swift // AnSplash // // Created by Aaron Lee on 2020-12-10. // import Foundation enum APIError: Error { case decodingError case httpError(Int) case unknown }
12.666667
39
0.657895
fcb6a52e7a70eef519d4ad37d935cc4d2c22234c
1,004
// // EventsModel.swift // PinPoint // // Created by Aaron Cabreja on 4/8/19. // Copyright © 2019 Pursuit. All rights reserved. // import Foundation struct EventsInArea: Codable{ let events: [Event] } struct Event: Codable { let name: NameOfEvent? let description: DescriptionOfEvent? let url: String? let start: StartTimeOfEvent? let end: EndTimeOfEvent? let created: String? let changed: String? let published: String? let capacity: String? let status: String? let currency: String? let logo: LogoOfTheEvent? let is_free: Bool? } struct NameOfEvent: Codable { let text: String? } struct DescriptionOfEvent: Codable { let text: String? } struct StartTimeOfEvent: Codable { let timezone: String let utc: String } struct EndTimeOfEvent: Codable { let timezone: String let utc: String } struct LogoOfTheEvent: Codable { let original: PictureOfTheEvent } struct PictureOfTheEvent: Codable { let url: String }
20.489796
50
0.690239
6229b0626b4e91d75aaf7beb9400fe437b6a5caa
3,535
/* This source file is part of the Swift.org open source project Copyright (c) 2021 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See https://swift.org/LICENSE.txt for license information See https://swift.org/CONTRIBUTORS.txt for Swift project authors */ import Foundation extension Dictionary where Key == String, Value == Any { /// Returns the value for the given key decoded as the requested type. func decode<T>(_ expectedType: T.Type, forKey key: String) throws -> T where T : Decodable { guard let value = self[key] else { throw TypedValueError.missingValue(key: key) } // First attempt to just cast the value as the requested type if let castedValue = value as? T { return castedValue } // If that fails, attempt to decode it. Since we know T is Decodable, // even if the given value cannot be _directly_ cast to T, it's possible // that it can be decoded as T. // // For example, the String "1.0.0" cannot be cast directly to `Version`, // but it can be _decoded_ to `Version`. do { let data = try JSONSerialization.data(withJSONObject: value, options: .fragmentsAllowed) return try JSONDecoder().decode(T.self, from: data) } catch { // Decoding failed as well, throw an error indicating that we were given the wrong type. throw TypedValueError.wrongType(key: key, expected: T.self, actual: type(of: value)) } } /// Returns the value for the given key decoded as the requested type, if present. func decodeIfPresent<T>(_ expectedType: T.Type, forKey key: String) throws -> T? where T : Decodable { guard self.keys.contains(key) else { return nil } return try decode(expectedType, forKey: key) } } /// A set of errors related to reading dictionary values as specific types. enum TypedValueError: DescribedError { /// The requested value is missing. case missingValue(key: String) /// The requested value is of the wrong type. case wrongType(key: String, expected: Any.Type, actual: Any.Type) /// One or more required ``DocumentationBundle.Info.Key``s are missing. case missingRequiredKeys([DocumentationBundle.Info.CodingKeys]) var errorDescription: String { switch self { case let .missingValue(key): return "Missing value for key '\(key.singleQuoted)'." case let .wrongType(key, expected, actual): return "Type mismatch for key '\(key.singleQuoted)'. Expected '\(expected)', but found '\(actual)'." case .missingRequiredKeys(let keys): var errorMessage = "" for key in keys { errorMessage += """ \n Missing value for \(key.rawValue.singleQuoted). """ if let argumentName = key.argumentName { errorMessage += """ Use the \(argumentName.singleQuoted) argument or add \(key.rawValue.singleQuoted) to the bundle Info.plist. """ } else { errorMessage += """ Add \(key.rawValue.singleQuoted) to the bundle Info.plist. """ } } return errorMessage } } }
39.719101
127
0.594908
62e6fbb7a124eccd28f563f33d0b3694c2e6f14d
3,371
/** * Copyright (c) 2017 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. * * 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 CallKit private let sharedManager = CallManager.init() class CallManager: NSObject { var reloadTable: (() -> Void)? var updateDelegates: (() -> Void)? var client: SINClient var audioController: SINAudioController { return client.audioController() } class var sharedInstance : CallManager { return sharedManager } private(set) var calls = [SINCall]() var currentCall: SINCall? { didSet { self.updateDelegates?() } } var currentCallStatus: SINCallState { return currentCall?.state ?? SINCallState.ended } override init() { client = Sinch.client(withApplicationKey: APPLICATION_KEY, applicationSecret: APPLICATION_SECRET, environmentHost: "sandbox.sinch.com", userId: AppDelegate.shared.user) client.setSupportCalling(true) client.setSupportMessaging(false) client.enableManagedPushNotifications() client.delegate = AppDelegate.shared // to be reviewed client.call().delegate = AppDelegate.shared // to be discussed client.start() client.startListeningOnActiveConnection() super.init() } func callWithHandle(_ handle: String) -> SINCall? { guard let index = calls.index(where: { $0.remoteUserId == handle }) else { return nil } return calls[index] } func callWithUUID(uuid: UUID) -> SINCall? { guard let index = calls.index(where: { UUID(uuidString: $0.callId)! == uuid }) else { return nil } return calls[index] } func addCall() { if let call = currentCall { calls.append(call) currentCall = nil reloadTable?() } } func addIncoming(call: SINCall) { calls.append(call) reloadTable?() } func remove(call: SINCall) { guard let index = calls.index(where: { $0 === call }) else { return } calls.remove(at: index) reloadTable?() } func removeAllCalls() { calls.removeAll() reloadTable?() } }
31.212963
180
0.63453
d67de5bd5e378518a255a6208bc22ae565bbce20
1,605
// // TouchHandlerView.swift // Coloretta // // Created by Bohdan Savych on 2/22/20. // Copyright © 2020 Padres. All rights reserved. // import UIKit final class TouchHandlerView: UIView { var touchBeganEvent: ((_ point: CGPoint, _ velocity: CGPoint) -> Void)? var touchMovedEvent: ((_ point: CGPoint, _ velocity: CGPoint) -> Void)? var touchesEnded: ((_ point: CGPoint, _ velocity: CGPoint) -> Void)? var touchesCancelled: ((_ point: CGPoint, _ velocity: CGPoint) -> Void)? var onTap: ((CGPoint) -> Void)? lazy var panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(self.onPan(sender:))) lazy var tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.onTap(sender:))) init() { super.init(frame: .zero) self.configure() } required init?(coder: NSCoder) { nil } func configure() { self.addGestureRecognizer(self.panGestureRecognizer) self.addGestureRecognizer(self.tapGestureRecognizer) self.isUserInteractionEnabled = true } @objc func onPan(sender: UIPanGestureRecognizer) { let state = sender.state let point = sender.location(in: self) let velocity = sender.velocity(in: self) switch state { case .began: self.touchBeganEvent?(point, velocity) case .changed: self.touchMovedEvent?(point, velocity) case .ended: self.touchesEnded?(point, velocity) default: self.touchesCancelled?(point, velocity) } } @objc func onTap(sender: UITapGestureRecognizer) { let point = sender.location(in: self) self.onTap?(point) } }
28.157895
110
0.692835
ff79b590f5fc5929e3243b1f606da55d9054bef8
313
import Fluent import Vapor func routes(_ app: Application) throws { app.get { req in return "It works!" } app.get("hello") { req -> String in return "Hello, world!" } try app.register(collection: TodoController()) try app.register(collection: SubjectController()) }
19.5625
53
0.623003
089e336d3de61af13c755ea96e89f64f469aed2f
457
// // MealViewModel.swift // gelato // // Created by EvanTsai on 2017/12/26. // Copyright © 2017年 Zurasta. All rights reserved. // import Foundation class MealViewModel { func addMeal() { let cartItem = CartItem() cartItem.id = Int(arc4random()) cartItem.name = "Beef Sandwich" cartItem.price = 10.2 RealmManager.sharedInstance.addCartItem(item: cartItem) } }
16.925926
63
0.579869
dd8df830178ade7a6a5a2fbe46bc9239878386b2
3,203
/** _____ _ _ _____ ______ _ | __ \ | | | | | __ \ | ____| | | | |__) | | |__| | | |__) | | |__ _ __ __ _ _ __ ___ _____ _____ _ __| | __ | ___/ | __ | | ___/ | __| '__/ _` | '_ ` _ \ / _ \ \ /\ / / _ \| '__| |/ / | | | | | | | | _ | | | | | (_| | | | | | | __/\ V V / (_) | | | < |_| |_| |_| |_| (_) |_| |_| \__,_|_| |_| |_|\___| \_/\_/ \___/|_| |_|\_\ Copyright (c) 2016 Wesley de Groot (http://www.wesleydegroot.nl), WDGWV (http://www.wdgwv.com) Variable prefixes: PFS = PHP.Framework Shared PFT = PHP.Framework Tests (internal) PFI = PHP.Framework Internal PFU = PHP.Framework Unspecified usage: php.the_php_function(and, parameters, ofcourse) documentation: http://wdg.github.io/php.framework/ wiki: https://github.com/wdg/php.framework/wiki questions/bugs: https://github.com/wdg/php.framework/issues --------------------------------------------------- File: levenshtein.swift Created: 16-FEB-2016 Creator: Wesley de Groot | g: @wdg | t: @wesdegroot Issue: #1 (String Functions) Prefix: N/A --------------------------------------------------- */ import Foundation /** **PHP.Framework** \ *PHP In Swift* Levenshtein calculator class */ public class calculateLevenshtein { /** Does nothing spectacular */ public init() { } /** Internal function min. - Parameter numbers: Int... - Returns: Int */ internal func min(_ numbers: Int...) -> Int { // return numbers.reduce(numbers[0], combine: {$0 < $1 ? $0 : $1}) //... return 0 } /** Internal class Array2D\ *create a 2 dimensional array* */ internal class Array2D { var cols: Int, rows: Int var matrix: [Int] init(cols: Int, rows: Int) { self.cols = cols self.rows = rows matrix = Array(repeating: 0, count: cols * rows) } subscript(col: Int, row: Int) -> Int { get { return matrix[cols * row + col] } set { matrix[cols * row + col] = newValue } } func colCount() -> Int { return self.cols } func rowCount() -> Int { return self.rows } } /** Calculate Levenshtein distance between two strings - Parameter aStr: The First String - Parameter bStr: The Second String - Returns: The String */ public func calc(_ aStr: String, _ bStr: String) -> Int { let a = Array(aStr.utf16) let b = Array(bStr.utf16) var dist = Array2D(cols: a.count + 1, rows: b.count + 1) if (self.lsNoop(dist)) { dist = Array2D(cols: a.count + 1, rows: b.count + 1) } for i in 1...a.count { dist[i, 0] = i } for j in 1...b.count { dist[0, j] = j } for i in 1...a.count { for j in 1...b.count { if a[i - 1] == b[j - 1] { dist[i, j] = dist[i - 1, j - 1] // noop } else { dist[i, j] = min( dist[i - 1, j] + 1, // deletion dist[i, j - 1] + 1, // insertion dist[i - 1, j - 1] + 1 // substitution ) } } } return dist[a.count, b.count] } /** Does nothing spectacular - Parameter x: Any. */ func lsNoop(_ x: Any...) -> Bool {return false} }
21.353333
95
0.511708
e2630af599a072180ad0b3a7334a11a0813af641
1,209
// // SearchTeam.swift // EAO // // Created by Amir Shayegh on 2018-04-03. // Copyright © 2018 FreshWorks. All rights reserved. // class TeamSearch { lazy var vc: TeamSearchViewController = { return UIStoryboard(name: "Team", bundle: Bundle.main).instantiateViewController(withIdentifier: "TeamSearch") as! TeamSearchViewController }() func getVC(teams: [Team], callBack: @escaping ((_ close: Bool,_ team: Team?) -> Void )) -> UIViewController { vc.setup(teams: teams, completion: callBack) return vc } func display(in container: UIView, on viewController: UIViewController) { container.alpha = 1 viewController.addChild(vc) container.addSubview(vc.view) vc.view.frame = container.bounds vc.view.autoresizingMask = [.flexibleWidth, .flexibleHeight] vc.didMove(toParent: viewController) } /** Note: also hides container by setting alpha to 0 */ func remove(from container: UIView, then hide: Bool = true) { vc.willMove(toParent: nil) vc.view.removeFromSuperview() vc.removeFromParent() if hide { container.alpha = 0 } } }
28.785714
147
0.635236
de9bc66845eeaa5c619e356941a70f4a86aa8552
4,652
// // FirebaseExtension.swift // CombineFirestore // // Created by Kumar Shivang on 20/02/20. // Copyright © 2020 Kumar Shivang. All rights reserved. // import FirebaseFirestore import Combine extension Query { struct Publisher: Combine.Publisher { typealias Output = QuerySnapshot typealias Failure = Error private let query: Query private let includeMetadataChanges: Bool init(_ query: Query, includeMetadataChanges: Bool) { self.query = query self.includeMetadataChanges = includeMetadataChanges } func receive<S>(subscriber: S) where S : Subscriber, Publisher.Failure == S.Failure, Publisher.Output == S.Input { let subscription = QuerySnapshot.Subscription(subscriber: subscriber, query: query, includeMetadataChanges: includeMetadataChanges) subscriber.receive(subscription: subscription) } } public func publisher(includeMetadataChanges: Bool = true) -> AnyPublisher<QuerySnapshot, Error> { Publisher(self, includeMetadataChanges: includeMetadataChanges) .eraseToAnyPublisher() } public func publisher<D: Decodable>(includeMetadataChanges: Bool = true, as type: D.Type, documentSnapshotMapper: @escaping (DocumentSnapshot) throws -> D? = DocumentSnapshot.defaultMapper(), querySnapshotMapper: @escaping (QuerySnapshot, (DocumentSnapshot) throws -> D?) -> [D] = QuerySnapshot.defaultMapper()) -> AnyPublisher<[D], Error> { publisher(includeMetadataChanges: includeMetadataChanges) .map { querySnapshotMapper($0, documentSnapshotMapper) } .eraseToAnyPublisher() } public func getDocuments(source: FirestoreSource = .default) -> AnyPublisher<QuerySnapshot, Error> { Future<QuerySnapshot, Error> { [weak self] promise in self?.getDocuments(source: source, completion: { (snapshot, error) in if let error = error { promise(.failure(error)) } else if let snapshot = snapshot { promise(.success(snapshot)) } else { promise(.failure(FirestoreError.nilResultError)) } }) }.eraseToAnyPublisher() } public func getDocuments<D: Decodable>(source: FirestoreSource = .default, as type: D.Type, documentSnapshotMapper: @escaping (DocumentSnapshot) throws -> D? = DocumentSnapshot.defaultMapper(), querySnapshotMapper: @escaping (QuerySnapshot, (DocumentSnapshot) throws -> D?) -> [D] = QuerySnapshot.defaultMapper()) -> AnyPublisher<[D], Error> { getDocuments(source: source) .map { querySnapshotMapper($0, documentSnapshotMapper) } .eraseToAnyPublisher() } } extension QuerySnapshot { fileprivate final class Subscription<SubscriberType: Subscriber>: Combine.Subscription where SubscriberType.Input == QuerySnapshot, SubscriberType.Failure == Error { private var registration: ListenerRegistration? init(subscriber: SubscriberType, query: Query, includeMetadataChanges: Bool) { registration = query.addSnapshotListener (includeMetadataChanges: includeMetadataChanges) { (querySnapshot, error) in if let error = error { subscriber.receive(completion: .failure(error)) } else if let querySnapshot = querySnapshot { DispatchQueue.global(qos: .userInitiated).async { _ = subscriber.receive(querySnapshot) } } else { subscriber.receive(completion: .failure(FirestoreError.nilResultError)) } } } func request(_ demand: Subscribers.Demand) { // We do nothing here as we only want to send events when they occur. // See, for more info: https://developer.apple.com/documentation/combine/subscribers/demand } func cancel() { registration?.remove() registration = nil } } public static func defaultMapper<D: Decodable>() -> (QuerySnapshot, (DocumentSnapshot) throws -> D?) -> [D] { { (snapshot, documentSnapshotMapper) in var dArray: [D] = [] snapshot.documents.forEach { do { if let d = try documentSnapshotMapper($0) { dArray.append(d) } } catch { print("Document snapshot mapper error for \($0.reference.path): \(error)") } } return dArray } } }
41.90991
347
0.622098
793d6376e33708dc183ad28a76fd33d7888e48b2
18,531
@testable import KsApi @testable import Library import Prelude import ReactiveExtensions_TestHelpers import XCTest final class KoalaTests: TestCase { func testDefaultProperties() { let bundle = MockBundle() let client = MockTrackingClient() let config = Config.template |> Config.lens.countryCode .~ "GB" |> Config.lens.locale .~ "en" let device = MockDevice(userInterfaceIdiom: .phone) let screen = MockScreen() let koala = Koala( bundle: bundle, client: client, config: config, device: device, loggedInUser: nil, screen: screen ) koala.trackAppOpen() XCTAssertEqual(["App Open", "Opened App"], client.events) let properties = client.properties.last XCTAssertEqual("Apple", properties?["manufacturer"] as? String) XCTAssertEqual(bundle.infoDictionary?["CFBundleVersion"] as? Int, properties?["app_version"] as? Int) XCTAssertEqual( bundle.infoDictionary?["CFBundleShortVersionString"] as? String, properties?["app_release"] as? String ) XCTAssertNotNil(properties?["model"]) XCTAssertEqual(device.systemName, properties?["os"] as? String) XCTAssertEqual(device.systemVersion, properties?["os_version"] as? String) XCTAssertEqual(UInt(screen.bounds.width), properties?["screen_width"] as? UInt) XCTAssertEqual(UInt(screen.bounds.height), properties?["screen_height"] as? UInt) XCTAssertEqual("kickstarter_ios", properties?["mp_lib"] as? String) XCTAssertEqual("native", properties?["client_type"] as? String) XCTAssertEqual("phone", properties?["device_format"] as? String) XCTAssertEqual("ios", properties?["client_platform"] as? String) XCTAssertNil(properties?["user_uid"]) XCTAssertEqual(false, properties?["user_logged_in"] as? Bool) XCTAssertEqual("GB", properties?["user_country"] as? String) } func testDefaultPropertiesVoiceOver() { let client = MockTrackingClient() let koala = Koala(client: client) withEnvironment(isVoiceOverRunning: { true }) { koala.trackAppOpen() let properties = client.properties.last XCTAssertEqual(true, properties?["is_voiceover_running"] as? Bool) } withEnvironment(isVoiceOverRunning: { false }) { koala.trackAppOpen() let properties = client.properties.last XCTAssertEqual(false, properties?["is_voiceover_running"] as? Bool) } } func testDefaultPropertiesWithLoggedInUser() { let client = MockTrackingClient() let user = User.template |> \.stats.backedProjectsCount .~ 2 |> \.stats.createdProjectsCount .~ 3 |> \.stats.starredProjectsCount .~ 4 |> \.location .~ .template let koala = Koala(client: client, loggedInUser: user) koala.trackAppOpen() XCTAssertEqual(["App Open", "Opened App"], client.events) let properties = client.properties.last XCTAssertEqual(user.id, properties?["user_uid"] as? Int) XCTAssertEqual(true, properties?["user_logged_in"] as? Bool) XCTAssertEqual(user.stats.backedProjectsCount, properties?["user_backed_projects_count"] as? Int) XCTAssertEqual(user.stats.createdProjectsCount, properties?["user_created_projects_count"] as? Int) XCTAssertEqual(user.stats.starredProjectsCount, properties?["user_starred_projects_count"] as? Int) XCTAssertEqual(user.location?.country, properties?["user_country"] as? String) } func testDeviceFormatAndClientPlatform_ForIPhoneIdiom() { let client = MockTrackingClient() let koala = Koala(client: client, device: MockDevice(userInterfaceIdiom: .phone), loggedInUser: nil) koala.trackAppOpen() XCTAssertEqual("phone", client.properties.last?["device_format"] as? String) XCTAssertEqual("ios", client.properties.last?["client_platform"] as? String) } func testDeviceFormatAndClientPlatform_ForIPadIdiom() { let client = MockTrackingClient() let koala = Koala(client: client, device: MockDevice(userInterfaceIdiom: .pad), loggedInUser: nil) koala.trackAppOpen() XCTAssertEqual("tablet", client.properties.last?["device_format"] as? String) XCTAssertEqual("ios", client.properties.last?["client_platform"] as? String) } func testDeviceFormatAndClientPlatform_ForTvIdiom() { let client = MockTrackingClient() let koala = Koala(client: client, device: MockDevice(userInterfaceIdiom: .tv), loggedInUser: nil) koala.trackAppOpen() XCTAssertEqual("tv", client.properties.last?["device_format"] as? String) XCTAssertEqual("tvos", client.properties.last?["client_platform"] as? String) } func testTrackProject() { let client = MockTrackingClient() let koala = Koala(client: client, loggedInUser: nil) let project = Project.template koala.trackProjectShow(project, refTag: .discovery, cookieRefTag: .recommended) XCTAssertEqual(3, client.properties.count) let properties = client.properties.last XCTAssertEqual("Project Page Viewed", client.events.last) XCTAssertEqual(project.stats.backersCount, properties?["project_backers_count"] as? Int) XCTAssertEqual(project.country.countryCode, properties?["project_country"] as? String) XCTAssertEqual(project.country.currencyCode, properties?["project_currency"] as? String) XCTAssertEqual(project.stats.goal, properties?["project_goal"] as? Int) XCTAssertEqual(project.id, properties?["project_pid"] as? Int) XCTAssertEqual(project.stats.pledged, properties?["project_pledged"] as? Int) XCTAssertEqual(project.stats.fundingProgress, properties?["project_percent_raised"] as? Float) XCTAssertNotNil(project.video) XCTAssertEqual(project.category.name, properties?["project_category"] as? String) XCTAssertEqual(project.category._parent?.name, properties?["project_parent_category"] as? String) XCTAssertEqual(project.location.name, properties?["project_location"] as? String) XCTAssertEqual(project.stats.backersCount, properties?["project_backers_count"] as? Int) XCTAssertEqual(24 * 15, properties?["project_hours_remaining"] as? Int) XCTAssertEqual(60 * 60 * 24 * 30, properties?["project_duration"] as? Int) XCTAssertEqual("discovery", properties?["ref_tag"] as? String) XCTAssertEqual("recommended", properties?["referrer_credit"] as? String) XCTAssertEqual(project.creator.id, properties?["creator_uid"] as? Int) XCTAssertEqual( project.creator.stats.backedProjectsCount, properties?["creator_backed_projects_count"] as? Int ) XCTAssertEqual( project.creator.stats.createdProjectsCount, properties?["creator_created_projects_count"] as? Int ) XCTAssertEqual( project.creator.stats.starredProjectsCount, properties?["creator_starred_projects_count"] as? Int ) } func testProjectProperties_LoggedInUser() { let client = MockTrackingClient() let project = Project.template |> Project.lens.personalization.isBacking .~ false <> Project.lens.personalization.isStarred .~ false let loggedInUser = User.template |> \.id .~ 42 let koala = Koala(client: client, loggedInUser: loggedInUser) koala.trackProjectShow(project, refTag: nil, cookieRefTag: nil) XCTAssertEqual(3, client.properties.count) let properties = client.properties.last XCTAssertEqual(false, properties?["user_is_project_creator"] as? Bool) XCTAssertEqual(false, properties?["user_is_backer"] as? Bool) XCTAssertEqual(false, properties?["user_has_starred"] as? Bool) } func testProjectProperties_LoggedInBacker() { let client = MockTrackingClient() let project = Project.template |> Project.lens.personalization.isBacking .~ true |> Project.lens.personalization.isStarred .~ false let loggedInUser = User.template |> \.id .~ 42 let koala = Koala(client: client, loggedInUser: loggedInUser) koala.trackProjectShow(project, refTag: nil, cookieRefTag: nil) XCTAssertEqual(3, client.properties.count) let properties = client.properties.last XCTAssertEqual(false, properties?["user_is_project_creator"] as? Bool) XCTAssertEqual(true, properties?["user_is_backer"] as? Bool) XCTAssertEqual(false, properties?["user_has_starred"] as? Bool) } func testProjectProperties_LoggedInStarrer() { let client = MockTrackingClient() let project = Project.template |> Project.lens.personalization.isBacking .~ false |> Project.lens.personalization.isStarred .~ true let loggedInUser = User.template |> \.id .~ 42 let koala = Koala(client: client, loggedInUser: loggedInUser) koala.trackProjectShow(project, refTag: nil, cookieRefTag: nil) XCTAssertEqual(3, client.properties.count) let properties = client.properties.last XCTAssertEqual(false, properties?["user_is_project_creator"] as? Bool) XCTAssertEqual(false, properties?["user_is_backer"] as? Bool) XCTAssertEqual(true, properties?["user_has_starred"] as? Bool) } func testProjectProperties_LoggedInCreator() { let client = MockTrackingClient() let project = Project.template |> Project.lens.personalization.isBacking .~ false <> Project.lens.personalization.isStarred .~ false let loggedInUser = project.creator let koala = Koala(client: client, loggedInUser: loggedInUser) koala.trackProjectShow(project, refTag: nil, cookieRefTag: nil) XCTAssertEqual(3, client.properties.count) let properties = client.properties.last XCTAssertEqual(true, properties?["user_is_project_creator"] as? Bool) XCTAssertEqual(false, properties?["user_is_backer"] as? Bool) XCTAssertEqual(false, properties?["user_has_starred"] as? Bool) } func testDiscoveryProperties() { let client = MockTrackingClient() let params = .defaults |> DiscoveryParams.lens.staffPicks .~ true <> DiscoveryParams.lens.starred .~ false <> DiscoveryParams.lens.social .~ false <> DiscoveryParams.lens.recommended .~ false <> DiscoveryParams.lens.category .~ Category.art <> DiscoveryParams.lens.query .~ "collage" <> DiscoveryParams.lens.sort .~ .popular let loggedInUser = User.template |> \.id .~ 42 let koala = Koala(client: client, loggedInUser: loggedInUser) koala.trackDiscovery(params: params, page: 1) let properties = client.properties.last XCTAssertEqual(1, properties?["discover_category_id"] as? Int) XCTAssertEqual(false, properties?["discover_recommended"] as? Bool) XCTAssertEqual(false, properties?["discover_social"] as? Bool) XCTAssertEqual(true, properties?["discover_staff_picks"] as? Bool) XCTAssertEqual(false, properties?["discover_starred"] as? Bool) XCTAssertEqual("collage", properties?["discover_term"] as? String) XCTAssertEqual(false, properties?["discover_everything"] as? Bool) XCTAssertEqual("popularity", properties?["discover_sort"] as? String) XCTAssertEqual(1, properties?["page"] as? Int) } func testDiscoveryProperties_NoCategory() { let client = MockTrackingClient() let params = .defaults |> DiscoveryParams.lens.staffPicks .~ true <> DiscoveryParams.lens.starred .~ false <> DiscoveryParams.lens.social .~ false <> DiscoveryParams.lens.recommended .~ false <> DiscoveryParams.lens.category .~ nil <> DiscoveryParams.lens.sort .~ .popular let loggedInUser = User.template |> \.id .~ 42 let koala = Koala(client: client, loggedInUser: loggedInUser) koala.trackDiscovery(params: params, page: 1) let properties = client.properties.last XCTAssertNil(properties?["discover_category_id"]) XCTAssertEqual(false, properties?["discover_recommended"] as? Bool) XCTAssertEqual(false, properties?["discover_social"] as? Bool) XCTAssertEqual(true, properties?["discover_staff_picks"] as? Bool) XCTAssertEqual(false, properties?["discover_starred"] as? Bool) XCTAssertEqual(false, properties?["discover_everything"] as? Bool) XCTAssertEqual("popularity", properties?["discover_sort"] as? String) XCTAssertEqual(1, properties?["page"] as? Int) } func testDiscoveryProperties_Everything() { let client = MockTrackingClient() let params = .defaults |> DiscoveryParams.lens.sort .~ .magic let loggedInUser = User.template |> \.id .~ 42 let koala = Koala(client: client, loggedInUser: loggedInUser) koala.trackDiscovery(params: params, page: 1) let properties = client.properties.last XCTAssertNil(properties?["discover_category_id"]) XCTAssertNil(properties?["discover_recommended"]) XCTAssertNil(properties?["discover_social"]) XCTAssertNil(properties?["discover_staff_picks"]) XCTAssertNil(properties?["discover_starred"]) XCTAssertNil(properties?["discover_term"]) XCTAssertEqual(true, properties?["discover_everything"] as? Bool) XCTAssertEqual("magic", properties?["discover_sort"] as? String) XCTAssertEqual(1, properties?["page"] as? Int) } func testTrackViewedPaymentMethods() { let client = MockTrackingClient() let koala = Koala(client: client) koala.trackViewedPaymentMethods() XCTAssertEqual(["Viewed Payment Methods"], client.events) } func testTrackViewedAddNewCard() { let client = MockTrackingClient() let koala = Koala(client: client) koala.trackViewedAddNewCard() XCTAssertEqual(["Viewed Add New Card"], client.events) } func testTrackDeletedPaymentMethod() { let client = MockTrackingClient() let koala = Koala(client: client) koala.trackDeletedPaymentMethod() XCTAssertEqual(["Deleted Payment Method"], client.events) } func testTrackDeletePaymentMethodError() { let client = MockTrackingClient() let koala = Koala(client: client) koala.trackDeletePaymentMethodError() XCTAssertEqual(["Errored Delete Payment Method"], client.events) } func testTrackSavedPaymentMethod() { let client = MockTrackingClient() let koala = Koala(client: client) koala.trackSavedPaymentMethod() XCTAssertEqual(["Saved Payment Method"], client.events) } func testTrackFailedPaymentMethodCreation() { let client = MockTrackingClient() let koala = Koala(client: client) koala.trackFailedPaymentMethodCreation() XCTAssertEqual(["Failed Payment Method Creation"], client.events) } func testLogEventsCallback() { let bundle = MockBundle() let client = MockTrackingClient() let config = Config.template let device = MockDevice(userInterfaceIdiom: .phone) let screen = MockScreen() let koala = Koala( bundle: bundle, client: client, config: config, device: device, loggedInUser: nil, screen: screen ) var callBackEvents = [String]() var callBackProperties: [String: Any]? koala.logEventCallback = { event, properties in callBackEvents.append(event) callBackProperties = properties } koala.trackAppOpen() XCTAssertEqual(["App Open", "Opened App"], client.events) XCTAssertEqual(["App Open", "Opened App"], callBackEvents) XCTAssertEqual("Apple", client.properties.last?["manufacturer"] as? String) XCTAssertEqual("Apple", callBackProperties?["manufacturer"] as? String) } func testTrackViewedAccount() { let client = MockTrackingClient() let koala = Koala(client: client) koala.trackAccountView() XCTAssertEqual(["Viewed Account"], client.events) } func testTrackCreatePassword_viewed() { let client = MockTrackingClient() let koala = Koala(client: client) koala.trackCreatePassword(event: .viewed) XCTAssertEqual([Koala.CreatePasswordTrackingEvent.viewed.rawValue], client.events) } func testTrackCreatePassword_passwordCreated() { let client = MockTrackingClient() let koala = Koala(client: client) koala.trackCreatePassword(event: .passwordCreated) XCTAssertEqual([Koala.CreatePasswordTrackingEvent.passwordCreated.rawValue], client.events) } func testTrackViewedChangeEmail() { let client = MockTrackingClient() let koala = Koala(client: client) koala.trackChangeEmailView() XCTAssertEqual(["Viewed Change Email"], client.events) } func testTrackChangeEmail() { let client = MockTrackingClient() let koala = Koala(client: client) koala.trackChangeEmail() XCTAssertEqual(["Changed Email"], client.events) } func testTrackViewedChangePassword() { let client = MockTrackingClient() let koala = Koala(client: client) koala.trackChangePasswordView() XCTAssertEqual(["Viewed Change Password"], client.events) } func testTrackChangePassword() { let client = MockTrackingClient() let koala = Koala(client: client) koala.trackChangePassword() XCTAssertEqual(["Changed Password"], client.events) } func testTrackChangedCurrency() { let client = MockTrackingClient() let koala = Koala(client: client) koala.trackChangedCurrency(.CAD) XCTAssertEqual(["Selected Chosen Currency"], client.events) XCTAssertEqual(Currency.CAD.descriptionText, client.properties.last?["currency"] as? String) } func testTrackDiscoveryPullToRefresh() { let client = MockTrackingClient() let koala = Koala(client: client) koala.trackDiscoveryPullToRefresh() XCTAssertEqual(["Triggered Refresh"], client.events) } func testTrackBackThisButtonClicked() { let client = MockTrackingClient() let project = Project.template let loggedInUser = User.template |> \.id .~ 42 let koala = Koala(client: client, loggedInUser: loggedInUser) koala.trackBackThisButtonClicked(project: project, screen: .projectPage) let properties = client.properties.last XCTAssertEqual(["Back this Project Button Clicked"], client.events) XCTAssertEqual("Project page", properties?["screen"] as? String) } func testTrackSelectRewardButtonClicked() { let client = MockTrackingClient() let reward = Reward.template let backing = .template |> Backing.lens.reward .~ reward let project = .template |> Project.lens.personalization.backing .~ backing let loggedInUser = User.template |> \.id .~ 42 let koala = Koala(client: client, loggedInUser: loggedInUser) koala.trackSelectRewardButtonClicked( project: project, reward: reward, backing: backing, screen: .backThisPage ) let properties = client.properties.last XCTAssertEqual(["Select Reward Button Clicked"], client.events) XCTAssertEqual("Back this page", properties?["screen"] as? String) } }
36.335294
105
0.721925
e8ac1195836f513c12363acda8529afeb7a49924
474
// // Team.swift // Demo2 // // Created by Vincent Bacalso on 15/11/2017. // Copyright © 2017 bluezald. All rights reserved. // import Foundation class Team { let name: String // TODO: Must be set to weak var members: [Person] = [] init(name: String) { self.name = name print("Team \(name) is initialized") } deinit { print("Team \(name) is being deallocated") } func add(person: Person) { self.members.append(person) } }
15.8
51
0.609705
d9245056791c50910e34625d2bff6627f4789a9b
238
import Foundation import NativeComponentKit final class BannerComponent: NativeComponent { private let view = BannerView() var ui: NativeUI { .view(view) } init(message: String) { view.message = message } }
18.307692
46
0.672269
62d8d448a54a42e2ba8bca8a26e8caab86547b12
925
// // mergeTwoSortedLists.swift // // Practice solution - Marwan Alani - 2017 // // Check the problem (and run the code) on leetCode @ https://leetcode.com/problems/merge-two-sorted-lists/ // Note: make sure that you select "Swift" from the top-left language menu of the code editor when testing this code // /** * Definition for singly-linked list. * public class ListNode { * public var val: Int * public var next: ListNode? * public init(_ val: Int) { * self.val = val * self.next = nil * } * } */ class Solution { func mergeTwoLists(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? { if (l1 == nil) { return l2 } if (l2 == nil) { return l1 } if (l1!.val < l2!.val) { l1!.next = mergeTwoLists(l1!.next, l2) return l1 } else { l2!.next = mergeTwoLists(l1, l2!.next) return l2 } } }
27.205882
117
0.566486
d5b2b063e838e743b450dac7abebc11df0a2bedd
1,532
// // Navigation.swift // NonReactiveMVVM // // Created by Ian Keen on 20/04/2016. // Copyright © 2016 Mustard. All rights reserved. // import UIKit class Navigation { //MARK: - Private private let navigationController: UINavigationController private let application: Application //MARK: - Lifecycle init(window: UIWindow, navigationController: UINavigationController, application: Application) { self.application = application self.navigationController = navigationController window.rootViewController = self.navigationController window.makeKeyAndVisible() } //MARK: - Public func start() { self.showFriendList() } //MARK: - Private private func showFriendList() { let viewModel = FriendsListViewModel( api: self.application.api, imageCache: self.application.imageCache ) viewModel.didSelectFriend = { [weak self] friend in self?.showFriend(friend) } let instance = FriendsListViewController(viewModel: viewModel) self.navigationController.pushViewController(instance, animated: false) } private func showFriend(friend: Friend) { let viewModel = FriendDetailViewModel( friend: friend, imageCache: self.application.imageCache ) let instance = FriendDetailViewController(viewModel: viewModel) self.navigationController.pushViewController(instance, animated: true) } }
30.64
100
0.664491
c15782fab092772a5d8ba70f022271d4322d0bc9
1,818
// // RouteCenter.swift // Pods // // Created by 王小涛 on 2017/7/7. // // import Foundation import URLNavigator // 规定routePattern的格式为restful风格,其中参数placehodler用<>括起来,例如: // scheme://zooms/<zoom_id>/animals/<animal_id> public protocol RoutePatternConvertible { var routePattern: String {get} } extension String { var routePattern: String { return self } } public protocol Routable { static var routePattern: RoutePatternConvertible {get} static func route(url: String, parameters: [String : String]) -> Bool } public class RouteCenter { public static let `default` = RouteCenter() private let navigator = Navigator() private init() {} public func add<T: Routable>(_ routable: T.Type) { map(routable.routePattern, handler: routable.route(url:parameters:)) } public func map(_ routePattern: RoutePatternConvertible, handler: @escaping (_ url: String, _ parameters: [String: String]) -> Bool) { navigator.handle(routePattern.routePattern) { (urlConvertible, values, context) -> Bool in let parameters = urlConvertible.queryParameters.reduce(values, { var result = $0 result.updateValue($1.value, forKey: $1.key) return result }) let newParameters: [String: String] = parameters.reduce([:], { result, turple in var newResult = result newResult[turple.key] = turple.value as? String return newResult }) return handler(urlConvertible.urlStringValue, newParameters) } } public func route(url: String) -> Bool { return navigator.open(url) } public func route(url: URL) -> Bool { return navigator.open(url) } }
27.545455
138
0.621012
03f04a24d8a951b806c77ae37c342a609ebec2aa
2,145
// // AppDelegate.swift // TipCalc // // Created by Simon Carroll on 7/29/16. // Copyright © 2016 Simon Carroll. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
45.638298
285
0.753846
4a5b8827a5a8167732e02c0ab02fbdcdf5493275
1,239
// // Package.swift // // Copyright (c) 2016 Marko Tadić <[email protected]> http://tadija.net // // 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 PackageDescription let package = Package( name: "AEXML" )
42.724138
81
0.755448
9cf21012ca438571f09f14786c323c218a523331
2,820
import Alamofire open class APIInputBase { public var headers: [String: String] = [:] public let urlString: String public let requestType: HTTPMethod public let encoding: ParameterEncoding public let parameters: [String: Any]? public let requireAccessToken: Bool public var accessToken: String? public var useCache: Bool = false { didSet { if requestType != .get || self is APIUploadInputBase { fatalError() } } } public var user: String? public var password: String? public init(urlString: String, parameters: [String: Any]?, requestType: HTTPMethod, requireAccessToken: Bool) { self.urlString = urlString self.parameters = parameters self.requestType = requestType self.encoding = requestType == .get ? URLEncoding.default : JSONEncoding.default self.requireAccessToken = requireAccessToken } } extension APIInputBase: CustomStringConvertible { open var urlEncodingString: String { guard let url = URL(string: urlString), var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), let parameters = parameters, requestType == .get else { return urlString } urlComponents.queryItems = parameters.map { return URLQueryItem(name: "\($0)", value: "\($1)") } return urlComponents.url?.absoluteString ?? urlString } open var description: String { if requestType == .get { return [ "🌎 \(requestType.rawValue) \(urlEncodingString)" ].joined(separator: "\n") } return [ "🌎 \(requestType.rawValue) \(urlString)", "Parameters: \(String(describing: parameters ?? JSONDictionary()))" ].joined(separator: "\n") } } public struct APIUploadData { public let data: Data public let name: String public let fileName: String public let mimeType: String public init(data: Data, name: String, fileName: String, mimeType: String) { self.data = data self.name = name self.fileName = fileName self.mimeType = mimeType } } open class APIUploadInputBase: APIInputBase { public let data: [APIUploadData] public init(data: [APIUploadData], urlString: String, parameters: [String: Any]?, requestType: HTTPMethod, requireAccessToken: Bool) { self.data = data super.init( urlString: urlString, parameters: parameters, requestType: requestType, requireAccessToken: requireAccessToken ) } }
28.77551
88
0.59078
f90fcceaf495504bc392358b11f17d15ad1da6cd
3,002
import Foundation import XCTest @testable import Xit class SidebarDelegateTest: XTTest { var outline = MockSidebarOutline() let sbDelegate = SidebarDelegate() var model: SidebarDataModel! override func setUp() { super.setUp() model = SidebarDataModel(repository: repository, outlineView: outline) sbDelegate.model = model } /// Check that root items (except Staging) are groups func testGroupItems() throws { try execute(in: repository) { CreateBranch("b1") } model.reload() for item in model.roots { XCTAssertTrue(sbDelegate.outlineView(outline, isGroupItem: item)) } } func testTags() throws { let tagName = "t1" guard let headOID = repository.headSHA.flatMap({ repository.oid(forSHA: $0) }) else { XCTFail("no head") return } try repository.createTag(name: tagName, targetOID: headOID, message: "msg") model.reload() let tagItem = model.rootItem(.tags).children[0] guard let cell = sbDelegate.outlineView(outline, viewFor: nil, item: tagItem) as? NSTableCellView else { XCTFail("wrong cell type") return } XCTAssertEqual(cell.textField?.stringValue, tagName) } func testBranches() throws { let branchNames = ["b1", "master"] try execute(in: repository) { CreateBranch("b1") } model.reload() for (item, name) in zip(model.rootItem(.branches).children, branchNames) { guard let cell = sbDelegate.outlineView(outline, viewFor: nil, item: item) as? NSTableCellView else { XCTFail("wrong cell type") continue } XCTAssertEqual(cell.textField?.stringValue, name) } } func testRemotes() throws { makeRemoteRepo() let remoteName = "origin" try execute(in: repository) { CheckOut(branch: "master") CreateBranch("b1") } try repository.addRemote(named: remoteName, url: URL(fileURLWithPath: remoteRepoPath)) let configArgs = ["config", "receive.denyCurrentBranch", "ignore"] _ = try remoteRepository.executeGit(args: configArgs, writes: false) try repository.push(remote: "origin") model.reload() let remoteItem = try XCTUnwrap(model.rootItem(.remotes).children.first) let branchItem = try XCTUnwrap(remoteItem.children.first) let remoteCell = try XCTUnwrap(sbDelegate.outlineView(outline, viewFor: nil, item: remoteItem) as? NSTableCellView) let branchCell = try XCTUnwrap(sbDelegate.outlineView(outline, viewFor: nil, item: branchItem) as? NSTableCellView) XCTAssertEqual(remoteCell.textField?.stringValue, remoteName) XCTAssertEqual(branchCell.textField?.stringValue, "b1") } }
27.045045
82
0.610926
26508e8f318eb7bbb0bcb0abee0a1560b3053107
4,147
//// BarPagerTabStripViewController.swift //// XLPagerTabStrip ( https://github.com/xmartlabs/XLPagerTabStrip ) //// //// Copyright (c) 2017 Xmartlabs ( http://xmartlabs.com ) //// //// //// Permission is hereby granted, free of charge, to any person obtaining a copy //// of this software and associated documentation files (the "Software"), to deal //// in the Software without restriction, including without limitation the rights //// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //// copies of the Software, and to permit persons to whom the Software is //// furnished to do so, subject to the following conditions: //// //// The above copyright notice and this permission notice shall be included in //// all copies or substantial portions of the Software. //// //// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //// THE SOFTWARE. // //import Foundation //import UIKit // //public struct BarPagerTabStripSettings { // // public struct Style { // public var barBackgroundColor: UIColor? // public var selectedBarBackgroundColor: UIColor? // public var barHeight: CGFloat = 5 // barHeight is ony set up when the bar is created programatically and not using storyboards or xib files. // } // // public var style = Style() //} // //open class BarPagerTabStripViewController: PagerTabStripViewController, PagerTabStripDataSource, PagerTabStripIsProgressiveDelegate { // // public var settings = BarPagerTabStripSettings() // // @IBOutlet weak public var barView: BarView! // // required public init?(coder aDecoder: NSCoder) { // super.init(coder: aDecoder) // delegate = self // datasource = self // } // // public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { // super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) // delegate = self // datasource = self // } // // open override func viewDidLoad() { // super.viewDidLoad() // barView = barView ?? { // let barView = BarView(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: settings.style.barHeight)) // barView.autoresizingMask = .flexibleWidth // barView.backgroundColor = .black // barView.selectedBar.backgroundColor = .white // return barView // }() // // barView.backgroundColor = settings.style.barBackgroundColor ?? barView.backgroundColor // barView.selectedBar.backgroundColor = settings.style.selectedBarBackgroundColor ?? barView.selectedBar.backgroundColor // } // // open override func viewWillAppear(_ animated: Bool) { // super.viewWillAppear(animated) // if barView.superview == nil { // view.addSubview(barView) // } // barView.optionsCount = viewControllers.count // barView.moveTo(index: currentIndex, animated: false) // } // // open override func reloadPagerTabStripView() { // super.reloadPagerTabStripView() // barView.optionsCount = viewControllers.count // if isViewLoaded { // barView.moveTo(index: currentIndex, animated: false) // } // } // // // MARK: - PagerTabStripDelegate // // open func updateIndicator(for viewController: PagerTabStripViewController, fromIndex: Int, toIndex: Int, withProgressPercentage progressPercentage: CGFloat, indexWasChanged: Bool) { // // barView.move(fromIndex: fromIndex, toIndex: toIndex, progressPercentage: progressPercentage) // } // // open func updateIndicator(for viewController: PagerTabStripViewController, fromIndex: Int, toIndex: Int) { // barView.moveTo(index: toIndex, animated: true) // } //}
41.888889
187
0.685556
7a92fafcbd72a684f9e222262823d9b05b8e4db1
839
// // NSUserDefaults+CustomObjects.swift // AudioMate // // Created by Ruben Nine on 25/04/16. // Copyright © 2016 Ruben Nine. All rights reserved. // import Foundation extension UserDefaults { public func customObjectForKey(defaultName: String) -> NSCoding? { guard let objectForKey = object(forKey: defaultName) as? NSData else { return nil } if let decodedObject = try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(objectForKey) as? NSCoding { return decodedObject } else { return nil } } public func setCustomObject(value: NSCoding?, forKey defaultName: String) { guard let object = value else { return } let encodedObject = NSKeyedArchiver.archivedData(withRootObject: object) set(encodedObject, forKey: defaultName) } }
26.21875
114
0.678188
cca2f33d2895e2e49cc135a6e6c1cccab3a80dcf
3,028
// // UIViewExtension.swift // CatNovel // // Created by Yu Li Lin on 2019/8/13. // Copyright © 2019 CatNovel. All rights reserved. // import UIKit extension UIView { func setRadius() { layer.borderWidth = 1.0 layer.borderColor = UIColor.clear.cgColor layer.cornerRadius = 5.0 } func setCornerRadius(value:CGFloat) { layer.cornerRadius = value layer.borderWidth = 1.0 layer.borderColor = UIColor.clear.cgColor } //MARK: ----- 設定圓角 ----- func setRoundRect(conrers:UIRectCorner, cornerRadius:CGFloat) { /* let rectShape = CAShapeLayer() bounds = frame rectShape.position = center rectShape.path = UIBezierPath(roundedRect: bounds, byRoundingCorners: conrers, cornerRadii: CGSize(width: cornerRadius, height: cornerRadius)).cgPath layer.mask = rectShape */ let maskPath = UIBezierPath.init(roundedRect: bounds, byRoundingCorners: conrers, cornerRadii:CGSize.init(width:cornerRadius, height:cornerRadius)) let maskLayer = CAShapeLayer() maskLayer.path = maskPath.cgPath layer.mask = maskLayer //設定圓角 } func setViewShadow() { layer.shadowColor = UIColor.black.cgColor layer.shadowOffset = CGSize(width: 0, height: 1) layer.shadowRadius = 5.0 layer.shadowOpacity = 0.2 layer.masksToBounds = false layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: layer.cornerRadius).cgPath } //讀取xib func loadNib(nibName:String) throws -> UIView { enum LoadNibError:Error { case unknowError } guard let view = UINib(nibName: nibName, bundle: Bundle.init(for: type(of:self))).instantiate(withOwner: self, options: nil).first as? UIView else { print("load nib with error") throw LoadNibError.unknowError } view.frame = bounds view.autoresizingMask = [.flexibleWidth , .flexibleHeight] return view } func zoomOut(completion: @escaping (Bool) -> Void) { UIView.animate(withDuration: 0.3, animations: { self.transform = CGAffineTransform(scaleX: 0.1,y: 0.1); }) { (finished) in self.transform = CGAffineTransform(scaleX: 0.0,y: 0.0) completion(finished) } } func zoomIn(completion: @escaping (Bool) -> Void) { UIView.animate(withDuration: 0.3, animations: { self.transform = CGAffineTransform(scaleX: 1.0,y: 1.0) }) { (finished) in completion(finished) } } } /* class UIViewExtension: NSObject { } */
25.024793
158
0.547886
3917d8eb847fac5cef2018e8f18ded220966e172
785
import Flutter import UIKit public class SwiftDemoPlugin: NSObject, FlutterPlugin { public static func register(with registrar: FlutterPluginRegistrar) { let channel = FlutterMethodChannel(name: "demo_plugin", binaryMessenger: registrar.messenger()) let instance = SwiftDemoPlugin() registrar.addMethodCallDelegate(instance, channel: channel) } public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { if (call.method.elementsEqual("nativeToast")) { let args = call.arguments as? NSDictionary let msg = args!["msg"] as? String UIAlertView(title:"", message:msg, delegate:nil, cancelButtonTitle:"OK") } result("iOS " + UIDevice.current.systemVersion) } }
39.25
103
0.681529
de8af9fd7357ec885641cb8f17c9b686bfa030ec
3,229
// // SlotFinderTests.swift // samaTests // // Created by Viktoras Laukevičius on 7/6/21. // import XCTest @testable import Sama class SlotFinderTests: XCTestCase { private var finder: SlotFinder! override func setUp() { super.setUp() finder = SlotFinder() } override func tearDown() { super.tearDown() finder = nil } func test_notOverlappingSuggestions() { let props = [ EventProperties(start: 12.25, duration: 0.25, daysOffset: 2, timezoneOffset: 0), EventProperties(start: 12.5, duration: 0.25, daysOffset: 2, timezoneOffset: 0), ] let result = finder.getPossibleSlots( with: SlotFinder.Context( eventProperties: props, blocksForDayIndex: [:], totalDaysOffset: 5002, currentDayIndex: 5000, minTarget: RescheduleTarget(daysOffset: 0, start: 21), baseStart: 11.75, duration: 3 ) ) let exp = [ SlotFinder.PossibleSlot(daysOffset: 1, start: 11.75), SlotFinder.PossibleSlot(daysOffset: 2, start: 12.75), SlotFinder.PossibleSlot(daysOffset: 2, start: 9.25), SlotFinder.PossibleSlot(daysOffset: 3, start: 11.75), SlotFinder.PossibleSlot(daysOffset: 4, start: 11.75) ] XCTAssertEqual(result, exp) } func test_notOverlappingEvents() { let result = finder.getPossibleSlots( with: SlotFinder.Context( eventProperties: [], blocksForDayIndex: [ 5001: [CalendarBlockedTime(id: AccountCalendarId(accountId: "1", calendarId: "1"), title: "SAMA Standup", start: 12.5, duration: 1, isBlockedTime: false, depth: 0)], 5003: [CalendarBlockedTime(id: AccountCalendarId(accountId: "1", calendarId: "1"), title: "SAMA Standup", start: 12.5, duration: 1, isBlockedTime: false, depth: 0)] ], totalDaysOffset: 5001, currentDayIndex: 5000, minTarget: RescheduleTarget(daysOffset: 0, start: 21), baseStart: 11.5, duration: 3 ) ) let exp = [ SlotFinder.PossibleSlot(daysOffset: 1, start: 13.5), SlotFinder.PossibleSlot(daysOffset: 1, start: 9.5), SlotFinder.PossibleSlot(daysOffset: 2, start: 11.5), SlotFinder.PossibleSlot(daysOffset: 3, start: 13.5), SlotFinder.PossibleSlot(daysOffset: 3, start: 9.5), ] XCTAssertEqual(result, exp) } func test_notIncludesPastDates() { let result = finder.getPossibleSlots( with: SlotFinder.Context( eventProperties: [], blocksForDayIndex: [:], totalDaysOffset: 4999, currentDayIndex: 5000, minTarget: RescheduleTarget(daysOffset: 0, start: 21), baseStart: 11.5, duration: 3 ) ) let exp = [ SlotFinder.PossibleSlot(daysOffset: 1, start: 11.5) ] XCTAssertEqual(result, exp) } }
34.351064
185
0.557138
8f2c5cc4b97032dae378d3f2d3a8771c71488afc
2,024
// Automatically generated by xdrgen // DO NOT EDIT or your changes may be overwritten import Foundation // === xdr source ============================================================ // //: CancelDataUpdateRequestOp is used to cancel reviwable request for data Update. // //: If successful, request with the corresponding ID will be deleted // struct CancelDataUpdateRequestOp // { // //: ID of the DataUpdateRequest request to be canceled // uint64 requestID; // // //: Reserved for future use // union switch (LedgerVersion v) // { // case EMPTY_VERSION: // void; // } // ext; // // }; // =========================================================================== public struct CancelDataUpdateRequestOp: XDRCodable { public var requestID: Uint64 public var ext: CancelDataUpdateRequestOpExt public init( requestID: Uint64, ext: CancelDataUpdateRequestOpExt) { self.requestID = requestID self.ext = ext } public func toXDR() -> Data { var xdr = Data() xdr.append(self.requestID.toXDR()) xdr.append(self.ext.toXDR()) return xdr } public init(xdrData: inout Data) throws { self.requestID = try Uint64(xdrData: &xdrData) self.ext = try CancelDataUpdateRequestOpExt(xdrData: &xdrData) } public enum CancelDataUpdateRequestOpExt: XDRDiscriminatedUnion { case emptyVersion public var discriminant: Int32 { switch self { case .emptyVersion: return LedgerVersion.emptyVersion.rawValue } } public func toXDR() -> Data { var xdr = Data() xdr.append(self.discriminant.toXDR()) switch self { case .emptyVersion: xdr.append(Data()) } return xdr } public init(xdrData: inout Data) throws { let discriminant = try Int32(xdrData: &xdrData) switch discriminant { case LedgerVersion.emptyVersion.rawValue: self = .emptyVersion default: throw XDRErrors.unknownEnumCase } } } }
23.811765
86
0.606225
61cc8a369fb92bd40b469d43527c50e228e1adaa
629
import Prelude import Tuple import XCTest final class TupleTests: XCTestCase { func testTuples() { let tuple = 1 .*. "hello" .*. true .*. 2.0 .*. unit XCTAssertEqual(1, tuple |> get1) XCTAssertEqual("hello", tuple |> get2) XCTAssertEqual(true, tuple |> get3) XCTAssertEqual(2.0, tuple |> get4) XCTAssertTrue( 2 .*. "hello" .*. true .*. 2.0 .*. unit == (tuple |> over1({ $0 + 1 })) ) let loweredTuple = lower(tuple) XCTAssertEqual(1, loweredTuple.0) XCTAssertEqual("hello", loweredTuple.1) XCTAssertEqual(true, loweredTuple.2) XCTAssertEqual(2.0, loweredTuple.3) } }
24.192308
77
0.626391
3a9e8bb536b17bd7e257b695a39706477be6f7ab
4,535
// Copyright SIX DAY LLC. All rights reserved. import Foundation import UIKit extension UIView { static func tableFooterToRemoveEmptyCellSeparators() -> UIView { return .init() } static var tokenSymbolBackgroundImageCache: ThreadSafeDictionary<UIColor, UIImage> = .init() static func tokenSymbolBackgroundImage(backgroundColor: UIColor) -> UIImage { if let cachedValue = tokenSymbolBackgroundImageCache[backgroundColor] { return cachedValue } let size = CGSize(width: 40, height: 40) let rect = CGRect(origin: .zero, size: size) let renderer = UIGraphicsImageRenderer(size: size) let image = renderer.image { ctx in ctx.cgContext.setFillColor(backgroundColor.cgColor) ctx.cgContext.addEllipse(in: rect) ctx.cgContext.drawPath(using: .fill) } tokenSymbolBackgroundImageCache[backgroundColor] = image return image } func dropShadow(color: UIColor, opacity: Float = 0.5, offSet: CGSize = .zero, radius: CGFloat = 1, scale: Bool = true, shouldRasterize: Bool = true) { layer.masksToBounds = false layer.shadowColor = color.cgColor layer.shadowOpacity = opacity layer.shadowOffset = offSet layer.shadowRadius = radius layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath layer.shouldRasterize = shouldRasterize layer.rasterizationScale = scale ? UIScreen.main.scale : 1 } func anchorsConstraint(to view: UIView, edgeInsets: UIEdgeInsets = .zero) -> [NSLayoutConstraint] { return [ leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: edgeInsets.left), trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -edgeInsets.right), topAnchor.constraint(equalTo: view.topAnchor, constant: edgeInsets.top), bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -edgeInsets.bottom), ] } func anchorsConstraint(to view: UIView, margin: CGFloat) -> [NSLayoutConstraint] { return anchorsConstraint(to: view, edgeInsets: .init(top: margin, left: margin, bottom: margin, right: margin)) } static func spacer(height: CGFloat = 1, backgroundColor: UIColor = .clear) -> UIView { let view = UIView(frame: .zero) view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = backgroundColor NSLayoutConstraint.activate([ view.heightAnchor.constraint(equalToConstant: height), ]) return view } static func spacerWidth(_ width: CGFloat = 1, backgroundColor: UIColor = .clear, alpha: CGFloat = 1, flexible: Bool = false) -> UIView { let view = UIView(frame: .zero) view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = backgroundColor view.alpha = alpha if flexible { NSLayoutConstraint.activate([ view.widthAnchor.constraint(greaterThanOrEqualToConstant: width), ]) } else { NSLayoutConstraint.activate([ view.widthAnchor.constraint(equalToConstant: width), ]) } return view } var centerRect: CGRect { return CGRect(x: bounds.midX, y: bounds.midY, width: 0, height: 0) } //Have to recreate UIMotionEffect every time, after `layoutSubviews()` complete func setupParallaxEffect(forView view: UIView, max: CGFloat) { view.motionEffects.forEach { view.removeMotionEffect($0) } let min = max let max = -max let xMotion = UIInterpolatingMotionEffect(keyPath: "center.x", type: .tiltAlongHorizontalAxis) xMotion.minimumRelativeValue = min xMotion.maximumRelativeValue = max let yMotion = UIInterpolatingMotionEffect(keyPath: "center.y", type: .tiltAlongVerticalAxis) yMotion.minimumRelativeValue = min yMotion.maximumRelativeValue = max let motionEffectGroup = UIMotionEffectGroup() motionEffectGroup.motionEffects = [xMotion, yMotion] view.addMotionEffect(motionEffectGroup) } func firstSubview<T>(ofType type: T.Type) -> T? { if let viewFound = subviews.first(where: { $0 is T }) { return viewFound as? T } for each in subviews { if let viewFound = each.firstSubview(ofType: T.self) { return viewFound } } return nil } }
38.109244
154
0.654686
f5c63ccc8804c5e91149b4b71f39b26c246b97b1
352
// // JSLMyProfilePhotoModel.swift // JSLogistics // 我的 编辑图片model // Created by gouyz on 2019/11/24. // Copyright © 2019 gouyz. All rights reserved. // import UIKit @objcMembers class JSLMyProfilePhotoModel: LHSBaseModel { /// var imgURL: String? = "" /// 订单编号 var img: UIImage? /// 0本地图片1网络图片 var isUrl: String? = "" }
16.761905
48
0.639205
e0e0ea6ae2975bf994ea62c8de53281aaad61a79
736
// // SpecialModelName.swift // // Generated by openapi-generator // https://openapi-generator.tech // import Foundation import AnyCodable public struct SpecialModelName: Codable, Hashable { public var specialPropertyName: Int64? public init(specialPropertyName: Int64? = nil) { self.specialPropertyName = specialPropertyName } public enum CodingKeys: String, CodingKey, CaseIterable { case specialPropertyName = "$special[property.name]" } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(specialPropertyName, forKey: .specialPropertyName) } }
24.533333
88
0.721467
e82bd9e67528ee9e4481988572015dc8ed6f9407
13,639
import Foundation import XcodeProj import PathKit import Yams import SourceryRuntime import QuartzCore public struct Project { public let file: XcodeProj public let root: Path public let targets: [Target] public let exclude: [Path] public struct Target { public let name: String public let module: String public init(dict: [String: String]) throws { guard let name = dict["name"] else { throw Configuration.Error.invalidSources(message: "Target name is not provided. Expected string.") } self.name = name self.module = dict["module"] ?? name } } public init(dict: [String: Any], relativePath: Path) throws { guard let file = dict["file"] as? String else { throw Configuration.Error.invalidSources(message: "Project file path is not provided. Expected string.") } let targetsArray: [Target] if let targets = dict["target"] as? [[String: String]] { targetsArray = try targets.map({ try Target(dict: $0) }) } else if let target = dict["target"] as? [String: String] { targetsArray = try [Target(dict: target)] } else { throw Configuration.Error.invalidSources(message: "'target' key is missing. Expected object or array of objects.") } guard !targetsArray.isEmpty else { throw Configuration.Error.invalidSources(message: "No targets provided.") } self.targets = targetsArray let exclude = (dict["exclude"] as? [String])?.map({ Path($0, relativeTo: relativePath) }) ?? [] self.exclude = exclude.flatMap { $0.allPaths } let path = Path(file, relativeTo: relativePath) self.file = try XcodeProj(path: path) self.root = path.parent() } } public struct Paths { public let include: [Path] public let exclude: [Path] public let allPaths: [Path] public var isEmpty: Bool { return allPaths.isEmpty } public init(dict: Any, relativePath: Path) throws { if let sources = dict as? [String: [String]], let include = sources["include"]?.map({ Path($0, relativeTo: relativePath) }) { let exclude = sources["exclude"]?.map({ Path($0, relativeTo: relativePath) }) ?? [] self.init(include: include, exclude: exclude) } else if let sources = dict as? [String] { let sources = sources.map({ Path($0, relativeTo: relativePath) }) guard !sources.isEmpty else { throw Configuration.Error.invalidPaths(message: "No paths provided.") } self.init(include: sources) } else { throw Configuration.Error.invalidPaths(message: "No paths provided. Expected list of strings or object with 'include' and optional 'exclude' keys.") } } public init(include: [Path], exclude: [Path] = []) { self.include = include self.exclude = exclude let start = CFAbsoluteTimeGetCurrent() let include = self.include.parallelFlatMap { $0.processablePaths } let exclude = self.exclude.parallelFlatMap { $0.processablePaths } self.allPaths = Array(Set(include).subtracting(Set(exclude))).sorted() Log.benchmark("Resolving Paths took \(CFAbsoluteTimeGetCurrent() - start)") } } extension Path { public var processablePaths: [Path] { if isDirectory { return (try? recursiveUnhiddenChildren()) ?? [] } else { return [self] } } public func recursiveUnhiddenChildren() throws -> [Path] { FileManager.default.enumerator(at: url, includingPropertiesForKeys: [.pathKey], options: [.skipsHiddenFiles, .skipsPackageDescendants], errorHandler: nil)?.compactMap { object in if let url = object as? URL { return self + Path(url.path) } return nil } ?? [] } } public enum Source { case projects([Project]) case sources(Paths) public init(dict: [String: Any], relativePath: Path) throws { if let projects = (dict["project"] as? [[String: Any]]) ?? (dict["project"] as? [String: Any]).map({ [$0] }) { guard !projects.isEmpty else { throw Configuration.Error.invalidSources(message: "No projects provided.") } self = try .projects(projects.map({ try Project(dict: $0, relativePath: relativePath) })) } else if let sources = dict["sources"] { do { self = try .sources(Paths(dict: sources, relativePath: relativePath)) } catch { throw Configuration.Error.invalidSources(message: "\(error)") } } else { throw Configuration.Error.invalidSources(message: "'sources' or 'project' key are missing.") } } public var isEmpty: Bool { switch self { case let .sources(paths): return paths.allPaths.isEmpty case let .projects(projects): return projects.isEmpty } } } public struct Output { public struct LinkTo { public let project: XcodeProj public let projectPath: Path public let targets: [String] public let group: String? public init(dict: [String: Any], relativePath: Path) throws { guard let project = dict["project"] as? String else { throw Configuration.Error.invalidOutput(message: "No project file path provided.") } if let target = dict["target"] as? String { self.targets = [target] } else if let targets = dict["targets"] as? [String] { self.targets = targets } else { throw Configuration.Error.invalidOutput(message: "No target(s) provided.") } let projectPath = Path(project, relativeTo: relativePath) self.projectPath = projectPath self.project = try XcodeProj(path: projectPath) self.group = dict["group"] as? String } } public let path: Path public let linkTo: LinkTo? public var isDirectory: Bool { guard path.exists else { return path.lastComponentWithoutExtension == path.lastComponent || path.string.hasSuffix("/") } return path.isDirectory } public init(dict: [String: Any], relativePath: Path) throws { guard let path = dict["path"] as? String else { throw Configuration.Error.invalidOutput(message: "No path provided.") } self.path = Path(path, relativeTo: relativePath) if let linkToDict = dict["link"] as? [String: Any] { do { self.linkTo = try LinkTo(dict: linkToDict, relativePath: relativePath) } catch { self.linkTo = nil Log.warning(error) } } else { self.linkTo = nil } } public init(_ path: Path, linkTo: LinkTo? = nil) { self.path = path self.linkTo = linkTo } } public struct Configuration { public enum Error: Swift.Error, CustomStringConvertible { case invalidFormat(message: String) case invalidSources(message: String) case invalidTemplates(message: String) case invalidOutput(message: String) case invalidCacheBasePath(message: String) case invalidPaths(message: String) public var description: String { switch self { case .invalidFormat(let message): return "Invalid config file format. \(message)" case .invalidSources(let message): return "Invalid sources. \(message)" case .invalidTemplates(let message): return "Invalid templates. \(message)" case .invalidOutput(let message): return "Invalid output. \(message)" case .invalidCacheBasePath(let message): return "Invalid cacheBasePath. \(message)" case .invalidPaths(let message): return "\(message)" } } } public let source: Source public let templates: Paths public let output: Output public let cacheBasePath: Path public let forceParse: [String] public let args: [String: NSObject] public init( path: Path, relativePath: Path, env: [String: String] = [:] ) throws { guard let dict = try Yams.load(yaml: path.read(), .default, Constructor.sourceryContructor(env: env)) as? [String: Any] else { throw Configuration.Error.invalidFormat(message: "Expected dictionary.") } try self.init(dict: dict, relativePath: relativePath) } public init(dict: [String: Any], relativePath: Path) throws { let source = try Source(dict: dict, relativePath: relativePath) guard !source.isEmpty else { throw Configuration.Error.invalidSources(message: "No sources provided.") } self.source = source let templates: Paths guard let templatesDict = dict["templates"] else { throw Configuration.Error.invalidTemplates(message: "'templates' key is missing.") } do { templates = try Paths(dict: templatesDict, relativePath: relativePath) } catch { throw Configuration.Error.invalidTemplates(message: "\(error)") } guard !templates.isEmpty else { throw Configuration.Error.invalidTemplates(message: "No templates provided.") } self.templates = templates self.forceParse = dict["forceParse"] as? [String] ?? [] if let output = dict["output"] as? String { self.output = Output(Path(output, relativeTo: relativePath)) } else if let output = dict["output"] as? [String: Any] { self.output = try Output(dict: output, relativePath: relativePath) } else { throw Configuration.Error.invalidOutput(message: "'output' key is missing or is not a string or object.") } if let cacheBasePath = dict["cacheBasePath"] as? String { self.cacheBasePath = Path(cacheBasePath, relativeTo: relativePath) } else if dict["cacheBasePath"] != nil { throw Configuration.Error.invalidCacheBasePath(message: "'cacheBasePath' key is not a string.") } else { self.cacheBasePath = Path.defaultBaseCachePath } self.args = dict["args"] as? [String: NSObject] ?? [:] } public init(sources: Paths, templates: Paths, output: Path, cacheBasePath: Path, forceParse: [String], args: [String: NSObject]) { self.source = .sources(sources) self.templates = templates self.output = Output(output, linkTo: nil) self.cacheBasePath = cacheBasePath self.forceParse = forceParse self.args = args } } public enum Configurations { public static func make( path: Path, relativePath: Path, env: [String: String] = [:] ) throws -> [Configuration] { guard let dict = try Yams.load(yaml: path.read(), .default, Constructor.sourceryContructor(env: env)) as? [String: Any] else { throw Configuration.Error.invalidFormat(message: "Expected dictionary.") } if let configurations = dict["configurations"] as? [[String: Any]] { return try configurations.map { dict in try Configuration(dict: dict, relativePath: relativePath) } } else { return try [Configuration(dict: dict, relativePath: relativePath)] } } } // Copied from https://github.com/realm/SwiftLint/blob/0.29.2/Source/SwiftLintFramework/Models/YamlParser.swift // and https://github.com/SwiftGen/SwiftGen/blob/6.1.0/Sources/SwiftGenKit/Utils/YAML.swift private extension Constructor { static func sourceryContructor(env: [String: String]) -> Constructor { return Constructor(customScalarMap(env: env)) } static func customScalarMap(env: [String: String]) -> ScalarMap { var map = defaultScalarMap map[.str] = String.constructExpandingEnvVars(env: env) return map } } private extension String { static func constructExpandingEnvVars(env: [String: String]) -> (_ scalar: Node.Scalar) -> String? { return { (scalar: Node.Scalar) -> String? in scalar.string.expandingEnvVars(env: env) } } func expandingEnvVars(env: [String: String]) -> String? { // check if entry has an env variable guard let match = self.range(of: #"\$\{(.)\w+\}"#, options: .regularExpression) else { return self } // get the env variable as "${ENV_VAR}" let key = String(self[match]) // get the env variable as "ENV_VAR" - note missing $ and brackets let keyString = String(key[2..<key.count-1]) guard let value = env[keyString] else { return "" } return self.replacingOccurrences(of: key, with: value) } } private extension StringProtocol { subscript(bounds: CountableClosedRange<Int>) -> SubSequence { let start = index(startIndex, offsetBy: bounds.lowerBound) let end = index(start, offsetBy: bounds.count) return self[start..<end] } subscript(bounds: CountableRange<Int>) -> SubSequence { let start = index(startIndex, offsetBy: bounds.lowerBound) let end = index(start, offsetBy: bounds.count) return self[start..<end] } }
35.892105
186
0.604663
6acf425e11a9a3ea299b9cd587fa2784acbc6b8a
3,535
// // TodayMultipleAppsController.swift // AppStore // // Created by SUNG HAO LIN on 2020/2/26. // Copyright © 2020 SUNG HAO LIN. All rights reserved. // import UIKit enum Mode { case small case fullscreen } class TodayMultipleAppsController: BaseListController { var apps = [FeedResult]() fileprivate var spacing: CGFloat = 16 fileprivate let mode: Mode override var prefersStatusBarHidden: Bool { return true } let closebutton: UIButton = { let button = UIButton(type: .system) button.setImage(UIImage(named: "close_button"), for: .normal) button.tintColor = .darkGray button.addTarget(self, action: #selector(handleDismiss), for: .touchUpInside) return button }() // MARK: - Initialization init(mode: Mode) { self.mode = mode super.init() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() if mode == .fullscreen { setupCloseButton() navigationController?.isNavigationBarHidden = true } else { collectionView.isScrollEnabled = false // Avoid scroll in cell } collectionView.backgroundColor = .white collectionView.register(MutipleAppCell.self, forCellWithReuseIdentifier: MutipleAppCell.reuseId) } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if mode == .fullscreen { return apps.count } return min(4, apps.count) } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MutipleAppCell.reuseId, for: indexPath) as! MutipleAppCell cell.app = apps[indexPath.item] return cell } override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let appId = self.apps[indexPath.item].id let appDetailController = AppDetailController(appId: appId) navigationController?.pushViewController(appDetailController, animated: true) } // MARK: - Private Methods private func setupCloseButton() { view.addSubview(closebutton) closebutton.anchor(top: view.topAnchor, leading: nil, bottom: nil, trailing: view.trailingAnchor, padding: .init(top: 20, left: 0, bottom: 0, right: 16), size: .init(width: 44, height: 44)) } @objc private func handleDismiss() { dismiss(animated: true, completion: nil) } } extension TodayMultipleAppsController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let height: CGFloat = 68 if mode == .fullscreen { return .init(width: view.frame.width - 48, height: height) } return .init(width: view.frame.width, height: height) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 16 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { if mode == .fullscreen { return .init(top: 12, left: 24, bottom: 12, right: 24) } return .zero } }
31.283186
168
0.703536
5067b35e4abe00352453fb5e1a290924717ad4da
5,454
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // Loosely adapted from https://github.com/apple/swift/tree/main/stdlib/private/StdlibUnittest public enum ExpectedComparisonResult: Hashable { case lt, eq, gt public func flip() -> ExpectedComparisonResult { switch self { case .lt: return .gt case .eq: return .eq case .gt: return .lt } } public static func comparing<C: Comparable>(_ left: C, _ right: C) -> Self { left < right ? .lt : left > right ? .gt : .eq } } extension ExpectedComparisonResult: CustomStringConvertible { public var description: String { switch self { case .lt: return "<" case .eq: return "==" case .gt: return ">" } } } public func checkComparable<Instance: Comparable>( sortedEquivalenceClasses: [[Instance]], file: StaticString = #file, line: UInt = #line ) { let instances = sortedEquivalenceClasses.flatMap { $0 } // oracle[i] is the index of the equivalence class that contains instances[i]. let oracle = sortedEquivalenceClasses.indices.flatMap { i in repeatElement(i, count: sortedEquivalenceClasses[i].count) } checkComparable( instances, oracle: { if oracle[$0] < oracle[$1] { return .lt } if oracle[$0] > oracle[$1] { return .gt } return .eq }, file: file, line: line) } /// Test that the elements of `instances` satisfy the semantic /// requirements of `Comparable`, using `oracle` to generate comparison /// expectations from pairs of positions in `instances`. public func checkComparable<Instances: Collection>( _ instances: Instances, oracle: (Instances.Index, Instances.Index) -> ExpectedComparisonResult, file: StaticString = #file, line: UInt = #line ) where Instances.Element: Comparable { checkEquatable(instances, oracle: { oracle($0, $1) == .eq }, file: file, line: line) _checkComparable(instances, oracle: oracle, file: file, line: line) } public func checkComparable<T : Comparable>( expected: ExpectedComparisonResult, _ lhs: T, _ rhs: T, file: StaticString = #file, line: UInt = #line ) { checkComparable( [lhs, rhs], oracle: { [[ .eq, expected], [ expected.flip(), .eq]][$0][$1] }, file: file, line: line) } /// Same as `checkComparable(_:oracle:file:line:)` but doesn't check /// `Equatable` conformance. Useful for preventing duplicate testing. public func _checkComparable<Instances: Collection>( _ instances: Instances, oracle: (Instances.Index, Instances.Index) -> ExpectedComparisonResult, file: StaticString = #file, line: UInt = #line ) where Instances.Element: Comparable { let entry = TestContext.current.push("checkComparable", file: file, line: line) defer { TestContext.current.pop(entry) } for i in instances.indices { let x = instances[i] expectFalse( x < x, "found 'x < x' at index \(i): \(String(reflecting: x))") expectFalse( x > x, "found 'x > x' at index \(i): \(String(reflecting: x))") expectTrue(x <= x, "found 'x <= x' to be false at index \(i): \(String(reflecting: x))") expectTrue(x >= x, "found 'x >= x' to be false at index \(i): \(String(reflecting: x))") for j in instances.indices where i != j { let y = instances[j] let expected = oracle(i, j) expectEqual( expected.flip(), oracle(j, i), """ bad oracle: missing antisymmetry: lhs (at index \(i)): \(String(reflecting: x)) rhs (at index \(j)): \(String(reflecting: y)) """) expectEqual( expected == .lt, x < y, """ x < y doesn't match oracle lhs (at index \(i)): \(String(reflecting: x)) rhs (at index \(j)): \(String(reflecting: y)) """) expectEqual( expected != .gt, x <= y, """ x <= y doesn't match oracle lhs (at index \(i)): \(String(reflecting: x)) rhs (at index \(j)): \(String(reflecting: y)) """) expectEqual( expected != .lt, x >= y, """ x >= y doesn't match oracle lhs (at index \(i)): \(String(reflecting: x)) rhs (at index \(j)): \(String(reflecting: y)) """) expectEqual( expected == .gt, x > y, """ x > y doesn't match oracle lhs (at index \(i)): \(String(reflecting: x)) rhs (at index \(j)): \(String(reflecting: y)) """) for k in instances.indices { let expected2 = oracle(j, k) if expected == expected2 { expectEqual( expected, oracle(i, k), """ bad oracle: transitivity violation x (at index \(i)): \(String(reflecting: x)) y (at index \(j)): \(String(reflecting: y)) z (at index \(k)): \(String(reflecting: instances[k])) """) } } } } }
30.813559
123
0.569674
71cb597c3d7566ea7632ba69809abb2bb819c1b8
4,098
#if os(macOS) import Foundation import IOKit import IOKit.serial import NewtonCommon public class DarwinSerialPortMonitor: SerialPortMonitor { public enum Error: Swift.Error { case portCreationFailed case addMatchingNotificationFailed case addTerminatedNotificationFailed } private let notificationQueue = DispatchQueue(label: "com.turbolent.NewtonKit.DarwinSerialPortMonitor") private let notificationPort: IONotificationPortRef private var matchedIterator: io_iterator_t = 0 private var terminatedIterator: io_iterator_t = 0 public let callbackQueue: DispatchQueue public var callback: Callback private static let matchCallback: IOServiceMatchingCallback = { userData, iterator in let monitor: DarwinSerialPortMonitor = fromContext(pointer: userData!) monitor.dispatchEvent(event: .matched, iterator: iterator) } private static let termCallback: IOServiceMatchingCallback = { userData, iterator in let monitor: DarwinSerialPortMonitor = fromContext(pointer: userData!) monitor.dispatchEvent(event: .terminated, iterator: iterator) } public required init(callbackQueue: DispatchQueue, callback: @escaping Callback) throws { guard let notificationPort = IONotificationPortCreate(kIOMasterPortDefault) else { throw Error.portCreationFailed } self.notificationPort = notificationPort IONotificationPortSetDispatchQueue(notificationPort, notificationQueue) self.callbackQueue = callbackQueue self.callback = callback } public func start() throws { guard matchedIterator == 0 else { return } let selfPointer = toContext(object: self) // add matching notification let addMatchResult = IOServiceAddMatchingNotification(notificationPort, kIOPublishNotification, serialPortMatching, DarwinSerialPortMonitor.matchCallback, selfPointer, &matchedIterator) guard addMatchResult == KERN_SUCCESS else { if matchedIterator != 0 { IOObjectRelease(matchedIterator) } throw Error.addMatchingNotificationFailed } // add terminated notification let addTermResult = IOServiceAddMatchingNotification(notificationPort, kIOTerminatedNotification, serialPortMatching, DarwinSerialPortMonitor.termCallback, selfPointer, &terminatedIterator) guard addTermResult == KERN_SUCCESS else { if terminatedIterator != 0 { IOObjectRelease(terminatedIterator) } throw Error.addTerminatedNotificationFailed } // Always iterate both matched and terminated iterators, so notifications are properly emitted. // Handle terminated iterator first, so that matched iterator ends up in correct state. dispatchEvent(event: .terminated, iterator: terminatedIterator) dispatchEvent(event: .matched, iterator: matchedIterator) } public func stop() throws { guard matchedIterator != 0 else { return } IOObjectRelease(matchedIterator) IOObjectRelease(terminatedIterator) matchedIterator = 0 terminatedIterator = 0 } private func dispatchEvent(event: SerialPortMonitorEvent, iterator: io_iterator_t) { for serialPort in DarwinSerialPorts(iterator: iterator, release: false) { callbackQueue.async { [callback] in callback(event, serialPort) } } } deinit { try? stop() } } #endif
33.590164
103
0.61591
d6e5f2d4c210218c4009b336fc87f2a507cdaaf6
1,093
// // MapStateLayer.swift // simprokcore // // Created by Andrey Prokhorenko on 01.12.2021. // Copyright (c) 2022 simprok. All rights reserved. import simprokmachine /// A general protocol that describes a type that represents a layer object. /// Contains a machine that receives layer state as input and emits global events as output. public protocol MapStateLayer { associatedtype GlobalEvent associatedtype GlobalState associatedtype State /// A machine that receives mapped state as input and emits output. var machine: Machine<State, GlobalEvent> { get } /// A mapper that maps application's state into layer state and sends it into machine as input. func map(state: GlobalState) -> State } public extension MapStateLayer { /// An equivalent to Layer.state(self) var layer: Layer<GlobalState, GlobalEvent> { Layer.state(self) } } public extension MapStateLayer { /// An equivalent to Layer.state(self) prefix static func ~(operand: Self) -> Layer<GlobalState, GlobalEvent> { operand.layer } }
26.02381
99
0.703568
168d0d541dc5095dae57c146e7f8e8a0e1ccb5be
11,152
/* file: current_change_element_assignment.swift generated: Mon Jan 3 16:32:52 2022 */ /* This file was generated by the EXPRESS to Swift translator "exp2swift", derived from STEPcode (formerly NIST's SCL). exp2swift version: v.1.0.1, derived from stepcode v0.8 as of 2019/11/23 WARNING: You probably don't want to edit it since your modifications will be lost if exp2swift is used to regenerate it. */ import SwiftSDAIcore extension AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF { //MARK: -ENTITY DEFINITION in EXPRESS /* ENTITY current_change_element_assignment SUBTYPE OF ( group_assignment ); SELF\group_assignment.assigned_group : current_element_assignment_select; items : SET [1 : ?] OF change_management_object; END_ENTITY; -- current_change_element_assignment (line:11007 file:ap242ed2_mim_lf_v1.101.TY.exp) */ //MARK: - ALL DEFINED ATTRIBUTES /* SUPER- ENTITY(1) group_assignment ATTR: assigned_group, TYPE: group -- EXPLICIT (DYNAMIC) -- possibly overriden by ENTITY: product_definition_group_assignment, TYPE: product_definition_element_relationship ENTITY: assigned_requirement, TYPE: requirement_assignment *** ENTITY: current_change_element_assignment, TYPE: current_element_assignment_select ENTITY: mating_material_items, TYPE: mating_material ENTITY: previous_change_element_assignment, TYPE: previous_element_assignment_select ENTITY: document_identifier_assignment, TYPE: document_identifier ENTITY: product_group_membership_rules, TYPE: product_group ENTITY: mated_part_relationship, TYPE: mated_part_relationship (as DERIVED) ENTITY: assigned_analysis, TYPE: analysis_assignment ENTITY: product_concept_feature_category_usage, TYPE: product_concept_feature_category ENTITY: source_for_requirement, TYPE: requirement_source ENTITY: sourced_requirement, TYPE: requirement_source ENTITY: containing_message, TYPE: message_contents_group ENTITY: product_group_attribute_set, TYPE: product_group ENTITY: satisfied_requirement, TYPE: satisfies_requirement ENTITY: message_contents_assignment, TYPE: message_contents_group ENTITY: breakdown_element_group_assignment, TYPE: product_definition_element_relationship ENTITY: satisfying_item, TYPE: satisfies_requirement ENTITY: analysis_item, TYPE: analysis_assignment ENTITY: product_group_rule_assignment, TYPE: product_group_rules ENTITY: product_group_attribute_assignment, TYPE: product_group_attributes ENTITY: change_group_assignment, TYPE: change_group ENTITY: requirement_assigned_object, TYPE: requirement_assignment ATTR: role, TYPE: object_role -- DERIVED := get_role( SELF ) ENTITY(SELF) current_change_element_assignment REDCR: assigned_group, TYPE: current_element_assignment_select -- EXPLICIT -- OVERRIDING ENTITY: group_assignment ATTR: items, TYPE: SET [1 : ?] OF change_management_object -- EXPLICIT */ //MARK: - Partial Entity public final class _current_change_element_assignment : SDAI.PartialEntity { public override class var entityReferenceType: SDAI.EntityReference.Type { eCURRENT_CHANGE_ELEMENT_ASSIGNMENT.self } //ATTRIBUTES /* override var _assigned_group: sCURRENT_ELEMENT_ASSIGNMENT_SELECT //EXPLICIT REDEFINITION(eGROUP_ASSIGNMENT) */ /// EXPLICIT ATTRIBUTE public internal(set) var _items: SDAI.SET<sCHANGE_MANAGEMENT_OBJECT>/*[1:nil]*/ // PLAIN EXPLICIT ATTRIBUTE public override var typeMembers: Set<SDAI.STRING> { var members = Set<SDAI.STRING>() members.insert(SDAI.STRING(Self.typeName)) return members } //VALUE COMPARISON SUPPORT public override func hashAsValue(into hasher: inout Hasher, visited complexEntities: inout Set<SDAI.ComplexEntity>) { super.hashAsValue(into: &hasher, visited: &complexEntities) self._items.value.hashAsValue(into: &hasher, visited: &complexEntities) } public override func isValueEqual(to rhs: SDAI.PartialEntity, visited comppairs: inout Set<SDAI.ComplexPair>) -> Bool { guard let rhs = rhs as? Self else { return false } if !super.isValueEqual(to: rhs, visited: &comppairs) { return false } if let comp = self._items.value.isValueEqualOptionally(to: rhs._items.value, visited: &comppairs) { if !comp { return false } } else { return false } return true } public override func isValueEqualOptionally(to rhs: SDAI.PartialEntity, visited comppairs: inout Set<SDAI.ComplexPair>) -> Bool? { guard let rhs = rhs as? Self else { return false } var result: Bool? = true if let comp = super.isValueEqualOptionally(to: rhs, visited: &comppairs) { if !comp { return false } } else { result = nil } if let comp = self._items.value.isValueEqualOptionally(to: rhs._items.value, visited: &comppairs) { if !comp { return false } } else { result = nil } return result } //EXPRESS IMPLICIT PARTIAL ENTITY CONSTRUCTOR public init(ITEMS: SDAI.SET<sCHANGE_MANAGEMENT_OBJECT>/*[1:nil]*/ ) { self._items = ITEMS super.init(asAbstructSuperclass:()) } //p21 PARTIAL ENTITY CONSTRUCTOR public required convenience init?(parameters: [P21Decode.ExchangeStructure.Parameter], exchangeStructure: P21Decode.ExchangeStructure) { let numParams = 1 guard parameters.count == numParams else { exchangeStructure.error = "number of p21 parameters(\(parameters.count)) are different from expected(\(numParams)) for entity(\(Self.entityName)) constructor"; return nil } guard case .success(let p0) = exchangeStructure.recoverRequiredParameter(as: SDAI.SET< sCHANGE_MANAGEMENT_OBJECT>.self, from: parameters[0]) else { exchangeStructure.add(errorContext: "while recovering parameter #0 for entity(\(Self.entityName)) constructor"); return nil } self.init( ITEMS: p0 ) } } //MARK: - Entity Reference /** ENTITY reference - EXPRESS: ```express ENTITY current_change_element_assignment SUBTYPE OF ( group_assignment ); SELF\group_assignment.assigned_group : current_element_assignment_select; items : SET [1 : ?] OF change_management_object; END_ENTITY; -- current_change_element_assignment (line:11007 file:ap242ed2_mim_lf_v1.101.TY.exp) ``` */ public final class eCURRENT_CHANGE_ELEMENT_ASSIGNMENT : SDAI.EntityReference { //MARK: PARTIAL ENTITY public override class var partialEntityType: SDAI.PartialEntity.Type { _current_change_element_assignment.self } public let partialEntity: _current_change_element_assignment //MARK: SUPERTYPES public let super_eGROUP_ASSIGNMENT: eGROUP_ASSIGNMENT // [1] public var super_eCURRENT_CHANGE_ELEMENT_ASSIGNMENT: eCURRENT_CHANGE_ELEMENT_ASSIGNMENT { return self } // [2] //MARK: SUBTYPES //MARK: ATTRIBUTES /// __DERIVE__ attribute /// - origin: SUPER( ``eGROUP_ASSIGNMENT`` ) public var ROLE: eOBJECT_ROLE? { get { if let cached = cachedValue(derivedAttributeName:"ROLE") { return cached.value as! eOBJECT_ROLE? } let origin = super_eGROUP_ASSIGNMENT let value = eOBJECT_ROLE(origin.partialEntity._role__getter(SELF: origin)) updateCache(derivedAttributeName:"ROLE", value:value) return value } } /// __EXPLICIT__ attribute /// - origin: SELF( ``eCURRENT_CHANGE_ELEMENT_ASSIGNMENT`` ) public var ITEMS: SDAI.SET<sCHANGE_MANAGEMENT_OBJECT>/*[1:nil]*/ { get { return SDAI.UNWRAP( self.partialEntity._items ) } set(newValue) { let partial = self.partialEntity partial._items = SDAI.UNWRAP(newValue) } } /// __EXPLICIT REDEF(DYNAMIC)__ attribute /// - origin: SELF( ``eCURRENT_CHANGE_ELEMENT_ASSIGNMENT`` ) public var ASSIGNED_GROUP: sCURRENT_ELEMENT_ASSIGNMENT_SELECT { get { if let resolved = _group_assignment._assigned_group__provider(complex: self.complexEntity) { let value = SDAI.UNWRAP( sCURRENT_ELEMENT_ASSIGNMENT_SELECT(resolved._assigned_group__getter( complex: self.complexEntity)) ) return value } else { return SDAI.UNWRAP( sCURRENT_ELEMENT_ASSIGNMENT_SELECT(super_eGROUP_ASSIGNMENT.partialEntity ._assigned_group) ) } } set(newValue) { if let _ = _group_assignment._assigned_group__provider(complex: self.complexEntity) { return } let partial = super_eGROUP_ASSIGNMENT.partialEntity partial._assigned_group = SDAI.UNWRAP( eGROUP(newValue)) } } //MARK: INITIALIZERS public convenience init?(_ entityRef: SDAI.EntityReference?) { let complex = entityRef?.complexEntity self.init(complex: complex) } public required init?(complex complexEntity: SDAI.ComplexEntity?) { guard let partial = complexEntity?.partialEntityInstance(_current_change_element_assignment.self) else { return nil } self.partialEntity = partial guard let super1 = complexEntity?.entityReference(eGROUP_ASSIGNMENT.self) else { return nil } self.super_eGROUP_ASSIGNMENT = super1 super.init(complex: complexEntity) } public required convenience init?<G: SDAIGenericType>(fromGeneric generic: G?) { guard let entityRef = generic?.entityReference else { return nil } self.init(complex: entityRef.complexEntity) } public convenience init?<S: SDAISelectType>(_ select: S?) { self.init(possiblyFrom: select) } public convenience init?(_ complex: SDAI.ComplexEntity?) { self.init(complex: complex) } //MARK: DICTIONARY DEFINITION public class override var entityDefinition: SDAIDictionarySchema.EntityDefinition { _entityDefinition } private static let _entityDefinition: SDAIDictionarySchema.EntityDefinition = createEntityDefinition() private static func createEntityDefinition() -> SDAIDictionarySchema.EntityDefinition { let entityDef = SDAIDictionarySchema.EntityDefinition(name: "CURRENT_CHANGE_ELEMENT_ASSIGNMENT", type: self, explicitAttributeCount: 1) //MARK: SUPERTYPE REGISTRATIONS entityDef.add(supertype: eGROUP_ASSIGNMENT.self) entityDef.add(supertype: eCURRENT_CHANGE_ELEMENT_ASSIGNMENT.self) //MARK: ATTRIBUTE REGISTRATIONS entityDef.addAttribute(name: "ROLE", keyPath: \eCURRENT_CHANGE_ELEMENT_ASSIGNMENT.ROLE, kind: .derived, source: .superEntity, mayYieldEntityReference: true) entityDef.addAttribute(name: "ITEMS", keyPath: \eCURRENT_CHANGE_ELEMENT_ASSIGNMENT.ITEMS, kind: .explicit, source: .thisEntity, mayYieldEntityReference: true) entityDef.addAttribute(name: "ASSIGNED_GROUP", keyPath: \eCURRENT_CHANGE_ELEMENT_ASSIGNMENT.ASSIGNED_GROUP, kind: .explicitRedeclaring, source: .thisEntity, mayYieldEntityReference: true) return entityDef } } }
41.61194
185
0.719692
9089b50cadf78da63b0c79d4a9aa7bd773d4625e
2,908
// // MAURLocation+Extension.swift // COVIDSafePaths // // Created by Michael Neas on 5/21/20. // Copyright © 2020 Path Check Inc. All rights reserved. // import Foundation import Scrypt extension MAURLocation { /// Generates array of geohashes concatenated with time, within a 10 meter radius of given location public var geoHashes: [String] { Geohash.GEO_CIRCLE_RADII.map({ radii in (latitude.doubleValue + radii.latitude, longitude.doubleValue + radii.longitude) }).reduce(into: Set<String>(), { (hashes, currentLocation) in hashes.insert(Geohash.encode(latitude: currentLocation.0, longitude: currentLocation.1, length: 8)) }).reduce(into: [String](), { (hashes, hash) in let timeWindow = timeWindows(interval: Double(60 * 5 * 1000)) hashes.append("\(hash)\(timeWindow.early)") hashes.append("\(hash)\(timeWindow.late)") }) } /// Encodes geoHashes with the scrypt algorithm public var scryptHashes: [String] { let start = DispatchTime.now() let scryptGeoHashes = geoHashes.map(scrypt) let end = DispatchTime.now() let nanoTime = end.uptimeNanoseconds - start.uptimeNanoseconds let timeInterval = Double(nanoTime) / 1_000_000_000 Log.scryptHashing.debug(String(format: "Hashing completed in: %.4f seconds", timeInterval)) return scryptGeoHashes } convenience init(location: Location) { self.init() time = location.date latitude = location.latitude as NSNumber longitude = location.longitude as NSNumber accuracy = location.accuracy.value as NSNumber? altitude = location.altitude.value as NSNumber? altitudeAccuracy = location.altitudeAccuracy.value as NSNumber? speed = location.speed.value as NSNumber? heading = location.bearing.value as NSNumber? } /// Generates rounded time windows for interval before and after timestamp /// https://pathcheck.atlassian.net/wiki/x/CoDXB /// - Parameters: /// - interval: location storage interval in seconds public func timeWindows(interval: TimeInterval) -> (early: Int, late: Int) { let time1 = Int(((time.timeIntervalSince1970 - interval / 2) / interval).rounded(.down) * interval) let time2 = Int(((time.timeIntervalSince1970 + interval / 2) / interval).rounded(.down) * interval) return (time1, time2) } /// Apply scrypt hash algorithm on a String /// /// - Parameters: /// - hash: value to hash public func scrypt(on hash: String) -> String { let hash = Array(hash.utf8) let generic = Array("salt".utf8) /// A “cost” (N) that is to be determined. Initially was 16384, then modified to 4096 /// A salt of “salt” /// A block size of 8 /// A keylen (output) of 8 bytes = 16 hex digits. /// Parallelization (p) of 1 - this is the default. return try! Scrypt.scrypt(password: hash, salt: generic, length: 8,N: 4096, r: 8, p: 1).toHexString() } }
37.766234
105
0.687758
f54adaf6505eb4c70c866c65162e2addabd6e334
344
// // KJFloatEx.swift // KJCommonKit // // Created by 黄克瑾 on 2020/7/8. // Copyright © 2020 黄克瑾. All rights reserved. // import Foundation import UIKit extension Float { func kj_cgFloatValue() -> CGFloat { return CGFloat(self) } } extension CGFloat { func kj_floatValue() -> Float { return Float(self) } }
14.956522
46
0.625
766dec2cf4679a188d50808a932b5022abc64dc3
1,266
// // AtStakeUITests.swift // AtStakeUITests // // Created by John Richardson on 2/8/17. // Copyright © 2017 Engagement Lab at Emerson College. All rights reserved. // import XCTest class AtStakeUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
34.216216
182
0.665877
2f97ee12f146028881d31a23f1efc3fa23c5bbd5
615
// swift-tools-version:5.2 import PackageDescription let package = Package( name: "stripe", platforms: [ .macOS(.v10_15) ], products: [ .library(name: "Stripe", targets: ["Stripe"]) ], dependencies: [ .package(url: "https://github.com/vapor/vapor.git", from: "4.0.0"), .package(url: "https://github.com/varungakhar/stripe-kit.git", from: "12.0.2"), ], targets: [ .target(name: "Stripe", dependencies: [ .product(name: "StripeKit", package: "stripe-kit"), .product(name: "Vapor", package: "vapor"), ]), ] )
26.73913
87
0.549593
2f29d6f838e9fafef82e2d2eb66aeb2d470045fc
1,754
// // CAShapeLayer+SVG.swift // SwiftSVG // // // Copyright (c) 2017 Michael Choe // http://www.github.com/mchoe // http://www.straussmade.com/ // http://www.twitter.com/_mchoe // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(iOS) || os(tvOS) import UIKit #elseif os(OSX) import AppKit #endif public extension CAShapeLayer { /** Convenience initalizer that synchronously parses a single path string and returns a `CAShapeLayer` - Parameter pathString: The path `d` string to parse. */ convenience init(pathString: String) { self.init() let singlePath = SVGPath(singlePathString: pathString) self.path = singlePath.svgLayer.path } }
33.09434
103
0.719498
71437893cda58559ac5dac487159504371be5b1c
6,538
// // HeadToHeadVC.swift // MedQuiz // // Created by Chad Johnson on 3/27/18. // Copyright © 2018 Omar Sherief. All rights reserved. // import UIKit import Firebase /* HeadToHeadVC allows the user to select a friend for a head to head game invitation. */ class HeadToHeadVC: UIViewController, UITableViewDelegate, UITableViewDataSource, HeadToHeadFriendRequestViewCellDelegate { @IBOutlet weak var friendsTableView: UITableView! @IBOutlet weak var backButton: UIButton! var quizKey:String! var friends:[Student]! /* Retrieve user friends and set values for table view. */ override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. friends = currentGlobalStudent.friends! let friendRequestsCellNib = UINib(nibName: "HeadToHeadFriendRequestTableViewCell", bundle: nil) self.friendsTableView.register(friendRequestsCellNib, forCellReuseIdentifier: "friendRequest_cell") self.friendsTableView.delegate = self self.friendsTableView.dataSource = self self.friendsTableView.rowHeight = 100.0 self.friendsTableView.allowsSelection = false self.friendsTableView.contentInset = UIEdgeInsetsMake(0, 0, 120, 0) self.friendsTableView.separatorStyle = .none } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* Return number of sections in table (1). */ func numberOfSections(in tableView: UITableView) -> Int { return 1 } /* Return number of rows in section of table view. */ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return friends.count } /* Set and return table view cell at indexPath. */ func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell : HeadToHeadFriendRequestTableViewCell = friendsTableView.dequeueReusableCell(withIdentifier: "friendRequest_cell") as! HeadToHeadFriendRequestTableViewCell cell.delegate = self cell.friend = friends[indexPath.row] cell.setViews() return cell } /* Check if selected friend if online and not busy. Create database objects for head to head game and transition to lobby. */ func requestMade(selectedFriend: Student) { StudentModel.From(key: selectedFriend.databaseID!) {friend in if !friend.online! { let alert = UIAlertController(title:"Friend Offline", message:"Friend is offline at the moment.", preferredStyle: .alert) alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "Default action"), style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) } else if friend.headToHeadGameRequest == nil { let headToHeadGameReference = Database.database().reference().child("head-to-head-game").childByAutoId() headToHeadGameReference.child("quiz").setValue(self.quizKey) headToHeadGameReference.child("inviter").child("student").setValue(currentUserID) headToHeadGameReference.child("inviter").child("ready").setValue(false) headToHeadGameReference.child("invitee").child("student").setValue(selectedFriend.databaseID) headToHeadGameReference.child("invitee").child("ready").setValue(false) headToHeadGameReference.child("accepted").setValue(false) headToHeadGameReference.child("decided").setValue(false) let inGameLeaderboardReference = Database.database().reference().child("inGameLeaderboards").childByAutoId() inGameLeaderboardReference.child("game").setValue(headToHeadGameReference.key) let inviterLeaderboardRef = inGameLeaderboardReference.child("students").child(currentUserID) inviterLeaderboardRef.child("studentKey").setValue(currentUserID) inviterLeaderboardRef.child("studentScore").setValue(0) let inviteeLeaderboardRef = inGameLeaderboardReference.child("students").child(selectedFriend.databaseID!) inviteeLeaderboardRef.child("studentKey").setValue(selectedFriend.databaseID) inviteeLeaderboardRef.child("studentScore").setValue(0) let friendReference = Database.database().reference().child("student").child(selectedFriend.databaseID!) friendReference.child("headtoheadgamerequest").setValue(headToHeadGameReference.key) let userReference = Database.database().reference().child("student").child(currentUserID) userReference.child("headtoheadgamerequest").setValue(headToHeadGameReference.key) let quizLobbyVC = self.storyboard?.instantiateViewController(withIdentifier: "quizLobbyVC") as! QuizLobbyVC quizLobbyVC.quizKey = self.quizKey quizLobbyVC.gameKey = headToHeadGameReference.key quizLobbyVC.headToHeadOpponent = selectedFriend quizLobbyVC.quizMode = QuizLobbyVC.QuizMode.HeadToHead quizLobbyVC.isInvitee = false globalBusy = true self.present(quizLobbyVC, animated: false, completion: nil) } else{ let alert = UIAlertController(title:"Friend Busy", message:"Friend is busy at the moment.", preferredStyle: .alert) alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "Default action"), style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) } } } /* Dismiss view. */ @IBAction func backButtonPressed(_ sender: Any) { self.dismiss(animated: false, completion: nil) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
42.732026
173
0.660294
8a06cf8c131ae406e9c71edde1b60b57e9910f4f
5,622
/* This SDK is licensed under the MIT license (MIT) Copyright (c) 2015- Applied Technologies Internet SAS (registration number B 403 261 258 - Trade and Companies Register of Bordeaux – France) 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. */ // // Video.swift // Tracker // import UIKit public class Video: RichMedia { /// Media type let type: String = "video" /// Duration public var duration: Int = 0 /// Set parameters in buffer override func setEvent() { super.setEvent() if (self.duration > 86400) { self.duration = 86400 } _ = self.tracker.setParam("m1", value: duration) .setParam("type", value: type) } } public class Videos { var list: [String: Video] = [String: Video]() /// MediaPlayer instance var player: MediaPlayer /** Videos initializer - parameter player: the player instance - returns: Videos instance */ init(player: MediaPlayer) { self.player = player } /** Create a new video - parameter video: name - parameter video: duration in seconds - returns: video instance */ public func add(_ name:String, duration: Int) -> Video { if let video = self.list[name] { self.player.tracker.delegate?.warningDidOccur("A Video with the same name already exists.") return video } else { let video = Video(player: player) video.name = name video.duration = duration self.list[name] = video return video } } /** Create a new video - parameter video: name - parameter first: chapter - parameter video: duration in seconds - returns: video instance */ public func add(_ name: String, chapter1: String, duration: Int) -> Video { if let video = self.list[name] { self.player.tracker.delegate?.warningDidOccur("A Video with the same name already exists.") return video } else { let video = Video(player: player) video.name = name video.duration = duration video.chapter1 = chapter1 self.list[name] = video return video } } /** Create a new video - parameter video: name - parameter first: chapter - parameter second: chapter - parameter video: duration in seconds - returns: video instance */ public func add(_ name: String, chapter1: String, chapter2: String, duration: Int) -> Video { if let video = self.list[name] { self.player.tracker.delegate?.warningDidOccur("A Video with the same name already exists.") return video } else { let video = Video(player: player) video.name = name video.duration = duration video.chapter1 = chapter1 video.chapter2 = chapter2 self.list[name] = video return video } } /** Create a new video - parameter video: name - parameter first: chapter - parameter second: chapter - parameter third: chapter - parameter video: duration in seconds - returns: video instance */ public func add(_ name: String, chapter1: String, chapter2: String, chapter3: String, duration: Int) -> Video { if let video = self.list[name] { self.player.tracker.delegate?.warningDidOccur("A Video with the same name already exists.") return video } else { let video = Video(player: player) video.name = name video.duration = duration video.chapter1 = chapter1 video.chapter2 = chapter2 video.chapter3 = chapter3 self.list[name] = video return video } } /** Remove a video - parameter video: name */ public func remove(_ name: String) { if let timer = list[name]?.timer { if timer.isValid { list[name]!.sendStop() } } self.list.removeValue(forKey: name) } /** Remove all videos */ public func removeAll() { for (_, value) in self.list { if let timer = value.timer { if timer.isValid { value.sendStop() } } } self.list.removeAll(keepingCapacity: false) } }
28.830769
141
0.591604
db85a3813c598607079e6967c559952579456acf
1,662
// Copyright (c) 2015 - 2019 Jann Schafranek // // 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 #if os(iOS) /// A protocol for a class observing settings. public protocol OKSettingsObserver : class { /** This method is called every time a matching setting is changed. - parameters: - value : The value set. - key : The key of the changed setting. - type : The type of the changed setting. - object : The object of the changed setting. */ func observe(value : AnyObject?, forKey key : String, type : OKSettingable.Type, object : OKSettingable?) } #endif
43.736842
109
0.726835
bb19cfa7205529c424da1287da7d780794e65c16
487
// // BaseTableViewCell.swift // Spectrum // // Created by Derick on 5/6/20. // Copyright © 2020 DerickDev. All rights reserved. // import UIKit class BaseTableViewCell: UITableViewCell { override func awakeFromNib() { super.awakeFromNib() setupUI() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } func setupUI() { selectionStyle = .none } }
17.392857
65
0.622177
16be03ade5ed0322ca685406d2664bc1b716ae33
5,686
// // SPTinderViewCell.swift // SPTinderView // // Created by Suraj Pathak on 3/2/16. // Copyright © 2016 Suraj Pathak. All rights reserved. // import UIKit /// The SPTinderViewCell defines the attributes and behavior of the cells that appear in SPTinderView objects. This class includes properties and methods for setting and managing cell content and background. @IBDesignable open class SPTinderViewCell: UIView, UIGestureRecognizerDelegate { @IBInspectable var reuseIdentifier: String? @IBInspectable var cornerRadius: CGFloat = 0 { didSet { self.layer.cornerRadius = cornerRadius } } var cellMovement: SPTinderViewCellMovement = .none typealias cellMovementChange = (SPTinderViewCellMovement) -> () var onCellDidMove: cellMovementChange? fileprivate var originalCenter = CGPoint(x: 0, y: 0) fileprivate var scaleToRemoveCell: CGFloat = 0.3 open override func awakeFromNib() { super.awakeFromNib() self.layer.shadowOffset = CGSize(width: 0.0, height: 5.0) } public required init(reuseIdentifier: String) { self.init() self.reuseIdentifier = reuseIdentifier } public override init(frame: CGRect) { super.init(frame: frame) setupLayerAttributes() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupLayerAttributes() } fileprivate func setupLayerAttributes() { self.layer.shouldRasterize = false self.layer.borderWidth = 2.0 self.layer.borderColor = UIColor.clear.cgColor self.layer.shadowColor = UIColor.darkGray.cgColor self.layer.shadowOffset = CGSize(width: 0.0, height: 5.0) self.layer.shadowOpacity = 0.5 self.layer.masksToBounds = false } open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { guard let _ = touches.first else { return } originalCenter = self.center } open override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { if let touch = touches.first { let prevLoc = touch.previousLocation(in: self) let thisLoc = touch.location(in: self) let deltaX = thisLoc.x - prevLoc.x let deltaY = thisLoc.y - prevLoc.y // There's also a little bit of transformation. When the cell is being dragged, it should feel the angle of drag as well let xDrift = self.center.x + deltaX - originalCenter.x let rotationAngle = xDrift * -0.05 * CGFloat(Double.pi / 90) // Note: Must set the animation option to `AllowUserInteraction` to prevent the main thread being blocked while animation is ongoin let rotatedTransfer = CGAffineTransform(rotationAngle: rotationAngle) UIView.animate(withDuration: 0.0, delay: 0.0, options: [.allowUserInteraction], animations: { self.transform = rotatedTransfer self.center.x += deltaX self.center.y += deltaY }, completion: { finished in }) } } open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { let xDrift = self.center.x - originalCenter.x let yDrift = self.center.y - originalCenter.y self.setCellMovementDirectionFromDrift(xDrift, yDrift: yDrift) } open override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { UIView.animate(withDuration: 0.2, delay: 0.1, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.1, options: [.allowUserInteraction], animations: { self.center = self.originalCenter self.transform = CGAffineTransform.identity }, completion: { finished in }) } open override func touchesEstimatedPropertiesUpdated(_ touches: Set<UITouch>) { // } func setCellMovementDirectionFromDrift(_ xDrift: CGFloat, yDrift: CGFloat){ if xDrift == 0, yDrift == 0 { onCellDidMove?(.tapped) return } var movement: SPTinderViewCellMovement = .none if(xDrift > self.frame.width * scaleToRemoveCell) { movement = .right } else if(-xDrift > self.frame.width * scaleToRemoveCell) { movement = .left } else if(-yDrift > self.frame.height * scaleToRemoveCell) { movement = .top } else if(yDrift > self.frame.height * scaleToRemoveCell) { movement = .bottom } else { movement = .none } if movement != .none { self.cellMovement = movement if let cellMoveBlock = onCellDidMove { cellMoveBlock(movement) } } else { UIView.animate(withDuration: 0.5, delay: 0.1, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.5, options: [.allowUserInteraction], animations: { self.center = self.originalCenter self.transform = CGAffineTransform.identity }, completion: nil) } } } /** `SPTinderViewCellMovement` defines the four types of movement when the cell is dragged around. - None: When the cell has not moved or not been moved enough to be considered one of the other 4 movements - Top: When the cell has moved towards top - Left: When the cell has moved towards left - Bottom: When the cell has moved towards bottom - Right: When the cell has moved towards right */ @objc public enum SPTinderViewCellMovement: Int { case none case top case left case bottom case right case tapped }
38.680272
208
0.642455
e0d0d3ba1cf2052ac89b191c82731d1ce1882e51
403
// // AppDelegate.swift // Serrano Example // // Created by Matt Jones on 8/9/16. // // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool { return true } }
18.318182
151
0.689826
911c5658bb4b377e7b90aa51caac82906c6c4299
298
// // String+Localize.swift // XLLocalizeManager // // Created by xx11dragon on 2019/7/3. // Copyright © 2019 xx11dragon. All rights reserved. // import Foundation public extension String { /// 本地化 String var xl_localize: String { return XLLString(self) } }
15.684211
53
0.630872
0edb10c3b188e3ad72f66b935e6de1de30ca925c
9,917
// // MovableTextField.swift // MovableTextField // // Created by Adrian Labbé on 3/30/19. // Copyright © 2019 Adrian Labbé. All rights reserved. // import UIKit #if MAIN import InputAssistant #endif /// A class for managing a movable text field. class MovableTextField: NSObject, UITextFieldDelegate { /// The view containing this text field. let console: ConsoleViewController /// The placeholder of the text field. var placeholder = "" { didSet { textField.placeholder = placeholder } } #if MAIN /// The input assistant containing arrows and a paste button. let inputAssistant = InputAssistantView() /// Applies theme. func applyTheme() { textField.inputAccessoryView = nil inputAssistant.leadingActions = (UIApplication.shared.statusBarOrientation.isLandscape ? [InputAssistantAction(image: UIImage())] : [])+[ InputAssistantAction(image: UIImage(named: "Down") ?? UIImage(), target: self, action: #selector(down)), InputAssistantAction(image: UIImage(named: "Up") ?? UIImage(), target: self, action: #selector(up)) ] inputAssistant.trailingActions = [ InputAssistantAction(image: UIImage(named: "CtrlC") ?? UIImage(), target: self, action: #selector(interrupt)), InputAssistantAction(image: UIImage(named: "Paste") ?? UIImage(), target: textField, action: #selector(UITextField.paste(_:))), ]+(UIApplication.shared.statusBarOrientation.isLandscape ? [InputAssistantAction(image: UIImage())] : []) textField.keyboardAppearance = theme.keyboardAppearance if console.traitCollection.userInterfaceStyle == .dark { textField.keyboardAppearance = .dark } if textField.keyboardAppearance == .dark { toolbar.barStyle = .black } else { toolbar.barStyle = .default } toolbar.isTranslucent = true inputAssistant.attach(to: textField) (textField.value(forKey: "textInputTraits") as? NSObject)?.setValue(theme.tintColor, forKey: "insertionPointColor") } /// Theme used by the bar. var theme: Theme = ConsoleViewController.choosenTheme { didSet { applyTheme() } } #endif /// The toolbar containing the text field let toolbar: UIToolbar /// The text field. let textField: UITextField /// Initializes the manager. /// /// - Parameters: /// - console: The console containing the text field. init(console: ConsoleViewController) { self.console = console toolbar = Bundle(for: MovableTextField.self).loadNibNamed("TextField", owner: nil, options: nil)?.first as! UIToolbar textField = toolbar.items!.first!.customView as! UITextField super.init() #if MAIN applyTheme() #endif textField.delegate = self if #available(iOS 13.0, *) { textField.textColor = UIColor.label } NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidShow(_:)), name: UIResponder.keyboardDidShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidHide(_:)), name: UIResponder.keyboardDidHideNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil) } /// Shows the text field. func show() { toolbar.frame.size.width = console.view.safeAreaLayoutGuide.layoutFrame.width toolbar.frame.origin.x = console.view.safeAreaInsets.left toolbar.frame.origin.y = console.view.safeAreaLayoutGuide.layoutFrame.height-toolbar.frame.height toolbar.autoresizingMask = [.flexibleWidth, .flexibleBottomMargin, .flexibleTopMargin] console.view.clipsToBounds = false console.view.addSubview(toolbar) } /// Shows keyboard. func focus() { guard console.shouldRequestInput else { return } DispatchQueue.main.asyncAfter(deadline: .now()+0.25) { self.textField.becomeFirstResponder() } } /// Code called when text is sent. Receives the text. var handler: ((String) -> Void)? // MARK: - Keyboard @objc private func keyboardDidShow(_ notification: NSNotification) { // That's the typical code you just cannot understand when you are playing Clash Royale while coding // So please, open iTunes, play your playlist, focus and then go back. if console.parent?.parent?.modalPresentationStyle != .popover || console.parent?.parent?.view.frame.width != console.parent?.parent?.preferredContentSize.width { #if MAIN let inputAssistantOrigin = inputAssistant.frame.origin let yPos = inputAssistant.convert(inputAssistantOrigin, to: console.view).y /*if EditorSplitViewController.shouldShowConsoleAtBottom { yPos = inputAssistantOrigin.y } else { yPos = }*/ toolbar.frame.origin = CGPoint(x: console.view.safeAreaInsets.left, y: yPos-toolbar.frame.height) if toolbar.superview != nil, !EditorSplitViewController.shouldShowConsoleAtBottom, !toolbar.superview!.bounds.intersection(toolbar.frame).equalTo(toolbar.frame) { toolbar.frame.origin.y = console.view.safeAreaLayoutGuide.layoutFrame.height-toolbar.frame.height } #else var r = notification.userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! CGRect r = console.textView.convert(r, from:nil) toolbar.frame.origin.y = console.view.frame.height-r.height-toolbar.frame.height #endif } UIView.animate(withDuration: 0.5) { self.toolbar.alpha = 1 } console.textView.scrollToBottom() } @objc private func keyboardDidHide(_ notification: NSNotification) { toolbar.frame.origin.y = console.view.safeAreaLayoutGuide.layoutFrame.height-toolbar.frame.height if textField.isFirstResponder { // Still editing, but with a hardware keyboard keyboardDidShow(notification) } UIView.animate(withDuration: 0.5) { self.toolbar.alpha = 1 } } @objc private func keyboardWillHide(_ notification: NSNotification) { UIView.animate(withDuration: 0.5) { self.toolbar.alpha = 0 } } @objc private func keyboardWillShow(_ notification: NSNotification) { UIView.animate(withDuration: 0.5) { self.toolbar.alpha = 0 } } // MARK: - Text field delegate func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() defer { handler?(textField.text ?? "") placeholder = "" #if MAIN if let text = textField.text, !text.isEmpty { if let i = history.firstIndex(of: text) { history.remove(at: i) } history.insert(text, at: 0) historyIndex = -1 } currentInput = nil #endif textField.text = "" } return true } #if MAIN func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { defer { if historyIndex == -1 { currentInput = (textField.text as NSString?)?.replacingCharacters(in: range, with: string) } } return true } #endif // MARK: - Actions @objc private func interrupt() { placeholder = "" textField.resignFirstResponder() #if MAIN if let path = console.editorSplitViewController?.editor.document?.fileURL.path { Python.shared.interrupt(script: path) } #endif } // MARK: - History /// The current command that is not in the history. var currentInput: String? /// The index of current input in the history. `-1` if the command is not in the history. var historyIndex = -1 { didSet { if historyIndex == -1 { textField.text = currentInput } else if history.indices.contains(historyIndex) { textField.text = history[historyIndex] } } } /// The history of input. This array is reversed. The first command in the history is the last in this array. var history: [String] { get { return (UserDefaults.standard.array(forKey: "inputHistory") as? [String]) ?? [] } set { UserDefaults.standard.set(newValue, forKey: "inputHistory") UserDefaults.standard.synchronize() // Yes, I know, that's not needed, but I call it BECAUSE I WANT, I CALL THIS FUNCTION BECAUSE I WANT OK } } /// Scrolls down on the history. @objc func down() { if historyIndex > -1 { historyIndex -= 1 } } /// Scrolls up on the history. @objc func up() { if history.indices.contains(historyIndex+1) { historyIndex += 1 } } }
34.919014
169
0.601492
f443f4ff4f18193f3d9a1f6a520b14ba097b4dc1
3,151
// This test is paired with testable-multifile-other.swift. // RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module %S/Inputs/TestableMultifileHelper.swift -enable-testing -o %t // RUN: %target-swift-emit-silgen -I %t %s %S/testable-multifile-other.swift -module-name main | %FileCheck %s // RUN: %target-swift-emit-silgen -I %t %S/testable-multifile-other.swift %s -module-name main | %FileCheck %s // RUN: %target-swift-emit-silgen -I %t -primary-file %s %S/testable-multifile-other.swift -module-name main | %FileCheck %s // Just make sure we don't crash later on. // RUN: %target-swift-emit-ir -verify-sil-ownership -I %t -primary-file %s %S/testable-multifile-other.swift -module-name main -o /dev/null // RUN: %target-swift-emit-ir -verify-sil-ownership -I %t -O -primary-file %s %S/testable-multifile-other.swift -module-name main -o /dev/null @testable import TestableMultifileHelper public protocol Fooable { func foo() } struct FooImpl: Fooable, HasDefaultFoo {} public struct PublicFooImpl: Fooable, HasDefaultFoo {} // CHECK-LABEL: sil{{.*}} @$s4main7FooImplVAA7FooableA2aDP3fooyyFTW : $@convention(witness_method: Fooable) (@in_guaranteed FooImpl) -> () { // CHECK: function_ref @$s23TestableMultifileHelper13HasDefaultFooPAAE3fooyyF // CHECK: } // end sil function '$s4main7FooImplVAA7FooableA2aDP3fooyyFTW' // CHECK-LABEL: sil{{.*}} @$s4main13PublicFooImplVAA7FooableA2aDP3fooyyFTW : $@convention(witness_method: Fooable) (@in_guaranteed PublicFooImpl) -> () { // CHECK: function_ref @$s23TestableMultifileHelper13HasDefaultFooPAAE3fooyyF // CHECK: } // end sil function '$s4main13PublicFooImplVAA7FooableA2aDP3fooyyFTW' private class PrivateSub: Base { fileprivate override func foo() {} } class Sub: Base { internal override func foo() {} } public class PublicSub: Base { public override func foo() {} } // CHECK-LABEL: sil_vtable PrivateSub { // CHECK-NEXT: #Base.foo!1: {{.*}} : @$s4main10PrivateSub33_F1525133BD493492AD72BF10FBCB1C52LLC3fooyyF // CHECK-NEXT: #Base.init!allocator.1: {{.*}} : @$s4main10PrivateSub33_F1525133BD493492AD72BF10FBCB1C52LLCADycfC // CHECK-NEXT: #PrivateSub.deinit!deallocator.1: @$s4main10PrivateSub33_F1525133BD493492AD72BF10FBCB1C52LLCfD // CHECK-NEXT: } // CHECK-LABEL: sil_vtable Sub { // CHECK-NEXT: #Base.foo!1: {{.*}} : @$s4main3SubC3fooyyF // CHECK-NEXT: #Base.init!allocator.1: {{.*}} : @$s4main3SubCACycfC // CHECK-NEXT: #Sub.deinit!deallocator.1: @$s4main3SubCfD // CHECK-NEXT: } // CHECK-LABEL: sil_vtable [serialized] PublicSub { // CHECK-NEXT: #Base.foo!1: {{.*}} : @$s4main9PublicSubC3fooyyF // CHECK-NEXT: #Base.init!allocator.1: {{.*}} : @$s4main9PublicSubCACycfC // CHECK-NEXT: #PublicSub.deinit!deallocator.1: @$s4main9PublicSubCfD // CHECK-NEXT: } // CHECK-LABEL: sil_witness_table hidden FooImpl: Fooable module main { // CHECK-NEXT: method #Fooable.foo!1: {{.*}} : @$s4main7FooImplVAA7FooableA2aDP3fooyyFTW // CHECK-NEXT: } // CHECK-LABEL: sil_witness_table [serialized] PublicFooImpl: Fooable module main { // CHECK-NEXT: method #Fooable.foo!1: {{.*}} : @$s4main13PublicFooImplVAA7FooableA2aDP3fooyyFTW // CHECK-NEXT: }
46.338235
153
0.734687
29265d5ad304fe12553d84960afabc22d500bb20
4,719
// // BookIssueViewController.swift // LibraryManagementSystem // // Created by Rahul Zore on 4/27/18. // Copyright © 2018 Rahul Zore. All rights reserved. // import UIKit import CoreData class BookIssueViewController: UIViewController { @IBOutlet weak var bookIssueIDField: UITextField! @IBOutlet weak var nuidFiled: UITextField! @IBOutlet weak var returnDateField: UIDatePicker! @IBOutlet weak var issueBookBtn: RoundedWhiteButton! var book = [String:AnyObject]() var issuedStudent : Student? var issuedBook = NSEntityDescription.insertNewObject(forEntityName: "Book", into: PersistenceService.context) as! Book override func viewDidLoad() { super.viewDidLoad() let fetchRequest: NSFetchRequest<Student> = Student.fetchRequest() do{ SingletonController.studentArray = try PersistenceService.context.fetch(fetchRequest) }catch{ } for s in SingletonController.studentArray{ print(s.name) } let id=book["id"] as! String var subtitles:String? var authors:String? if let volumeInfo = book["volumeInfo"] as? [String:AnyObject]{ let title=volumeInfo["title"] as? String if let subtitle = volumeInfo["subtitle"] as? String { let subtitles=subtitle } var authorss:[String] = volumeInfo["authors"] as! [String] var author = "" for a in authorss{ author = author + a } authors=author // issuedBook.id=id // issuedBook.title=title // issuedBook.subtitle=subtitles // issuedBook.authors=authors if id != nil { issuedBook.id = id } if title != nil { issuedBook.title = title } else { issuedBook.title = "" } if subtitles != nil { issuedBook.subtitle = subtitles } else { issuedBook.subtitle = "" } if authors != nil { issuedBook.authors = authors } else { issuedBook.authors = "" } } // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func datePickerChanged(_ sender: UIDatePicker) { returnDateField.minimumDate = Date() } @IBAction func issueBookButton(_ sender: Any) { if (bookIssueIDField.text?.isEmpty)! || (nuidFiled.text?.isEmpty)!{ self.throwAlert(reason: "All fields are mandatory") return } guard let nuid = nuidFiled.text else {return} var returndate = returnDateField.date var flag:Bool = false for student in SingletonController.studentArray{ if student.nuid == nuid{ issuedStudent = student flag = true break } } if flag == false { self.throwAlert(reason: "Student not found") return } let issuedDate = Date() let returnDate = returnDateField.date let id = bookIssueIDField.text print(issuedBook.id) SingletonController.createBookIssuance(student: issuedStudent!, book: issuedBook, issued: true, returned: false, issuedDate: issuedDate, returnedDate: returnDate, lateDays: 0, lateFee: 0, id: id!) self.throwAlert(reason: "Book issued successfully") } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ func throwAlert(reason :String){ let alert = UIAlertController(title: "Library Management System", message:reason , preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: { action in })) self.present(alert, animated: true, completion: nil) } }
30.843137
204
0.5605
dd128f46abb6cd1cd509b89b6bf8097a40c91ed2
978
// // CircleSolver.swift // iGeometry // // Created by Nail Sharipov on 11.06.2020. // import iGeometry public extension Array where Element == CircleDefinition { func union(maxRadius: Float, iGeom: IntGeom) -> PlainShapeList { guard self.count > 2 else { if let circle = self.first { return PlainShapeList(plainShape: PlainShape(points: circle.getPath(maxRadius: maxRadius, iGeom: iGeom))) } else { return .empty } } // sort let circles = self.sorted(by: { $0.minX > $1.minX }) var shapes = [PlainShape]() for circle in circles { let path = circle.getPath(maxRadius: maxRadius, iGeom: iGeom) shapes.union(path: path) } var result = PlainShapeList.empty for shape in shapes { result.add(plainShape: shape) } return result } }
24.45
121
0.541922
b96cb7d5c4a91679bb1319e0cbfad170054ad160
2,304
// // Constants.swift // Kebab // // Created by Sasha Prokhorenko on 9/21/15. // Copyright © 2015 Minikin. All rights reserved. // // MARK: - Notifications constants enum Notifications { static let kebabFailedtoParseJSON = "me.minikin.kebab.failed.to.parse.json" static let hideTipsCollectionViewNotification = "kebab.ocklock.hide.tips.collection.view." static let kebabGeoCoderCantParseData = "me.minikin.kebab.geo.coder.cant.parse.data" static let kebabGetPlaceOperationStarted = "me.minikin.kebab.get.place.data.started" static let kebabGetPlaceOperationFinished = "me.minikin.kebab.get.place.data.finished" static let kebabFailToConnectToTheInternet = "me.minikin.kebab.fail.to.connect.to.the.internet" static let kebabDidStartLocatingUser = "me.minikin.kebab.did.start.locating.user" static let kebabDidFinishLocatingUser = "me.minikin.kebab.did.finish.locating.user" static let kebabDidFinishLocatingUserWithError = "me.minikin.kebab.did.finish.with.error.locating.user" } // MARK: - Properties enum Utils { // Used in predicate in RootViewController static let earthRadius = 6378137.0 // In case we can't get a correct img url we use this one. Check ParsePhotoOperation & ParsePlaceOperation for details. static let flickrPhotoUrl = "https://c2.staticflickr.com/2/1509/24246343163_50164b3e0f_o.png" } // MARK: - Foursquare data enum FoursquareData : String { // FIXME:- PUT YOUR CLINET ID & SECRET HERE! case clientId = "Your client Id" case clientSecret = "Your client secret" case baseFoursquareUrl = "https://api.foursquare.com/v2/venues/" case version = "20150920" case limitSearch = "50" case limitPhotos = "5" case limitTips = "10" } // MARK: - Junkfood categories enum JunkFoodType: String { case Kebab case Burger case Chips case Pizza case Chicken case Pies case Sandwiches case Sushi case Rolls case Coffee } // MARK: - Search radius enum SearchRadius : String { case one = "1500" case two = "1000" case three = "700" case four = "500" case five = "200" } // MARK: - Photo sizes enum PhotoSize : String { case small = "36x36" case medium = "200x200" case large = "500x500" } // MARK: - KebabError Type enum KebabError : ErrorType { case NoPhotoUrl }
24
121
0.721788
f80673cd4ec4d490a8980d32fd1e26201cc1b6b4
165
// // Response.swift // StoryForge // // Created by Martin Vytrhlík on 28/03/16. // Copyright © 2016 Martin Vytrhlík. All rights reserved. // import Foundation
16.5
58
0.690909
ef802935aa03167404435aedb88617c1025b681c
635
// // AppDelegate.swift // MacSwiftDemo // // Created by C.W. Betts on 10/18/14. // Copyright (c) 2014 C.W. Betts. All rights reserved. // import Cocoa import SVGKit.SVGKit @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(aNotification: NSNotification) { // Insert code here to initialize your application SVGKit.enableLogging() //Don't attempt to use SVGKImageRep: just unload it. SVGKImageRep.unloadSVGKImageRep() } func applicationWillTerminate(aNotification: NSNotification) { // Insert code here to tear down your application } }
19.84375
68
0.732283
fe0599fd0f32a5a0cbd5b367d638eaf539153a3e
1,107
// // AppFlowBuilder.swift // ReduxApp // // Created by Ihor Yarovyi on 1/4/22. // import SwiftUI import Redux /* import SignIn */ import LaunchScreen struct AppFlowBuilder { static func make(basedOn graph: Graph) -> AppFlow { /* if graph.session.hasSessionResult { if graph.session.isActive { return .general(.main(onMain: EmptyView().eraseToAnyView())) } else { if graph.deepLink.isActive { if graph.signUpForm.hasVerificationResult { return .verifyEmail(onVerify: VerifyEmailConnector().eraseToAnyView()) } else if graph.restorePassword.hasVerificationResult { return .verifyRestoreToken(onVerify: VerifyRestoreTokenConnector().eraseToAnyView()) } } else { return .general(.auth(onAuth: SignIn.Connector().eraseToAnyView())) } } } */ return .launchScreen(onLaunch: LaunchScreen.Connector().eraseToAnyView()) } }
29.131579
108
0.563686
de3b4dc6836da67f6f8e3355efc4dfb17a0148cf
1,014
// // Copyright (c) 2015 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit import Firebase @objc(MyTopPostsViewController) class MyTopPostsViewController: PostListViewController { override func getQuery() -> FIRDatabaseQuery { // [START my_top_posts_query] // My top posts by number of stars let myTopPostsQuery = (ref.child("user-posts").child(getUid())).queryOrdered(byChild: "starCount") // [END my_top_posts_query] return myTopPostsQuery } }
33.8
102
0.732742
fbbc28249afdf777b0c76a0ba07ee67e6541be4e
1,663
// // VideoClipLine.swift // VideoClipAnnotationEditor // // Copyright © 2015 Fleur de Swift. All rights reserved. // import Foundation import ExtraDataStructures internal class VideoClipLine { var threads: [VideoClipAnnotationThread] = []; var entries: [VideoClipLineEntry] = []; func placeAnnotation(clip: VideoClip, annotation: VideoClipAnnotation, position: NSRange, edge: EdgeType) -> VideoClipAnnotationThread { for thread in threads { if thread.reserveAnnotation(clip, annotation: annotation, position: position, edge: edge) { return thread; } } let newThread = VideoClipAnnotationThread(); newThread.reserveAnnotation(clip, annotation: annotation, position: position, edge: edge); threads.append(newThread); return newThread; } func placeClip(clip: VideoClip, time: TimeRange, position: NSRange, previewConfig: VideoClipPreviewConfiguration) -> VideoClipLineEntry { let full = TimeRange(start: 0, end: clip.duration); let entry = VideoClipLineEntry(clip: clip, time: time, position: position, edge: full.edge(time), previewConfig: previewConfig); entries.append(entry); for annotation in clip.annotations { let intersect = time.intersection(annotation.time); if !intersect.isValid { continue; } placeAnnotation(clip, annotation: annotation, position: entry.position(intersect), edge: annotation.time.edge(intersect)) } return entry; } }
34.645833
141
0.635598
039707f95aef1b219c579024860cc951cb8299db
1,687
// // SearchInteractorTests.swift // SpotifySearch // // Created by Arash Goodarzi on 11/1/19. // Copyright (c) 2019 Arash Goodarzi. All rights reserved. // // This file was generated by the Clean Swift Xcode Templates so // you can apply clean architecture to your iOS and Mac projects, // see http://clean-swift.com // @testable import SpotifySearch import XCTest class SearchInteractorTests: XCTestCase { // MARK: Subject under test var sut: SearchInteractor! // MARK: Test lifecycle override func setUp() { super.setUp() setupSearchInteractor() } override func tearDown() { super.tearDown() } // MARK: Test setup func setupSearchInteractor() { sut = SearchInteractor() } // MARK: Test doubles class SearchPresentationLogicSpy: SearchPresentationLogic { var presentSearchTracksCalled = false func presentSearchTracks(response: Search.Tracks.Response) { presentSearchTracksCalled = true } } // MARK: Tests func testPresentSearchTracks() { //Given let spy = SearchPresentationLogicSpy() sut.presenter = spy //When let request = Search.Tracks.Request(query: "a qeury") self.sut.searchTracks(request: request) //Then let workItem = DispatchWorkItem { XCTAssertTrue(spy.presentSearchTracksCalled, "should ask the presenter to present the result") } let timeOut = DispatchTime.now() + 5 DispatchQueue.main.asyncAfter(deadline: timeOut, execute: workItem) } }
24.808824
106
0.620628
de9186151f86389798ee364491fd719dac050d4c
1,398
// // AppDelegate.swift // PaidBills // // Created by Ronaldo Gomes on 16/08/21. // import UIKit import Firebase @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. FirebaseApp.configure() return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } }
35.846154
179
0.744635
22f8b1fbb69a17ca1d539a343de006333dce0a95
2,300
// // ForgotPasswordVC.swift // AkilaDilshan-COBSCComp171p-015 // // Created by Akila Dilshan on 5/13/19. // Copyright © 2019 Akila Dilshan. All rights reserved. // import UIKit import FirebaseAuth class ForgotPasswordVC: UIViewController { //MARK:- UI Outlets @IBOutlet weak var closeButton: UIButton! @IBOutlet weak var emailTextField: UITextField! //MARK:- Variables var utill = Utill() let alertService = AlertService() override func viewDidLoad() { super.viewDidLoad() utill.setupTextFields(textFields: [emailTextField]) } //MARK:- Functions func retriveNewPassword(userName:String){ Auth.auth().sendPasswordReset(withEmail: userName) { (error) in if (error != nil){ self.alertService.alert(title: "Error", body: error!.localizedDescription, buttonTitle: "Try Again", isSuccess: false, isDone: false, completion: { self.retriveNewPassword(userName: userName) }) }else{ self.utill.showToast(message: "Password reset link has been sent your email", view: self.view, width: 350) DispatchQueue.main.asyncAfter(deadline: .now() + 2, execute: { self.dismiss(animated: true, completion: nil) }) } } } //MARK:- UI Actions @IBAction func closePasswordView(_ sender: Any) { let transition: CATransition = CATransition() transition.duration = 0.5 transition.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut) transition.type = CATransitionType.reveal transition.subtype = CATransitionSubtype.fromRight self.view.window!.layer.add(transition, forKey: nil) self.dismiss(animated: false, completion: nil) } @IBAction func getNewPassword(_ sender: Any) { if ((emailTextField.text?.isEmpty)!){ utill.showToast(message: "Please fill the fields", view: self.view, width: 350) return }else{ retriveNewPassword(userName: emailTextField.text!) } } }
28.75
163
0.594783
e6fc6e97ecc3718fe2bbcca55042d5f4a4030401
710
// // AlphabeticOrderingTests.swift // VIAddressBookKit // // Created by Nils Fischer on 09.10.14. // Copyright (c) 2014 viWiD Webdesign & iOS Development. All rights reserved. // import XCTest import VIAddressBookKit class AlphabeticOrderingTests: XCTestCase { /*struct AlphabeticOrderedString: AlphabeticOrdering { let string: String? var alphabeticOrderingString: String? { return string } } func testExample() { let alice = AlphabeticOrderedString(string: "Alice") let bob = AlphabeticOrderedString(string: "Bob") XCTAssert(isOrderedAlphabetically(alice, bob), "Alice and Bob should be ordered alphabetically") }*/ }
25.357143
104
0.683099
64037c3da466d0d914ff571e79ff2dfa15fa9898
212
// // ProductListViewDelegate.swift // Teste_ML // // Created by Bruna Drago on 25/09/21. // import Foundation protocol ProductListViewDelegate: AnyObject { func didSelectProduct(product:APIResponse) }
15.142857
46
0.740566
cc7d773c57daacb0da8dd234976d0c90ef4760b4
7,506
// // TSChatActionBarView.swift // TSWeChat // // Created by Hilen on 12/16/15. // Copyright © 2015 Hilen. All rights reserved. // import UIKit import UIColor_Hex_Swift let kChatActionBarOriginalHeight: CGFloat = 50 //ActionBar orginal height let kChatActionBarTextViewMaxHeight: CGFloat = 120 //Expandable textview max height /** * 表情按钮和分享按钮来控制键盘位置 */ protocol TSChatActionBarViewDelegate: class { /** 不显示任何自定义键盘,并且回调中处理键盘frame 当唤醒的自定义键盘时候,这时候点击切换录音 button。需要隐藏掉 */ func chatActionBarRecordVoiceHideKeyboard() /** 显示表情键盘,并且处理键盘高度 */ func chatActionBarShowEmotionKeyboard() /** 显示分享键盘,并且处理键盘高度 */ func chatActionBarShowShareKeyboard() } class TSChatActionBarView: UIView { enum ChatKeyboardType: Int { case `default`, text, emotion, share } var keyboardType: ChatKeyboardType? = .default weak var delegate: TSChatActionBarViewDelegate? var inputTextViewCurrentHeight: CGFloat = kChatActionBarOriginalHeight @IBOutlet weak var inputTextView: UITextView! { didSet{ inputTextView.font = UIFont.systemFont(ofSize: 17) inputTextView.layer.borderColor = UIColor.init(ts_hexString:"#DADADA").cgColor inputTextView.layer.borderWidth = 1 inputTextView.layer.cornerRadius = 5.0 inputTextView.scrollsToTop = false inputTextView.textContainerInset = UIEdgeInsetsMake(7, 5, 5, 5) inputTextView.backgroundColor = UIColor.init(ts_hexString:"#f8fefb") inputTextView.returnKeyType = .send inputTextView.isHidden = false inputTextView.enablesReturnKeyAutomatically = true inputTextView.layoutManager.allowsNonContiguousLayout = false inputTextView.scrollsToTop = false }} @IBOutlet weak var voiceButton: TSChatButton! @IBOutlet weak var emotionButton: TSChatButton! { didSet{ emotionButton.showTypingKeyboard = false }} @IBOutlet weak var shareButton: TSChatButton! { didSet{ shareButton.showTypingKeyboard = false }} @IBOutlet weak var recordButton: UIButton! { didSet{ recordButton.setBackgroundImage(UIImage.ts_imageWithColor(UIColor.init(ts_hexString:"#F3F4F8")), for: .normal) recordButton.setBackgroundImage(UIImage.ts_imageWithColor(UIColor.init(ts_hexString:"#C6C7CB")), for: .highlighted) recordButton.layer.borderColor = UIColor.init(ts_hexString:"#C2C3C7").cgColor recordButton.layer.borderWidth = 0.5 recordButton.layer.cornerRadius = 5.0 recordButton.layer.masksToBounds = true recordButton.isHidden = true }} override init (frame: CGRect) { super.init(frame : frame) self.initContent() } convenience init () { self.init(frame:CGRect.zero) self.initContent() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func initContent() { let topBorder = UIView() let bottomBorder = UIView() topBorder.backgroundColor = UIColor.init(ts_hexString:"#C2C3C7") bottomBorder.backgroundColor = UIColor.init(ts_hexString: "#C2C3C7") self.addSubview(topBorder) self.addSubview(bottomBorder) topBorder.snp.makeConstraints { (make) -> Void in make.top.left.right.equalTo(self) make.height.equalTo(0.5) } bottomBorder.snp.makeConstraints { (make) -> Void in make.bottom.left.right.equalTo(self) make.height.equalTo(0.5) } } override func awakeFromNib() { initContent() } deinit { log.verbose("deinit") } } // MARK: - @extension TSChatActionBarView //控制键盘的各种互斥事件 extension TSChatActionBarView { //重置所有 Button 的图片 func resetButtonUI() { self.voiceButton.setImage(TSAsset.Tool_voice_1.image, for: UIControlState()) self.voiceButton.setImage(TSAsset.Tool_voice_2.image, for: .highlighted) self.emotionButton.setImage(TSAsset.Tool_emotion_1.image, for: UIControlState()) self.emotionButton.setImage(TSAsset.Tool_emotion_2.image, for: .highlighted) self.shareButton.setImage(TSAsset.Tool_share_1.image, for: UIControlState()) self.shareButton.setImage(TSAsset.Tool_share_2.image, for: .highlighted) } //当是表情键盘 或者 分享键盘的时候,此时点击文本输入框,唤醒键盘事件。 func inputTextViewCallKeyboard() { self.keyboardType = .text self.inputTextView.isHidden = false //设置接下来按钮的动作 self.recordButton.isHidden = true self.voiceButton.showTypingKeyboard = false self.emotionButton.showTypingKeyboard = false self.shareButton.showTypingKeyboard = false } //显示文字输入的键盘 func showTyingKeyboard() { self.keyboardType = .text self.inputTextView.becomeFirstResponder() self.inputTextView.isHidden = false //设置接下来按钮的动作 self.recordButton.isHidden = true self.voiceButton.showTypingKeyboard = false self.emotionButton.showTypingKeyboard = false self.shareButton.showTypingKeyboard = false } //显示录音 func showRecording() { self.keyboardType = .default self.inputTextView.resignFirstResponder() self.inputTextView.isHidden = true if let delegate = self.delegate { delegate.chatActionBarRecordVoiceHideKeyboard() } //设置接下来按钮的动作 self.recordButton.isHidden = false self.voiceButton.showTypingKeyboard = true self.emotionButton.showTypingKeyboard = false self.shareButton.showTypingKeyboard = false } /* 显示表情键盘 当点击唤起自定义键盘时,操作栏的输入框需要 resignFirstResponder,这时候会给键盘发送通知。 通知在 TSChatViewController+Keyboard.swift 中需要对 actionbar 进行重置位置计算 */ func showEmotionKeyboard() { self.keyboardType = .emotion self.inputTextView.resignFirstResponder() self.inputTextView.isHidden = false if let delegate = self.delegate { delegate.chatActionBarShowEmotionKeyboard() } //设置接下来按钮的动作 self.recordButton.isHidden = true self.emotionButton.showTypingKeyboard = true self.shareButton.showTypingKeyboard = false } //显示分享键盘 func showShareKeyboard() { self.keyboardType = .share self.inputTextView.resignFirstResponder() self.inputTextView.isHidden = false if let delegate = self.delegate { delegate.chatActionBarShowShareKeyboard() } //设置接下来按钮的动作 self.recordButton.isHidden = true self.emotionButton.showTypingKeyboard = false self.shareButton.showTypingKeyboard = true } //取消输入 func resignKeyboard() { self.keyboardType = .default self.inputTextView.resignFirstResponder() //设置接下来按钮的动作 self.emotionButton.showTypingKeyboard = false self.shareButton.showTypingKeyboard = false } /** <暂无用到> 控制切换键盘的时候光标的颜色 如果是切到 表情或分享 ,就是透明 如果是输入文字,就是蓝色 - parameter color: 目标颜色 */ fileprivate func changeTextViewCursorColor(_ color: UIColor) { self.inputTextView.tintColor = color UIView.setAnimationsEnabled(false) self.inputTextView.resignFirstResponder() self.inputTextView.becomeFirstResponder() UIView.setAnimationsEnabled(true) } }
31.275
123
0.664002
69412a9177541d69d4cec66b474b43e25e76638c
2,409
// // RequestService.swift // MusicNet // // Created by Genaro Codina Reverter on 21/2/21. // import Foundation public enum APIError: Error { case missingData } public enum Result<T> { case success(T) case failure(Error) } public final class RequestService: RequestServiceProtocol { typealias SerializationFunction<T> = (Data?, URLResponse?, Error?) -> Result<T> public var defaultSession: URLSession public var sessionConfig: URLSessionConfiguration public var tokenEntity: TokenEntity? public init() { sessionConfig = URLSessionConfiguration.default defaultSession = URLSession(configuration: sessionConfig) } // MARK: - Public methods public func setAccessToken(token: TokenEntity) { let authValue: String = "Bearer \(token.accessToken)" sessionConfig.httpAdditionalHeaders = ["Authorization": authValue] defaultSession = URLSession(configuration: sessionConfig) tokenEntity = TokenEntity(accessToken: token.accessToken, expiresIn: token.expiresIn, tokenType: token.tokenType) } public func request<T: Decodable>(_ url: URL, completion: @escaping (Result<T>) -> Void) -> URLSessionDataTask { return request(url, serializationFunction: serializeJSON, completion: completion) } // MARK: - Private methods private func request<T>(_ url: URL, serializationFunction: @escaping SerializationFunction<T>, completion: @escaping (Result<T>) -> Void) -> URLSessionDataTask { let dataTask = defaultSession.dataTask(with: url) { data, response, error in let result: Result<T> = serializationFunction(data, response, error) DispatchQueue.main.async { completion(result) } } dataTask.resume() return dataTask } private func serializeJSON<T: Decodable>(with data: Data?, response: URLResponse?, error: Error?) -> Result<T> { if let error = error { return .failure(error) } guard let data = data else { return .failure(APIError.missingData) } do { let serializedValue = try JSONDecoder().decode(T.self, from: data) return .success(serializedValue) } catch let error { return .failure(error) } } }
30.1125
121
0.636364
61c20151900d63174eb425ef61283c9b13db26bf
1,785
import XCTest @testable import AppGroups final class AppGroupTests: XCTestCase { func testEquatingAndHashing() { let appGroup1 = AppGroup(identifier: "group.test.one") let appGroup2 = AppGroup(identifier: "group.test.two") let appGroup3 = AppGroup(identifier: "group.test.one") XCTAssertEqual(appGroup1, appGroup3) XCTAssertNotEqual(appGroup1, appGroup2) XCTAssertNotEqual(appGroup2, appGroup3) XCTAssertEqual(appGroup1.hashValue, appGroup3.hashValue) XCTAssertNotEqual(appGroup1.hashValue, appGroup2.hashValue) XCTAssertNotEqual(appGroup2.hashValue, appGroup3.hashValue) } func testCodable() throws { struct Wrapper: Codable { let group: AppGroup } let appGroup = AppGroup(identifier: "group.test.coding") let data = try JSONEncoder().encode(Wrapper(group: appGroup)) XCTAssertEqual(String(decoding: data, as: UTF8.self), #"{"group":"\#(appGroup.identifier)"}"#) let decodedGroup = try JSONDecoder().decode(Wrapper.self, from: data).group XCTAssertEqual(decodedGroup, appGroup) } func testAccessors() { let appGroup = AppGroup(identifier: "group.test.accessors") XCTAssertNotNil(appGroup.userDefaults) XCTAssertNotNil(appGroup.fileSystem) } func testFileSystem() { let fs = AppGroup.FileSystem(root: URL(fileURLWithPath: "/Somewhere/")) XCTAssertEqual(fs.library.path, "/Somewhere/Library") XCTAssertEqual(fs.applicationSupport.path, "/Somewhere/Library/Application Support") XCTAssertEqual(fs.caches.path, "/Somewhere/Library/Caches") XCTAssertEqual(fs.preferences.path, "/Somewhere/Library/Preferences") } }
38.804348
92
0.677311
08af167af171ed75ff26045216dc6cca9392562b
1,302
/******************************************************************************* * Copyright 2019 alladin-IT GmbH * * 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 /// Measurement agent registration response object which is returned to the measurement agent after successful registration. /// For convenience this response also contains the current settings. class RegistrationResponse: Codable { /// The generated measurement agent UUID. var agentUuid: String? /// The settings response object sent to the measurement agent. var settings: SettingsResponse? /// enum CodingKeys: String, CodingKey { case agentUuid = "agent_uuid" case settings } }
37.2
124
0.646697
db2d4a28f2c54e76840f247c2a40e26f8f4e0fe4
2,491
// // BorrowersAccountViewController.swift // EWallet // // Created by Rishabh Yadav on 8/23/20. // Copyright © 2020 SouthSoft. All rights reserved. // import UIKit class BorrowersAccountViewController: BaseViewController { static var storyBoardId: String = "BorrowersAccountViewController" static var storyBoardName: String = Storyboard.main @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() showBackButtonForcelyWhenLoad = true setNavigationBar(title: "Borrower's Account", leftBtnImage: UIImage(named: "hamburger_icon") ?? UIImage(), rightBtnImage: UIImage(named: "profile_dot_icon")) setupTableView() } fileprivate func setupTableView(){ tableView.estimatedRowHeight = 100 tableView.rowHeight = UITableView.automaticDimension tableView.estimatedSectionHeaderHeight = 35 tableView.sectionHeaderHeight = UITableView.automaticDimension tableView.estimatedSectionFooterHeight = CGFloat.zero tableView.sectionFooterHeight = CGFloat.zero tableView.register(UINib(nibName: BorrowersTableViewCell.reuseId, bundle: nil), forCellReuseIdentifier: BorrowersTableViewCell.reuseId) } override func onBackButtonPressed(button: UIButton) { self.slideMenuController()?.openLeft() } override func onRightButtonPressed(button: UIButton) { let profileVC = UserProfileViewController.instantiateFromStoryBoard() navigationController?.pushViewController(profileVC, animated: true) } } extension BorrowersAccountViewController:UITableViewDelegate, UITableViewDataSource{ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 6 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: BorrowersTableViewCell.reuseId, for: indexPath) return cell } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = TableTitleHeaderView() headerView.label.text = "Account Breakdown" return headerView } func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return nil } }
35.084507
143
0.69731
9065b9ad9e4befd72cb0603c1ebc0b696e10acfb
351
// // SunriseSunsetManager.swift // VaporApp // // Created by Eric on 25/09/2016. // // import Foundation import Dispatch import RxSwift protocol SunriseSunsetServicable { var sunriseTimeObserver : ReplaySubject<String> {get} var sunsetTimeObserver : ReplaySubject<String> {get} init(httpClient:HttpClientable, refreshPeriod: Int) }
17.55
57
0.74359
c1ee9ff4338dc9bb9694b8fb3c40d939e6d6cf15
2,372
// // ADSQLColumnConstraint.swift // ActionControls // // Created by Kevin Mullins on 10/24/17. // Copyright © 2017 Appracatappra, LLC. All rights reserved. // import Foundation /** Holds information about a constraint applied to a Column Definition that has been parsed from a SQL CREATE TABLE instruction. */ public struct ADSQLColumnConstraint { // MARK: - Enumerations. /// Defines the type of column constraint. public enum ColumnConstraintType { /// The column is the primary key for the table in an ascending order. case primaryKeyAsc /// The column is the primary key for the table in a descending order. case primaryKeyDesc /// The column's value cannot be NULL. case notNull /// The column's value must be unique inside the table. case unique /// A custom constraint is being applied to the columns value. case check /// If this column is NULL, it will be replaced with this default value. case defaultValue /// The columns has a collation constraint. case collate /// The column value is a foreign key to another table's row. case foreignKey } // MARK: - Properties /// The type of the constraint. public var type: ColumnConstraintType = .primaryKeyAsc /// If the column is a PRIMARY KEY of the INTEGER type, is it automatically incremented when a new row is created in the table. public var autoIncrement: Bool = false /// Defines how conflicts should be handled for this column. public var conflictHandling: ADSQLConflictHandling = .none /// Holds the expression for a Check or Default Value constraint. public var expression: ADSQLExpression? // MARK: - Initializers /// Initializes a new instance of the Column Constraint. public init() { } /** Initializes a new instance of the Column Constraint. - Parameters: - type: The type of constraint being created. - expression: An expression for a Check or Default Value constraint. */ public init(ofType type: ColumnConstraintType, withExpression expression: ADSQLExpression? = nil) { self.type = type self.expression = expression } }
31.626667
131
0.645868
3ac51ba250144b3b6a43248f31b12dacb38bb0ee
2,560
// Copyright 2020 Penguin Authors // // 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 PenguinParallelWithFoundation import XCTest final class NonblockingConditionTests: XCTestCase { typealias Cond = NonblockingCondition<PosixConcurrencyPlatform> func testSimple() { // Spawn 3 threads to wait on a `Cond`. Wait until they've started, and then notify one, and // then notify all. let plt = PosixConcurrencyPlatform() var waiterCount = 0 let coordCondVar = PosixConcurrencyPlatform.ConditionMutex() let nbc = Cond(threadCount: 3) var threads = [PosixConcurrencyPlatform.Thread]() for i in 0..<3 { let thread = plt.makeThread(name: "test thread \(i)") { coordCondVar.lock() waiterCount += 1 nbc.preWait() coordCondVar.unlock() nbc.commitWait(i) // Should be woken up. } threads.append(thread) } coordCondVar.lock() coordCondVar.await { waiterCount == 3 } nbc.notify() nbc.notify(all: true) for i in 0..<3 { threads[i].join() } } func testRepeatedNotification() { let nbc = Cond(threadCount: 3) for _ in 0..<1000 { nbc.notify() } } func testNotifyWhileCommitting() { let nbc = Cond(threadCount: 3) nbc.preWait() // Thread 1 nbc.notify() // Thread 2 nbc.commitWait(1) // Should not go to sleep, but instead consume the previous notify. } func testNotifyAllWhileMultipleCommitting() { let nbc = Cond(threadCount: 5) nbc.preWait() // Thread 1 nbc.preWait() // Thread 2 nbc.preWait() // Thread 3 nbc.notify(all: true) // Thread 4 nbc.preWait() // Thread 5 nbc.commitWait(1) nbc.cancelWait() // Thread 5 nbc.commitWait(2) nbc.commitWait(3) } static var allTests = [ ("testSimple", testSimple), ("testRepeatedNotification", testRepeatedNotification), ("testNotifyWhileCommitting", testNotifyWhileCommitting), ("testNotifyAllWhileMultipleCommitting", testNotifyAllWhileMultipleCommitting), ] }
29.767442
96
0.674609
2991acb2f88330ee2c97d24b8c834f45220a9fcf
2,542
// // SocketIOEventView.swift // Pods // // Created by Kenneth on 27/1/2016. // // final class LiveChatTableView: UITableView { //MARK: Init required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } override init(frame: CGRect, style: UITableViewStyle) { super.init(frame: frame, style: style) commonInit() } private func commonInit() { separatorStyle = .None backgroundColor = UIColor.clearColor() showsVerticalScrollIndicator = false tableFooterView = UIView() rowHeight = UITableViewAutomaticDimension estimatedRowHeight = 44.0 keyboardDismissMode = .Interactive let podBundle = NSBundle(forClass: self.classForCoder) if let bundleURL = podBundle.URLForResource("SocketIOChatClient", withExtension: "bundle") { if let bundle = NSBundle(URL: bundleURL) { registerNib(UINib(nibName: "MessageCell", bundle: bundle), forCellReuseIdentifier: "MessageCell") registerNib(UINib(nibName: "UserJoinCell", bundle: bundle), forCellReuseIdentifier: "UserJoinCell") }else { assertionFailure("Could not load xib from bundle") } }else { assertionFailure("Could not create a path to the bundle") } transform = CGAffineTransformMakeScale (1,-1); } } //MARK: Handle Touches extension LiveChatTableView { override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { if let superview = superview { superview.touchesBegan(touches, withEvent: event) } super.touchesBegan(touches, withEvent: event) } override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { if let superview = superview { superview.touchesEnded(touches, withEvent: event) } super.touchesEnded(touches, withEvent: event) } override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) { if let superview = superview { superview.touchesCancelled(touches, withEvent: event) } super.touchesCancelled(touches, withEvent: event) } override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { if let superview = superview { superview.touchesMoved(touches, withEvent: event) } super.touchesMoved(touches, withEvent: event) } }
33.447368
115
0.635327
5d5bdb22e9ff6f10e2366cff4c9f0346880ea6ac
12,321
#if canImport(UIKit) import UIKit import AVFoundation public final class CameraFinderView: UIView, CameraFinderViewInterface { // MARK: - IBOutlet // swiftlint:disable private_outlet @IBOutlet public private(set) weak var captureVideoPreviewView: AVCaptureVideoPreviewView! @IBOutlet public private(set) weak var contentView: UIView! // swiftlint:enable private_outlet @IBOutlet fileprivate weak var gridView: GridView! @IBOutlet fileprivate weak var focusIndicatorView: FocusIndicatorView! @IBOutlet fileprivate weak var exposureIndicatorView: ExposureIndicatorView! @IBOutlet fileprivate weak var zoomIndicatorButton: ZoomIndicatorButton! @IBOutlet fileprivate weak var shutterAnimationView: ShutterAnimationView! @IBOutlet fileprivate weak var captureVideoPreviewViewTapGestureRecognizer: UITapGestureRecognizer! @IBOutlet fileprivate weak var captureVideoPreviewViewPinchGestureRecognizer: UIPinchGestureRecognizer! // MARK: - UIView override public var contentMode: UIView.ContentMode { didSet { updateSubviewContentModes() } } override public func didMoveToWindow() { super.didMoveToWindow() if let _ = window { updateSubviewContentModes() } } private func updateSubviewContentModes() { if let captureVideoPreviewView = captureVideoPreviewView { captureVideoPreviewView.contentMode = contentMode } if let gridView = gridView { gridView.contentMode = contentMode setNeedsLayout() } } override public func layoutSubviews() { super.layoutSubviews() if let gridView = gridView { gridView.bounds = CGRect(origin: .zero, size: gridViewSize) gridView.center = CGPoint(x: bounds.midX, y: bounds.midY) } } private var gridRatio: CGFloat? { if let input = captureVideoPreviewView?.captureVideoPreviewLayer.connection?.inputPorts.first?.input as? AVCaptureDeviceInput { let d = CMVideoFormatDescriptionGetDimensions(input.device.activeFormat.formatDescription) return CGFloat(d.width) / CGFloat(d.height) } else { return nil } } private var gridViewSize: CGSize { guard let gridRatio = gridRatio else { return bounds.size } let originalSize = bounds.size let aspectSize1 = CGSize(width: originalSize.width, height: originalSize.width * gridRatio) let aspectSize2 = CGSize(width: originalSize.height / gridRatio, height: originalSize.height) let minSize: CGSize let maxSize: CGSize let s1 = aspectSize1.width * aspectSize1.height let s2 = aspectSize2.width * aspectSize2.height if s1 < s2 { minSize = aspectSize1 maxSize = aspectSize2 } else { minSize = aspectSize2 maxSize = aspectSize1 } switch contentMode { case .scaleAspectFit: return minSize case .scaleAspectFill: return maxSize default: return originalSize } } // MARK: - Initializer public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupSubviewsFromXib() SimpleCamera.shared.add(simpleCameraObserver: self) } override init(frame: CGRect) { super.init(frame: frame) setupSubviewsFromXib() SimpleCamera.shared.add(simpleCameraObserver: self) } private func setupSubviewsFromXib() { let klass = type(of: self) guard let klassName = NSStringFromClass(klass).components(separatedBy: ".").last else { return } guard let subviewContainer = UINib(nibName: klassName, bundle: Bundle(for: klass)).instantiate(withOwner: self, options: nil).first as? UIView else { return } subviewContainer.autoresizingMask = [.flexibleWidth, .flexibleHeight] subviewContainer.frame = bounds addSubview(subviewContainer) updateZoomIndicatorButtonHidden() } fileprivate func updateZoomIndicatorButtonHidden() { zoomIndicatorButton.isHidden = !(SimpleCamera.shared.maxZoomFactor > 1.0) } // MARK: - IBActions @IBAction private func handleFocusAndExposeTapGestureRecognizer(_ gestureRecognizer: UITapGestureRecognizer) { // captureVideoPreviewView の contentMode もとい videoGravity に応じて正しい CGPoint が返ってきてるように見えるので大丈夫そう。 let viewPoint = gestureRecognizer.location(in: gestureRecognizer.view) let devicePoint = captureVideoPreviewView.captureVideoPreviewLayer.captureDevicePointConverted(fromLayerPoint: viewPoint) let x: Double = Double(devicePoint.x) - 0.5 let y: Double = Double(devicePoint.y) - 0.5 let distance: Double = sqrt( pow(x, 2.0) + pow(y, 2.0) ) if distance > 0.05 { SimpleCamera.shared.focusAndExposure(at: devicePoint, focusMode: .continuousAutoFocus, exposureMode: .continuousAutoExposure, monitorSubjectAreaChange: true) } else { SimpleCamera.shared.resetFocusAndExposure() } } private var beforeZoomFactor: CGFloat = 1.0 @IBAction private func handleZoomPinchGestureRecognizer(_ gestureRecognizer: UIPinchGestureRecognizer) { switch gestureRecognizer.state { case .began: zoomIndicatorButton.isEnabled = false beforeZoomFactor = SimpleCamera.shared.zoomFactor case .changed: let zoomFactor = beforeZoomFactor * gestureRecognizer.scale SimpleCamera.shared.zoomFactor = zoomFactor case .ended, .failed, .cancelled: zoomIndicatorButton.isEnabled = true SimpleCamera.shared.resetFocusAndExposure() case .possible: break @unknown default: break } } @IBAction private func touchUpInsideZoomIndicatorButton(_ sender: ZoomIndicatorButton) { if SimpleCamera.shared.zoomFactor == 1.0 { SimpleCamera.shared.zoomFactor = 2.0 } else { SimpleCamera.shared.zoomFactor = 1.0 } SimpleCamera.shared.resetFocusAndExposure() } // MARK: - Tap to Focus, Pinch to Zoom @IBInspectable public var isEnabledTapToFocusAndExposure: Bool { get { guard let captureVideoPreviewViewTapGestureRecognizer = captureVideoPreviewViewTapGestureRecognizer else { return false } return captureVideoPreviewViewTapGestureRecognizer.isEnabled } set { captureVideoPreviewViewTapGestureRecognizer?.isEnabled = newValue } } @IBInspectable public var isEnabledPinchToZoom: Bool { get { guard let captureVideoPreviewViewPinchGestureRecognizer = captureVideoPreviewViewPinchGestureRecognizer else { return false } return captureVideoPreviewViewPinchGestureRecognizer.isEnabled } set { captureVideoPreviewViewPinchGestureRecognizer?.isEnabled = newValue } } // MARK: - GridView Property Bridge public var gridType: GridType { get { gridView.gridType } set { gridView.gridType = newValue setNeedsLayout() } } @IBInspectable public var blackLineWidth: CGFloat { get { gridView.blackLineWidth } set { gridView.blackLineWidth = newValue setNeedsLayout() } } @IBInspectable public var whiteLineWidth: CGFloat { get { gridView.whiteLineWidth } set { gridView.whiteLineWidth = newValue setNeedsLayout() } } @IBInspectable public var blackLineAlpha: CGFloat { get { gridView.blackLineAlpha } set { gridView.blackLineAlpha = newValue setNeedsLayout() } } @IBInspectable public var whiteLineAlpha: CGFloat { get { gridView.whiteLineAlpha } set { gridView.whiteLineAlpha = newValue setNeedsLayout() } } // MARK: - Focus Exposure Indicator @IBInspectable public var isFollowFocusIndicatoreHiddenDeviceCapability: Bool = true { didSet { updateFocusIndicatorHidden() } } @IBInspectable public var isFollowExposureIndicatoreHiddenDeviceCapability: Bool = true { didSet { updateExposureIndicatorHidden() } } @IBInspectable public var isFocusIndicatorHidden: Bool { get { focusIndicatorView.isHidden } set { focusIndicatorView.isHidden = newValue } } @IBInspectable public var isExposureIndicatorHidden: Bool { get { exposureIndicatorView.isHidden } set { exposureIndicatorView.isHidden = newValue } } fileprivate func updateFocusIndicatorHidden() { if isFollowFocusIndicatoreHiddenDeviceCapability, let shown = SimpleCamera.shared.currentDevice?.isFocusPointOfInterestSupported { isFocusIndicatorHidden = !shown } } fileprivate func updateExposureIndicatorHidden() { if isFollowExposureIndicatoreHiddenDeviceCapability, let shown = SimpleCamera.shared.currentDevice?.isExposurePointOfInterestSupported { isExposureIndicatorHidden = !shown } } // MARK: - Shutter Animation public func shutterCloseAnimation(duration: TimeInterval, completion: ((Bool) -> Void)?) { shutterAnimationView.shutterCloseAnimation(duration: duration, completion: completion) } public func shutterOpenAnimation(duration: TimeInterval, completion: ((Bool) -> Void)?) { shutterAnimationView.shutterOpenAnimation(duration: duration, completion: completion) } public func shutterCloseAndOpenAnimation(duration: TimeInterval = 0.1, completion: ((Bool) -> Void)? = nil) { shutterCloseAnimation(duration: duration / 2.0) { (finished: Bool) -> Void in self.shutterOpenAnimation(duration: duration / 2.0, completion: completion) } } } extension CameraFinderView: SimpleCameraObservable { public func simpleCameraDidStopRunning(simpleCamera: SimpleCamera) {} public func simpleCameraDidChangeZoomFactor(simpleCamera: SimpleCamera) {} // public func simpleCameraSessionRuntimeError(simpleCamera: SimpleCamera, error: AVError) {} // @available(iOS 9.0, *) // public func simpleCameraSessionWasInterrupted(simpleCamera: SimpleCamera, reason: AVCaptureSession.InterruptionReason) {} public func simpleCameraSessionInterruptionEnded(simpleCamera: SimpleCamera) {} public func simpleCameraDidStartRunning(simpleCamera: SimpleCamera) { updateZoomIndicatorButtonHidden() } public func simpleCameraDidChangeFocusPointOfInterest(simpleCamera: SimpleCamera) { let point = captureVideoPreviewView.captureVideoPreviewLayer.layerPointConverted(fromCaptureDevicePoint: simpleCamera.focusPointOfInterest) if !point.x.isNaN && !point.y.isNaN { focusIndicatorView.focusAnimation(to: point) } } public func simpleCameraDidChangeExposurePointOfInterest(simpleCamera: SimpleCamera) { let point = captureVideoPreviewView.captureVideoPreviewLayer.layerPointConverted(fromCaptureDevicePoint: simpleCamera.exposurePointOfInterest) if !point.x.isNaN && !point.y.isNaN { exposureIndicatorView.exposureAnimation(to: point) } } public func simpleCameraDidResetFocusAndExposure(simpleCamera: SimpleCamera) { focusIndicatorView.focusResetAnimation() exposureIndicatorView.exposureResetAnimation() } public func simpleCameraDidSwitchCameraInput(simpleCamera: SimpleCamera) { updateFocusIndicatorHidden() updateExposureIndicatorHidden() updateZoomIndicatorButtonHidden() focusIndicatorView.focusResetAnimation(animated: false) exposureIndicatorView.exposureResetAnimation(animated: false) } } #endif
34.707042
169
0.669507
ed72533871a1cb488d39a9e3db4dd66462e8b8de
2,005
/// Copyright (c) 2019 Razeware LLC /// /// Permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to deal /// in the Software without restriction, including without limitation the rights /// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell /// copies of the Software, and to permit persons to whom the Software is /// furnished to do so, subject to the following conditions: /// /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, /// distribute, sublicense, create a derivative work, and/or sell copies of the /// Software in any work that is designed, intended, or marketed for pedagogical or /// instructional purposes related to programming, coding, application development, /// or information technology. Permission for such use, copying, modification, /// merger, publication, distribution, sublicensing, creation of derivative works, /// or sale is expressly withheld. /// /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN /// THE SOFTWARE. import UIKit class StarshipTableView: UITableView { override func draw(_ rect: CGRect) { guard let context = UIGraphicsGetCurrentContext() else { return } context.drawLinearGradient(in: rect, startingWith: UIColor.starwarsSpaceBlue.cgColor, finishingWith: UIColor.black.cgColor) } }
47.738095
131
0.742643
39eecb9b56977ee1ea0129ee0cbba1ee1e7367cb
354
// // FloatingPoint+Extension.swift // CircularProgressView // // Created by Bartosz Dolewski on 23/04/2019. // Copyright © 2019 Bartosz Dolewski. All rights reserved. // import Foundation internal extension FloatingPoint { func clamped(to range: ClosedRange<Self>) -> Self { max(min(self, range.upperBound), range.lowerBound) } }
20.823529
59
0.70339
e4bfd18ae962cd63561acdee7fc40be9fcd46a29
10,330
// // StickersViewController.swift // Photo Editor // // Created by Mohamed Hamed on 4/23/17. // Copyright © 2017 Mohamed Hamed. All rights reserved. // Credit https://github.com/AhmedElassuty/IOS-BottomSheet import UIKit class StickersViewController: UIViewController, UIGestureRecognizerDelegate { @IBOutlet weak var headerView: UIView! @IBOutlet weak var holdView: UIView! @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var pageControl: UIPageControl! var collectioView: UICollectionView! var emojisCollectioView: UICollectionView! var emojisDelegate: EmojisCollectionViewDelegate! var stickers : [UIImage] = [] var stickersViewControllerDelegate : StickersViewControllerDelegate? let screenSize = UIScreen.main.bounds.size let fullView: CGFloat = 100 // remainder of screen height var partialView: CGFloat { return UIScreen.main.bounds.height - 380 } override func viewDidLoad() { super.viewDidLoad() configureCollectionViews() scrollView.contentSize = CGSize(width: 2.0 * screenSize.width, height: scrollView.frame.size.height) scrollView.isPagingEnabled = true scrollView.delegate = self pageControl.numberOfPages = 2 holdView.layer.cornerRadius = 3 let gesture = UIPanGestureRecognizer.init(target: self, action: #selector(StickersViewController.panGesture)) gesture.delegate = self view.addGestureRecognizer(gesture) } func configureCollectionViews() { let frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: view.frame.height - 40) let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout() layout.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10) let width = (CGFloat) ((screenSize.width - 30) / 3.0) layout.itemSize = CGSize(width: width, height: 100) collectioView = UICollectionView(frame: frame, collectionViewLayout: layout) collectioView.backgroundColor = .clear scrollView.addSubview(collectioView) collectioView.delegate = self collectioView.dataSource = self collectioView.register( UINib(nibName: "StickerCollectionViewCell", bundle: Bundle(for: StickerCollectionViewCell.self)), forCellWithReuseIdentifier: "StickerCollectionViewCell") //----------------------------------- let emojisFrame = CGRect(x: scrollView.frame.size.width, y: 0, width: UIScreen.main.bounds.width, height: view.frame.height - 40) let emojislayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout() emojislayout.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10) emojislayout.itemSize = CGSize(width: 70, height: 70) emojisCollectioView = UICollectionView(frame: emojisFrame, collectionViewLayout: emojislayout) emojisCollectioView.backgroundColor = .clear scrollView.addSubview(emojisCollectioView) emojisDelegate = EmojisCollectionViewDelegate() emojisDelegate.stickersViewControllerDelegate = stickersViewControllerDelegate emojisCollectioView.delegate = emojisDelegate emojisCollectioView.dataSource = emojisDelegate emojisCollectioView.register( UINib(nibName: "EmojiCollectionViewCell", bundle: Bundle(for: EmojiCollectionViewCell.self)), forCellWithReuseIdentifier: "EmojiCollectionViewCell") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) prepareBackgroundView() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) UIView.animate(withDuration: 0.6) { [weak self] in guard let `self` = self else { return } let frame = self.view.frame let yComponent = self.partialView self.view.frame = CGRect(x: 0, y: yComponent, width: frame.width, height: UIScreen.main.bounds.height - self.partialView) } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() collectioView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: view.frame.height - 40) emojisCollectioView.frame = CGRect(x: scrollView.frame.size.width, y: 0, width: UIScreen.main.bounds.width, height: view.frame.height - 40) scrollView.contentSize = CGSize(width: 2.0 * screenSize.width, height: scrollView.frame.size.height) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } //MARK: Pan Gesture @objc func panGesture(_ recognizer: UIPanGestureRecognizer) { let translation = recognizer.translation(in: self.view) let velocity = recognizer.velocity(in: self.view) let y = self.view.frame.minY if y + translation.y >= fullView { let newMinY = y + translation.y self.view.frame = CGRect(x: 0, y: newMinY, width: view.frame.width, height: UIScreen.main.bounds.height - newMinY ) self.view.layoutIfNeeded() recognizer.setTranslation(CGPoint.zero, in: self.view) } if recognizer.state == .ended { var duration = velocity.y < 0 ? Double((y - fullView) / -velocity.y) : Double((partialView - y) / velocity.y ) duration = duration > 1.3 ? 1 : duration //velocity is direction of gesture UIView.animate(withDuration: duration, delay: 0.0, options: [.allowUserInteraction], animations: { if velocity.y >= 0 { if y + translation.y >= self.partialView { self.removeBottomSheetView() } else { self.view.frame = CGRect(x: 0, y: self.partialView, width: self.view.frame.width, height: UIScreen.main.bounds.height - self.partialView) self.view.layoutIfNeeded() } } else { if y + translation.y >= self.partialView { self.view.frame = CGRect(x: 0, y: self.partialView, width: self.view.frame.width, height: UIScreen.main.bounds.height - self.partialView) self.view.layoutIfNeeded() } else { self.view.frame = CGRect(x: 0, y: self.fullView, width: self.view.frame.width, height: UIScreen.main.bounds.height - self.fullView) self.view.layoutIfNeeded() } } }, completion: nil) } } func removeBottomSheetView() { UIView.animate(withDuration: 0.3, delay: 0, options: UIView.AnimationOptions.curveEaseIn, animations: { () -> Void in var frame = self.view.frame frame.origin.y = UIScreen.main.bounds.maxY self.view.frame = frame }, completion: { (finished) -> Void in self.view.removeFromSuperview() self.removeFromParentViewController() self.stickersViewControllerDelegate?.stickersViewDidDisappear() }) } func prepareBackgroundView(){ let blurEffect = UIBlurEffect.init(style: .light) let visualEffect = UIVisualEffectView.init(effect: blurEffect) let bluredView = UIVisualEffectView.init(effect: blurEffect) bluredView.contentView.addSubview(visualEffect) visualEffect.frame = UIScreen.main.bounds bluredView.frame = UIScreen.main.bounds view.insertSubview(bluredView, at: 0) } } extension StickersViewController: UIScrollViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { let pageWidth = scrollView.bounds.width let pageFraction = scrollView.contentOffset.x / pageWidth self.pageControl.currentPage = Int(round(pageFraction)) } } // MARK: - UICollectionViewDataSource extension StickersViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return stickers.count } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { stickersViewControllerDelegate?.didSelectImage(image: stickers[indexPath.item]) } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let identifier = "StickerCollectionViewCell" let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as! StickerCollectionViewCell cell.stickerImage.image = stickers[indexPath.item] return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 4 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 0 } }
41.653226
175
0.605808
89644cb6f177f90586aeb68ee222a2c5c92813ee
269
// // EchoResponse.swift // GGARest_Tests // // Created by Adrian Sanchis Serrano on 17/7/18. // Copyright © 2018 CocoaPods. All rights reserved. // import UIKit import GGARest class EchoResponse_MyClass: HttpBinResponse { @objc dynamic var json : MyClass? }
17.933333
52
0.72119
229a1515c72e01cfdab4da6e519e31228cc6ea4c
251
// // String+.swift // SwiftUICoreData_MVVM // // Created by Daymein Gregorio on 1/31/22. // import Foundation extension String { static func agentID() -> String { return UUID().uuidString.components(separatedBy: "-").first ?? "" } }
14.764706
69
0.645418
ef3062892e35f8a6d88c9ecec50bd187c14daa64
12,069
// // DurationTests.swift // DurationTests // // Created by Maciej Gad on 05/03/2019. // Copyright © 2019 MaciejGad. All rights reserved. // import XCTest @testable import Duration class DurationTests: XCTestCase { let date_6_03_2019 = Date(timeIntervalSince1970: 1551867068) let date_25_03_2018 = Date(timeIntervalSince1970: 1521932460) override func setUp() { Duration.calendar = Calendar(identifier: .gregorian) Duration.timeZone = TimeZone(identifier: "Europe/Warsaw")! } func test1day() throws { //given let givenDurationText = "P1D" //when let sut = try Duration(string: givenDurationText) //then XCTAssertEqual(sut.timeInterval, TimeInterval.day) XCTAssertEqual(sut.timeIntervalFrom(date: date_25_03_2018), TimeInterval.day - TimeInterval.hour) //change time to daylight saving XCTAssertEqual(sut.timeIntervalTo(date: date_25_03_2018), TimeInterval.day) XCTAssertEqual(sut.startDate(ending: date_25_03_2018).timeIntervalSince1970, 1521846060.0) XCTAssertEqual(sut.endDate(starting: date_25_03_2018).timeIntervalSince1970, 1522015260.0) } func test1year() throws { //given let givenDurationText = "P1Y" //when let sut = try Duration(string: givenDurationText) //then XCTAssertEqual(sut.timeInterval, TimeInterval.year) XCTAssertEqual(sut.timeIntervalFrom(date: date_6_03_2019), TimeInterval.day * 366) //leap-year XCTAssertEqual(sut.timeIntervalTo(date: date_6_03_2019), TimeInterval.day * 365) XCTAssertEqual(sut.startDate(ending: date_6_03_2019).timeIntervalSince1970, 1520331068.0) XCTAssertEqual(sut.endDate(starting: date_6_03_2019).timeIntervalSince1970, 1583489468.0) } func test1year1day() throws { //given let givenDurationText = "P1Y1D" //when let sut = try Duration(string: givenDurationText) //then XCTAssertEqual(sut.timeInterval, TimeInterval.year + TimeInterval.day ) XCTAssertEqual(sut.timeIntervalFrom(date: date_6_03_2019), TimeInterval.day * 366 + TimeInterval.day) //leap-year XCTAssertEqual(sut.timeIntervalTo(date: date_6_03_2019), TimeInterval.day * 365 + TimeInterval.day) XCTAssertEqual(sut.startDate(ending: date_6_03_2019).timeIntervalSince1970, 1520244668.0) XCTAssertEqual(sut.endDate(starting: date_6_03_2019).timeIntervalSince1970, 1583575868.0) } func test2_5years() throws { //given let givenDurationText = "P2.5Y" //when let sut = try Duration(string: givenDurationText) //then XCTAssertEqual(sut.timeInterval, TimeInterval.year * 2.5) XCTAssertEqual(sut.timeIntervalTo(date: date_6_03_2019), 78714000) //1551867068 - 1473153068 XCTAssertEqual(sut.timeIntervalFrom(date: date_6_03_2019), 79052400) //1630919468 - 1551867068 XCTAssertEqual(sut.startDate(ending: date_6_03_2019).timeIntervalSince1970, 1473153068.0) XCTAssertEqual(sut.endDate(starting: date_6_03_2019).timeIntervalSince1970, 1630919468.0) } func test2_coma_5years() throws { //given let givenDurationText = "P2,5Y" //when let sut = try Duration(string: givenDurationText) //then XCTAssertEqual(sut.timeInterval, TimeInterval.year * 2.5) XCTAssertEqual(sut.timeIntervalTo(date: date_6_03_2019), 78714000) //1551867068 - 1473153068 XCTAssertEqual(sut.timeIntervalFrom(date: date_6_03_2019), 79052400) //1630919468 - 1551867068 XCTAssertEqual(sut.startDate(ending: date_6_03_2019).timeIntervalSince1970, 1473153068.0) XCTAssertEqual(sut.endDate(starting: date_6_03_2019).timeIntervalSince1970, 1630919468.0) } func test1month() throws { //given let givenDurationText = "P1M" //when let sut = try Duration(string: givenDurationText) //then XCTAssertEqual(sut.timeInterval, TimeInterval.month) XCTAssertEqual(sut.timeIntervalTo(date: date_6_03_2019), TimeInterval.day * 28) XCTAssertEqual(sut.timeIntervalFrom(date: date_6_03_2019), TimeInterval.day * 31 - TimeInterval.hour) //change time to daylight saving XCTAssertEqual(sut.startDate(ending: date_6_03_2019).timeIntervalSince1970, 1549447868.0) XCTAssertEqual(sut.endDate(starting: date_6_03_2019).timeIntervalSince1970, 1554541868.0) } func test1_5monthAnd4days() throws { //given let givenDurationText = "P1.5M4D" //when let sut = try Duration(string: givenDurationText) //then XCTAssertEqual(sut.timeInterval, TimeInterval.day * (30 * 1.5 + 4)) XCTAssertEqual(sut.timeIntervalTo(date: date_6_03_2019), TimeInterval.day * (28 + 15 + 4) ) XCTAssertEqual(sut.timeIntervalFrom(date: date_6_03_2019), TimeInterval.day * (31 + 15 + 4) - TimeInterval.hour) //change time to daylight saving XCTAssertEqual(sut.startDate(ending: date_6_03_2019).timeIntervalSince1970, 1547806268.0) XCTAssertEqual(sut.endDate(starting: date_6_03_2019).timeIntervalSince1970, 1556183468.0) } func test0_5month() throws { //given let givenDurationText = "P0.5M" //when let sut = try Duration(string: givenDurationText) //then XCTAssertEqual(sut.timeInterval, TimeInterval.day * 15) XCTAssertEqual(sut.timeIntervalTo(date: date_25_03_2018), TimeInterval.day * 15 ) XCTAssertEqual(sut.timeIntervalFrom(date: date_25_03_2018), TimeInterval.day * 15 - TimeInterval.hour) //change time to daylight saving XCTAssertEqual(sut.startDate(ending: date_25_03_2018).timeIntervalSince1970, 1520636460.0) XCTAssertEqual(sut.endDate(starting: date_25_03_2018).timeIntervalSince1970, 1523224860.0) } func test1week() throws { //given let givenDurationText = "P1W" //when let sut = try Duration(string: givenDurationText) //then XCTAssertEqual(sut.timeInterval, TimeInterval.week) XCTAssertEqual(sut.timeIntervalTo(date: date_25_03_2018), TimeInterval.day * 7) XCTAssertEqual(sut.timeIntervalFrom(date: date_25_03_2018), TimeInterval.day * 7 - TimeInterval.hour) //change time to daylight saving } func test1hour() throws { //given let givenDurationText = "PT1H" //when let sut = try Duration(string: givenDurationText) //then XCTAssertEqual(sut.timeInterval, TimeInterval.hour) XCTAssertEqual(sut.timeIntervalTo(date: date_25_03_2018), TimeInterval.hour) XCTAssertEqual(sut.timeIntervalFrom(date: date_25_03_2018), TimeInterval.hour) } func test1minute() throws { //given let givenDurationText = "PT1M" //when let sut = try Duration(string: givenDurationText) //then XCTAssertEqual(sut.timeInterval, TimeInterval.minute) XCTAssertEqual(sut.timeIntervalTo(date: date_6_03_2019), TimeInterval.minute) XCTAssertEqual(sut.timeIntervalFrom(date: date_6_03_2019), TimeInterval.minute) XCTAssertEqual(sut.startDate(ending: date_6_03_2019).timeIntervalSince1970, 1551867008.0) XCTAssertEqual(sut.endDate(starting: date_6_03_2019).timeIntervalSince1970, 1551867128.0) } func test1second() throws { //given let givenDurationText = "PT1S" //when let sut = try Duration(string: givenDurationText) //then XCTAssertEqual(sut.timeInterval, 1) XCTAssertEqual(sut.timeIntervalTo(date: date_6_03_2019), 1) XCTAssertEqual(sut.timeIntervalFrom(date: date_6_03_2019), 1) XCTAssertEqual(sut.startDate(ending: date_6_03_2019).timeIntervalSince1970, 1551867067.0) XCTAssertEqual(sut.endDate(starting: date_6_03_2019).timeIntervalSince1970, 1551867069.0) } func testP3Y6M4DT12H30M5S() throws { //given let givenDurationText = "P3Y6M4DT12H30M5S" //when let sut = try Duration(string: givenDurationText) //then let timeInterval = TimeInterval.year * 3 + TimeInterval.month * 6 + TimeInterval.day * 4 + TimeInterval.hour * 12 + TimeInterval.minute * 30 + 5 print(sut.timeInterval) XCTAssertEqual(sut.timeInterval, timeInterval) XCTAssertEqual(sut.timeIntervalTo(date: date_6_03_2019), 110727005) //1551867068 - 1441140063 XCTAssertEqual(sut.timeIntervalFrom(date: date_6_03_2019), 110979005) //1662846073 - 1551867068 XCTAssertEqual(sut.startDate(ending: date_6_03_2019).timeIntervalSince1970, 1441140063.0) XCTAssertEqual(sut.endDate(starting: date_6_03_2019).timeIntervalSince1970, 1662846073.0) // let startDate = sut.startDate(ending: date_6_03_2019) // let endDate = sut.endDate(starting: date_6_03_2019) // print("current: \(date_6_03_2019)") // print("start: \(startDate) - \(startDate.timeIntervalSince1970)") // print("end: \(endDate) - \(endDate.timeIntervalSince1970)") } func testNo_P_atBeginThrows() { XCTAssertThrowsError(try Duration(string: "1DT3H")) } func testNo_T_atBeginOfTimeThrows() { XCTAssertThrowsError(try Duration(string: "P3H")) XCTAssertThrowsError(try Duration(string: "P3S")) } func testUnknownElement() { XCTAssertThrowsError(try Duration(string: "P3H T1H")) } func testDiscontinuous() { XCTAssertThrowsError(try Duration(string: "P3H T1")) } func testDecode() throws { //given let json = """ { "duration": "P1Y1D" } """.utf8 let data = Data(json) let decoder = JSONDecoder() //when let sut = try decoder.decode(Box.self, from: data) //then XCTAssertEqual(sut.duration.timeInterval, TimeInterval.year + TimeInterval.day ) XCTAssertEqual(sut.duration.timeIntervalFrom(date: date_6_03_2019), TimeInterval.day * 366 + TimeInterval.day) //leap-year XCTAssertEqual(sut.duration.timeIntervalTo(date: date_6_03_2019), TimeInterval.day * 365 + TimeInterval.day) XCTAssertEqual(sut.duration.startDate(ending: date_6_03_2019).timeIntervalSince1970, 1520244668.0) XCTAssertEqual(sut.duration.endDate(starting: date_6_03_2019).timeIntervalSince1970, 1583575868.0) } func testEncode() throws { //given let givenDuration = try Duration(string: "P1Y1D") let decoder = JSONDecoder() let encoder = JSONEncoder() encoder.outputFormatting = [.prettyPrinted] let data: Data let newDuration: Duration //when do { /// due to bug: https://bugs.swift.org/browse/SR-6163 /// you can't encode single Duration like that: // data = try encoder.encode(givenDuration) /// you will need to box the value in some container /// check Box struct data = try encoder.encode(Box(duration: givenDuration)) newDuration = try decoder.decode(Box.self, from: data).duration } catch { print(error) throw error } //then let textOutput = String(bytes: data, encoding: .utf8) print(textOutput!) print(newDuration) XCTAssertEqual(givenDuration.timeInterval, newDuration.timeInterval) } } struct Box: Codable { let duration:Duration }
38.314286
153
0.65109
fee283329ceaa3c33682b44377f4dac25913f31b
2,262
// // Copyright (c) 2018 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit import FirebaseFirestore /// A class that populates a table view using RestaurantTableViewCell cells /// with restaurant data from a Firestore query. Consumers should update the /// table view with new data from Firestore in the updateHandler closure. @objc class RestaurantTableViewDataSource: NSObject, UITableViewDataSource { private var restaurants: [Restaurant] = [] public init(query: Query, updateHandler: @escaping ([DocumentChange]) -> ()) { fatalError("Unimplemented") } // Pull data from Firestore /// Starts listening to the Firestore query and invoking the updateHandler. public func startUpdates() { fatalError("Unimplemented") } /// Stops listening to the Firestore query. updateHandler will not be called unless startListening /// is called again. public func stopUpdates() { fatalError("Unimplemented") } /// Returns the restaurant at the given index. subscript(index: Int) -> Restaurant { return restaurants[index] } /// The number of items in the data source. public var count: Int { return restaurants.count } // MARK: - UITableViewDataSource func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "RestaurantTableViewCell", for: indexPath) as! RestaurantTableViewCell let restaurant = restaurants[indexPath.row] cell.populate(restaurant: restaurant) return cell } }
31.416667
100
0.715738
1ad33ca22e18d61d590a5a7341536d058a8bdfdb
1,995
/* * Copyright (c) 2016, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ import Foundation //-------------------------------------- // MARK: - WhenAny //-------------------------------------- extension Task { /** Creates a task that will complete when any of the input tasks have completed. The returned task will complete when any of the supplied tasks have completed. This is true even if the first task to complete ended in the canceled or faulted state. - parameter tasks: Array of tasks to wait on for completion. - returns: A new task that will complete when any of the `tasks` are completed. */ public class func whenAny(_ tasks: [Task]) -> Task<Void> { if tasks.isEmpty { return Task.emptyTask() } let taskCompletionSource = TaskCompletionSource<Void>() for task in tasks { // Do not continue anything if we completed the task, because we fulfilled our job here. if taskCompletionSource.task.completed { break } task.continueWith { _ in taskCompletionSource.trySet(result: ()) } } return taskCompletionSource.task } /** Creates a task that will complete when any of the input tasks have completed. The returned task will complete when any of the supplied tasks have completed. This is true even if the first task to complete ended in the canceled or faulted state. - parameter tasks: Zeror or more tasks to wait on for completion. - returns: A new task that will complete when any of the `tasks` are completed. */ public class func whenAny(_ tasks: Task...) -> Task<Void> { return whenAny(tasks) } }
33.813559
100
0.629073
e6d6c78e7ad654e8e478962124c65ccffcecf34f
1,250
// ---------------------------------------------------------------------------- // // Check.Same.swift // // @author Alexander Bragin <[email protected]> // @copyright Copyright (c) 2017, Roxie Mobile Ltd. All rights reserved. // @link https://www.roxiemobile.com/ // // ---------------------------------------------------------------------------- extension Check { // MARK: - Methods /// Checks that two objects refer to the same object. /// /// - Parameters: /// - expected: Expected object. /// - actual: Actual object. /// - message: The identifying message for the `CheckError` (`nil` okay). The default is an empty string. /// - file: The file name. The default is the file where function is called. /// - line: The line number. The default is the line number where function is called. /// /// - Throws: /// CheckError /// public static func same<T: AnyObject>( _ expected: T?, _ actual: T?, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line ) throws { guard (expected === actual) else { throw newCheckError(message(), file, line) } } }
31.25
111
0.5032
115433e21ea562f0afd7ec804e39b25967f0098a
238
// // ServiceTypeCollectionCell.swift // Issues // // Created by Jonathan Bennett on 2015-12-25. // Copyright © 2015 Jonathan Bennett. All rights reserved. // import UIKit public class ServiceTypeTableViewCell: UITableViewCell { }
17
59
0.739496
2fe599fa7cb7233a44cabbb62ab4f8172ac0a4dc
1,406
// // AppDelegate.swift // CustomSwitch // // Created by Alex on 5/10/21. // Copyright © 2021 AlexCo. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } }
37
179
0.746799
5bf08f3346098874bc9f94ce14d503d21d4eb328
2,923
// // MovieHomeGrid.swift // MovieSwift // // Created by Thomas Ricouard on 10/10/2019. // Copyright © 2019 Thomas Ricouard. All rights reserved. // import SwiftUI import SwiftUIFlux struct MoviesHomeGrid: ConnectedView { struct Props { let movies: [MoviesMenu: [Int]] let genres: [Genre] } private func moviesRow(menu: MoviesMenu, props: Props) -> some View{ VStack(alignment: .leading) { HStack { Text(menu.title()) .titleFont(size: 23) .foregroundColor(.steam_gold) .padding(.horizontal, 16) .padding(.top, 16) NavigationLink( destination: MoviesList(movies: props.movies[menu] ?? [], displaySearch: true, pageListener: MoviesMenuListPageListener(menu: menu, loadOnInit: false), menu: menu) .navigationBarTitle(menu.title()), label: { Spacer() Text("See all") .foregroundColor(.steam_blue) }) .padding(.trailing, 16) .padding(.top, 16) } MoviesHomeGridMoviesRow(movies: props.movies[menu] ?? []) .padding(.bottom, 8) }.onAppear { store.dispatch(action: MoviesActions.FetchMoviesMenuList(list: menu, page: 1)) }.listRowInsets(EdgeInsets()) } func map(state: AppState, dispatch: @escaping DispatchFunction) -> Props { var genres = state.moviesState.genres if !genres.isEmpty { genres.removeFirst() } return Props(movies: state.moviesState.moviesList, genres: genres) } func body(props: Props) -> some View { List { ForEach(MoviesMenu.allCases, id: \.self) { menu in Group { if menu == .genres { ForEach(props.genres) { genre in NavigationLink(destination: MoviesGenreList(genre: genre)) { Text(genre.name) } } } else { self.moviesRow(menu: menu, props: props) } } } } .listStyle(PlainListStyle()) .navigationBarTitle("Movies", displayMode: .automatic) .onAppear { store.dispatch(action: MoviesActions.FetchGenres()) } } } struct MoviesHomeGrid_Previews: PreviewProvider { static var previews: some View { MoviesHomeGrid() } }
33.597701
116
0.464933
ef2266efc38e6c8af04631e027987665601f6fae
1,465
// // SVGLineTests.swift // SwiftSVG // // // Copyright (c) 2017 Michael Choe // http://www.github.com/mchoe // http://www.straussmade.com/ // http://www.twitter.com/_mchoe // // 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 XCTest class SVGLineTests: XCTestCase { func testElementName() { XCTAssert(SVGLine.elementName == "line", "Expected \"line\", got \(SVGLine.elementName)") } }
36.625
97
0.725597