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
|
---|---|---|---|---|---|
ed67161ba9c759fe75620ccfd75f927796a9f514 | 971 | /***************************************************************************
* Copyright 2014-2016 SPECURE GmbH
* Copyright 2016-2017 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
///
protocol ConnectivityServiceDelegate {
///
func connectivityDidChange(_ connectivityService: ConnectivityService, connectivityInfo: ConnectivityInfo)
}
| 37.346154 | 110 | 0.639547 |
fe0ab7e7470945d4bb523d67002d8c9b3db8507a | 1,178 | /*
* The MIT License (MIT)
*
* Copyright (c) 2020 Shopify Inc.
*
* 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.
*/
let syrup = Syrup()
syrup.run()
| 43.62963 | 80 | 0.752971 |
280eb68b54da54803495dfcc7d33bff38418f24c | 18,111 | import XCTest
// Altough we only run this test above the below specified versions, we exped the
// implementation to be thread safe
@available(tvOS 10.0, *)
@available(OSX 10.12, *)
@available(iOS 10.0, *)
class SentryHttpTransportTests: XCTestCase {
private static let dsnAsString = TestConstants.dsnAsString(username: "SentryHttpTransportTests")
private static let dsn = TestConstants.dsn(username: "SentryHttpTransportTests")
private class Fixture {
let event: Event
let eventRequest: SentryNSURLRequest
let eventWithAttachmentRequest: SentryNSURLRequest
let eventWithSessionEnvelope: SentryEnvelope
let eventWithSessionRequest: SentryNSURLRequest
let session: SentrySession
let sessionEnvelope: SentryEnvelope
let sessionRequest: SentryNSURLRequest
let currentDateProvider: TestCurrentDateProvider
let fileManager: SentryFileManager
let options: Options
let requestManager: TestRequestManager
let rateLimits: DefaultRateLimits
let userFeedback: UserFeedback
let userFeedbackRequest: SentryNSURLRequest
init() {
currentDateProvider = TestCurrentDateProvider()
CurrentDate.setCurrentDateProvider(currentDateProvider)
event = Event()
event.message = SentryMessage(formatted: "Some message")
eventRequest = buildRequest(SentryEnvelope(event: event))
let eventEnvelope = SentryEnvelope(id: event.eventId, items: [SentryEnvelopeItem(event: event), SentryEnvelopeItem(attachment: TestData.dataAttachment, maxAttachmentSize: 5 * 1_024 * 1_024)!])
eventWithAttachmentRequest = buildRequest(eventEnvelope)
session = SentrySession(releaseName: "2.0.1")
sessionEnvelope = SentryEnvelope(id: nil, singleItem: SentryEnvelopeItem(session: session))
sessionRequest = buildRequest(sessionEnvelope)
let items = [SentryEnvelopeItem(event: event), SentryEnvelopeItem(session: session)]
eventWithSessionEnvelope = SentryEnvelope(id: event.eventId, items: items)
eventWithSessionRequest = buildRequest(eventWithSessionEnvelope)
fileManager = try! SentryFileManager(dsn: SentryHttpTransportTests.dsn, andCurrentDateProvider: currentDateProvider)
options = Options()
options.dsn = SentryHttpTransportTests.dsnAsString
requestManager = TestRequestManager(session: URLSession(configuration: URLSessionConfiguration.ephemeral))
rateLimits = DefaultRateLimits(retryAfterHeaderParser: RetryAfterHeaderParser(httpDateParser: HttpDateParser()), andRateLimitParser: RateLimitParser())
userFeedback = UserFeedback(eventId: SentryId())
userFeedback.comments = "It doesn't really"
userFeedback.email = "[email protected]"
userFeedback.name = "John Me"
userFeedbackRequest = buildRequest(SentryEnvelope(userFeedback: userFeedback))
}
var sut: SentryHttpTransport {
get {
return SentryHttpTransport(
options: options,
fileManager: fileManager,
requestManager: requestManager,
rateLimits: rateLimits,
envelopeRateLimit: EnvelopeRateLimit(rateLimits: rateLimits),
dispatchQueueWrapper: TestSentryDispatchQueueWrapper()
)
}
}
}
class func buildRequest(_ envelope: SentryEnvelope) -> SentryNSURLRequest {
let envelopeData = try! SentrySerialization.data(with: envelope)
return try! SentryNSURLRequest(envelopeRequestWith: SentryHttpTransportTests.dsn, andData: envelopeData)
}
private var fixture: Fixture!
private var sut: SentryHttpTransport!
override func setUp() {
fixture = Fixture()
fixture.fileManager.deleteAllEnvelopes()
fixture.requestManager.returnResponse(response: HTTPURLResponse())
sut = fixture.sut
}
override func tearDown() {
fixture.fileManager.deleteAllEnvelopes()
}
func testInitSendsCachedEnvelopes() {
givenNoInternetConnection()
sendEventAsync()
assertEnvelopesStored(envelopeCount: 1)
waitForAllRequests()
givenOkResponse()
_ = fixture.sut
waitForAllRequests()
assertEnvelopesStored(envelopeCount: 0)
assertRequestsSent(requestCount: 2)
}
func testSendOneEvent() throws {
sendEvent()
assertRequestsSent(requestCount: 1)
assertEventIsSentAsEnvelope()
assertEnvelopesStored(envelopeCount: 0)
}
func testSendEventWhenSessionRateLimitActive() {
fixture.rateLimits.update(TestResponseFactory.createRateLimitResponse(headerValue: "1:\(SentryEnvelopeItemTypeSession):key"))
sendEvent()
assertEventIsSentAsEnvelope()
assertEnvelopesStored(envelopeCount: 0)
}
func testSendEventWithSession_SentInOneEnvelope() {
sut.send(fixture.event, with: fixture.session, attachments: [])
waitForAllRequests()
assertRequestsSent(requestCount: 1)
assertEnvelopesStored(envelopeCount: 0)
assertEventAndSesionAreSentInOneEnvelope()
}
func testSendEventWithSession_RateLimitForEventIsActive_OnlySessionSent() {
givenRateLimitResponse(forCategory: "error")
sendEvent()
sut.send(fixture.event, with: fixture.session, attachments: [])
waitForAllRequests()
assertRequestsSent(requestCount: 2)
assertEnvelopesStored(envelopeCount: 0)
// Envelope with only Session is sent
let envelope = SentryEnvelope(id: fixture.event.eventId, items: [SentryEnvelopeItem(session: fixture.session)])
let request = SentryHttpTransportTests.buildRequest(envelope)
XCTAssertEqual(request.httpBody, fixture.requestManager.requests.last?.httpBody)
}
func testSendAllCachedEvents() {
givenNoInternetConnection()
sendEvent()
givenRateLimitResponse(forCategory: "someCat")
sendEnvelope()
XCTAssertEqual(3, fixture.requestManager.requests.count)
assertEnvelopesStored(envelopeCount: 0)
}
func testSendAllCachedEnvelopes() {
givenNoInternetConnection()
let envelope = SentryEnvelope(session: SentrySession(releaseName: "1.9.0"))
sendEnvelope(envelope: envelope)
sendEnvelope()
givenOkResponse()
sendEvent()
XCTAssertEqual(5, fixture.requestManager.requests.count)
assertEnvelopesStored(envelopeCount: 0)
}
func testSendCachedButNotReady() {
givenNoInternetConnection()
sendEnvelope()
fixture.requestManager.isReady = false
givenOkResponse()
sendEvent()
XCTAssertEqual(1, fixture.requestManager.requests.count)
assertEnvelopesStored(envelopeCount: 2)
}
func testSendCachedEventsButRateLimitIsActive() {
givenNoInternetConnection()
sendEvent()
// Rate limit changes between sending the event succesfully
// and calling sending all events. This can happen when for
// example when multiple requests run in parallel.
givenRateLimitResponse(forCategory: "error")
sendEvent()
XCTAssertEqual(3, fixture.requestManager.requests.count)
assertEnvelopesStored(envelopeCount: 0)
}
func testRateLimitGetsActiveWhileSendAllEvents() {
givenNoInternetConnection()
sendEvent()
sendEvent()
sendEvent()
// 7 envelopes are saved in the FileManager
// The next envelope is stored as well and now all 4 should be sent.
// The first stored envelope from the FileManager is sent normally and for the
// second envelope the response contains a rate limit.
// Now 2 envelopes are still to be sent, but they get discarded cause of the
// active rate limit.
givenFirstRateLimitGetsActiveWithSecondResponse()
sendEvent()
XCTAssertEqual(7, fixture.requestManager.requests.count)
assertEnvelopesStored(envelopeCount: 0)
}
func testSendAllEventsAllEventsDeletedWhenNotReady() {
givenNoInternetConnection()
sendEvent()
sendEvent()
assertEnvelopesStored(envelopeCount: 2)
givenRateLimitResponse(forCategory: "error")
sendEvent()
assertEnvelopesStored(envelopeCount: 0)
}
func testSendEventWithRetryAfterResponse() {
let response = givenRetryAfterResponse()
sendEvent()
assertRateLimitUpdated(response: response)
}
func testSendEventWithRateLimitResponse() {
let response = givenRateLimitResponse(forCategory: SentryEnvelopeItemTypeSession)
sendEvent()
assertRateLimitUpdated(response: response)
}
func testSendEnvelopeWithRetryAfterResponse() {
let response = givenRetryAfterResponse()
sendEnvelope()
assertRateLimitUpdated(response: response)
}
func testSendEnvelopeWithRateLimitResponse() {
let response = givenRateLimitResponse(forCategory: SentryEnvelopeItemTypeSession)
sendEnvelope()
assertRateLimitUpdated(response: response)
}
func testRateLimitForEvent() {
givenRateLimitResponse(forCategory: "error")
sendEvent()
assertRequestsSent(requestCount: 1)
// Retry-After almost expired
let date = fixture.currentDateProvider.date()
fixture.currentDateProvider.setDate(date: date.addingTimeInterval(0.999))
sendEvent()
assertRequestsSent(requestCount: 2)
// Retry-After expired
fixture.currentDateProvider.setDate(date: date.addingTimeInterval(1))
sendEvent()
assertRequestsSent(requestCount: 3)
}
func testSendEventWithFaultyNSUrlRequest() {
sut.send(event: TestConstants.eventWithSerializationError, attachments: [])
assertRequestsSent(requestCount: 1)
}
func testSendOneEnvelope() {
sendEnvelope()
assertRequestsSent(requestCount: 1)
}
func testActiveRateLimitForAllEnvelopeItems() {
givenRateLimitResponse(forCategory: "error")
sendEvent()
sendEnvelope()
assertRequestsSent(requestCount: 1)
assertEnvelopesStored(envelopeCount: 0)
}
func testActiveRateLimitForSomeEnvelopeItems() {
givenRateLimitResponse(forCategory: "error")
sendEvent()
sendEnvelopeWithSession()
assertRequestsSent(requestCount: 2)
assertEnvelopesStored(envelopeCount: 0)
}
func testActiveRateLimitForAllCachedEnvelopeItems() {
givenNoInternetConnection()
sendEnvelope()
givenRateLimitResponse(forCategory: "error")
sendEvent()
assertRequestsSent(requestCount: 3)
assertEnvelopesStored(envelopeCount: 0)
}
func testActiveRateLimitForSomeCachedEnvelopeItems() {
givenNoInternetConnection()
sendEvent()
sut.send(envelope: fixture.eventWithSessionEnvelope)
waitForAllRequests()
givenRateLimitResponse(forCategory: "error")
sendEvent()
assertRequestsSent(requestCount: 5)
assertEnvelopesStored(envelopeCount: 0)
let sessionEnvelope = SentryEnvelope(id: fixture.event.eventId, singleItem: SentryEnvelopeItem(session: fixture.session))
let sessionData = try! SentrySerialization.data(with: sessionEnvelope)
let sessionRequest = try! SentryNSURLRequest(envelopeRequestWith: SentryHttpTransportTests.dsn, andData: sessionData)
XCTAssertEqual(sessionRequest.httpBody, fixture.requestManager.requests[3].httpBody, "Envelope with only session item should be sent.")
}
func testAllCachedEnvelopesCantDeserializeEnvelope() throws {
let path = fixture.fileManager.store(TestConstants.envelope)
let faultyEnvelope = Data([0x70, 0xa3, 0x10, 0x45])
try faultyEnvelope.write(to: URL(fileURLWithPath: path))
sendEvent()
assertRequestsSent(requestCount: 1)
assertEnvelopesStored(envelopeCount: 0)
}
func testSendCachedEnvelopesFirst() throws {
givenNoInternetConnection()
sendEvent()
givenOkResponse()
sendEnvelopeWithSession()
fixture.requestManager.waitForAllRequests()
XCTAssertEqual(3, fixture.requestManager.requests.count)
XCTAssertEqual(fixture.eventWithAttachmentRequest.httpBody, fixture.requestManager.requests[1].httpBody, "Cached envelope was not sent first.")
XCTAssertEqual(fixture.sessionRequest.httpBody, fixture.requestManager.requests[2].httpBody, "Cached envelope was not sent first.")
}
func testPerformanceOfSending() {
self.measure {
givenNoInternetConnection()
for _ in 0...5 {
sendEventAsync()
}
givenOkResponse()
for _ in 0...5 {
sendEventAsync()
}
}
}
func testSendEnvelopesConcurrent() {
self.measure {
fixture.requestManager.responseDelay = 0.000_1
let queue = DispatchQueue(label: "SentryHubTests", qos: .utility, attributes: [.concurrent, .initiallyInactive])
let group = DispatchGroup()
for _ in 0...20 {
group.enter()
queue.async {
self.sendEventAsync()
group.leave()
}
}
queue.activate()
group.waitWithTimeout()
waitForAllRequests()
}
XCTAssertEqual(210, fixture.requestManager.requests.count)
}
func testSendUserFeedback() {
sut.send(userFeedback: fixture.userFeedback)
waitForAllRequests()
XCTAssertEqual(1, fixture.requestManager.requests.count)
let actualRequest = fixture.requestManager.requests.last
XCTAssertEqual(fixture.userFeedbackRequest.httpBody, actualRequest?.httpBody, "Request for user feedback is faulty.")
}
func testSendFaultyAttachment() {
let faultyAttachment = Attachment(path: "")
sut.send(event: fixture.event, attachments: [faultyAttachment])
waitForAllRequests()
XCTAssertEqual(1, fixture.requestManager.requests.count)
// The attachment gets dropped
let actualRequest = fixture.requestManager.requests.last
XCTAssertEqual(fixture.eventRequest.httpBody, actualRequest?.httpBody, "Request for faulty attachment is faulty.")
}
private func givenRetryAfterResponse() -> HTTPURLResponse {
let response = TestResponseFactory.createRetryAfterResponse(headerValue: "1")
fixture.requestManager.returnResponse(response: response)
return response
}
@discardableResult private func givenRateLimitResponse(forCategory category: String) -> HTTPURLResponse {
let response = TestResponseFactory.createRateLimitResponse(headerValue: "1:\(category):key")
fixture.requestManager.returnResponse(response: response)
return response
}
private func givenNoInternetConnection() {
fixture.requestManager.returnResponse(response: nil)
}
private func givenOkResponse() {
fixture.requestManager.returnResponse(response: HTTPURLResponse())
}
func givenFirstRateLimitGetsActiveWithSecondResponse() {
var i = -1
fixture.requestManager.returnResponse { () -> HTTPURLResponse? in
i += 1
if i == 0 {
return HTTPURLResponse()
} else {
return TestResponseFactory.createRateLimitResponse(headerValue: "1:error:key")
}
}
}
private func waitForAllRequests() {
fixture.requestManager.waitForAllRequests()
}
private func sendEvent() {
sendEventAsync()
waitForAllRequests()
}
private func sendEventAsync() {
sut.send(event: fixture.event, attachments: [TestData.dataAttachment])
}
private func sendEnvelope(envelope: SentryEnvelope = TestConstants.envelope) {
sut.send(envelope: envelope)
waitForAllRequests()
}
private func sendEnvelopeWithSession() {
sut.send(envelope: fixture.sessionEnvelope)
waitForAllRequests()
}
private func assertRateLimitUpdated(response: HTTPURLResponse) {
XCTAssertEqual(1, fixture.requestManager.requests.count)
XCTAssertTrue(fixture.rateLimits.isRateLimitActive(SentryRateLimitCategory.session))
}
private func assertRequestsSent(requestCount: Int) {
XCTAssertEqual(requestCount, fixture.requestManager.requests.count)
}
private func assertEventIsSentAsEnvelope() {
let actualEventRequest = fixture.requestManager.requests.last
XCTAssertEqual(fixture.eventWithAttachmentRequest.httpBody, actualEventRequest?.httpBody, "Event was not sent as envelope.")
}
private func assertEventAndSesionAreSentInOneEnvelope() {
let actualEventRequest = fixture.requestManager.requests.last
XCTAssertEqual(fixture.eventWithSessionRequest.httpBody, actualEventRequest?.httpBody, "Request for event with session is faulty.")
}
private func assertEnvelopesStored(envelopeCount: Int) {
XCTAssertEqual(envelopeCount, fixture.fileManager.getAllEnvelopes().count)
}
}
| 35.030948 | 204 | 0.662912 |
fc2eddffadcd43f59922c7a8617e39455b92c320 | 469 | //
// Date+.swift
// IssueTracker
//
// Created by 송민관 on 2020/11/13.
//
import Foundation
extension Date {
/// Date를 특정 형식에 맞는 String으로 변환
///
/// 함수를 확장하여 다양하게 사용 가능
///
/// - Returns: String
func timeAgoDisplay() -> String {
let formatter = RelativeDateTimeFormatter()
formatter.unitsStyle = .full
formatter.dateTimeStyle = .numeric
return formatter.localizedString(for: self, relativeTo: Date())
}
}
| 20.391304 | 71 | 0.609808 |
9c65a6ec23dc3cc8b2df638b90ce4ac28346b1c3 | 4,055 | // Generated by Create API
// https://github.com/kean/CreateAPI
//
// swiftlint:disable all
import Foundation
import Get
import URLQueryEncoder
extension Paths {
internal static var token: Token {
Token(path: "/token")
}
internal struct Token {
/// Path: `/token`
internal let path: String
internal func post(grantType: GrantType, redirectURL: URL? = nil, _ body: PostRequest)
-> Request<GoTrue.Session>
{
.post(path, query: makePostQuery(grantType, redirectURL), body: body)
}
private func makePostQuery(_ grantType: GrantType, _ redirectURL: URL?) -> [(String, String?)] {
let encoder = URLQueryEncoder()
encoder.encode(grantType, forKey: "grant_type")
encoder.encode(redirectURL, forKey: "redirect_url")
return encoder.items
}
internal enum GrantType: String, Codable, CaseIterable {
case password
case refreshToken = "refresh_token"
case idToken = "id_token"
}
internal enum PostRequest: Encodable, Equatable {
case userCredentials(GoTrue.UserCredentials)
case openIDConnectCredentials(GoTrue.OpenIDConnectCredentials)
internal func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .userCredentials(let value): try container.encode(value)
case .openIDConnectCredentials(let value): try container.encode(value)
}
}
}
}
}
extension Paths {
internal static var signup: Signup {
Signup(path: "/signup")
}
internal struct Signup {
/// Path: `/signup`
internal let path: String
internal func post(redirectURL: URL? = nil, _ body: GoTrue.SignUpRequest) -> Request<
GoTrue.SessionOrUser
> {
.post(path, query: makePostQuery(redirectURL), body: body)
}
private func makePostQuery(_ redirectURL: URL?) -> [(String, String?)] {
let encoder = URLQueryEncoder()
encoder.encode(redirectURL, forKey: "redirect_url")
return encoder.items
}
}
}
extension Paths {
internal static var otp: Otp {
Otp(path: "/otp")
}
internal struct Otp {
/// Path: `/otp`
internal let path: String
internal func post(redirectURL: URL? = nil, _ body: GoTrue.OTPParams) -> Request<Void> {
.post(path, query: makePostQuery(redirectURL), body: body)
}
private func makePostQuery(_ redirectURL: URL?) -> [(String, String?)] {
let encoder = URLQueryEncoder()
encoder.encode(redirectURL, forKey: "redirect_url")
return encoder.items
}
}
}
extension Paths {
internal static var verify: Verify {
Verify(path: "/verify")
}
internal struct Verify {
/// Path: `/verify`
internal let path: String
internal func post(_ body: GoTrue.VerifyOTPParams) -> Request<GoTrue.SessionOrUser> {
.post(path, body: body)
}
}
}
extension Paths {
internal static var user: User {
User(path: "/user")
}
internal struct User {
/// Path: `/user`
internal let path: String
internal var get: Request<GoTrue.User> {
.get(path)
}
internal func put(_ body: GoTrue.UserAttributes) -> Request<GoTrue.User> {
.put(path, body: body)
}
}
}
extension Paths {
internal static var logout: Logout {
Logout(path: "/logout")
}
internal struct Logout {
/// Path: `/logout`
internal let path: String
internal var post: Request<Void> {
.post(path)
}
}
}
extension Paths {
internal static var recover: Recover {
Recover(path: "/recover")
}
internal struct Recover {
/// Path: `/recover`
internal let path: String
internal func post(redirectURL: URL? = nil, _ body: GoTrue.RecoverParams) -> Request<Void> {
.post(path, query: makePostQuery(redirectURL), body: body)
}
private func makePostQuery(_ redirectURL: URL?) -> [(String, String?)] {
let encoder = URLQueryEncoder()
encoder.encode(redirectURL, forKey: "redirect_url")
return encoder.items
}
}
}
internal enum Paths {}
| 24.136905 | 100 | 0.649075 |
6944f6042fbc012345917264c13290e812aef51e | 3,021 | //
// Created by Benjamin Soung
// Copyright (c) 2016 Benjamin Soung. All rights reserved.
//
import Foundation
import UIKit
class PokemonsCollectionView: UICollectionViewController, PokemonsCollectionViewProtocol
{
private let reuseIdentifier = "PokemonCollectionCell"
private var currentPokemons:[Pokemon]!
var presenter: PokemonsCollectionPresenterProtocol?
override func viewDidLoad() {
super.viewDidLoad();
// Register cell classes
self.collectionView!.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
// Initialize the data structrure
self.currentPokemons = [Pokemon]()
guard (presenter != nil) else {
return
}
presenter!.loadPokemons()
}
// MARK: UICollectionViewDataSource
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of items
print ("collectionView \(currentPokemons.count)")
return currentPokemons.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath)
cell.backgroundColor = UIColor.whiteColor()
// Configure the cell
return cell
}
// MARK PRESENTER -> VIEW
func showErrorMessage(message:String) {
// TODO localize the title and the 'Yes' button
let alertController = UIAlertController(title: "Alert", message: message, preferredStyle: .Alert)
// Initialize Actions
let yesAction = UIAlertAction(title: "Yes", style: .Default) { (action) -> Void in
print("The user is okay.")
}
// Add Actions
alertController.addAction(yesAction)
// Present Alert Controller
self.presentViewController(alertController, animated: true, completion: nil)
}
func renderData(value: [Pokemon]) {
currentPokemons = value
self.collectionView?.reloadData()
}
// MARK: - User Interactions
@IBAction func openFavorites(sender: AnyObject) {
guard (presenter != nil) else {
return
}
presenter!.openFavorites()
}
@IBAction func openDetails(sender: AnyObject) {
guard (presenter != nil) else {
return
}
presenter!.openDetails("test")
}
} | 28.5 | 139 | 0.618007 |
f8080793d84ef18303309da49fc582b2d1ce83d1 | 549 | import Foundation
struct RESTError: Error, LocalizedError, Decodable {
let errorMessage: String?
let errorCode: String
var statusCodeError: HTTPStatusCodeError? {
Int(errorCode).flatMap { HTTPStatusCodeError(statusCode: $0) }
}
var errorDescription: String? {
return errorMessage
}
}
extension RESTError {
init?(statusCode: Int) {
if 200..<300 ~= statusCode {
return nil
} else {
self = .init(errorMessage: nil, errorCode: String(statusCode))
}
}
}
| 21.96 | 74 | 0.621129 |
21aef34731a268b72b344349d89b57916c83b0e5 | 761 | //
// ViewController.swift
// RxSwiftPractice
//
// Created by Vincent Bacalso on 14/12/2017.
// Copyright © 2017 Command Bin. All rights reserved.
//
import UIKit
import RxSwift
class MasterViewController: UIViewController {
@IBOutlet weak var greetingsLabel: UILabel!
let disposeBag = DisposeBag()
@IBAction func selectCharacter(_ sender: Any) {
let detailVC = storyboard?.instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController
detailVC.selectedCharacter
.subscribe(onNext: { [weak self] character in
self?.greetingsLabel.text = "Hello \(character)"
}).disposed(by: disposeBag)
navigationController?.pushViewController(detailVC, animated: true)
}
}
| 23.78125 | 121 | 0.713535 |
5dfa1c56cbba0d56cd4bf295f90c0c4e9595b1cb | 6,312 | //
// InterfaceController.swift
// AirTime WatchKit App Extension
//
// Created by Lincoln Fraley on 9/7/18.
// Copyright © 2018 Dynepic, Inc. All rights reserved.
//
import WatchKit
import Foundation
import HealthKit
import CoreMotion
import WatchConnectivity
class ChallengeInterfaceController: WKInterfaceController {
// MARK: - Outlets
@IBOutlet var jumpLabel: WKInterfaceButton!
// MARK: Properties
var active = false
let motionManager = CMMotionManager()
let queue = OperationQueue()
let healthStore = HKHealthStore()
var session: HKWorkoutSession?
let upperBound = 20.0
let lowerBound = 2.0
let sampleRate = 60
var sampleInterval: Int {
get { return 1 / sampleRate }
}
var bufferSize: Int {
get { return sampleRate / 5 }
}
var jumpCounter: JumpCounter?
var jumpsArray : [Date] = []
var watchSession: WCSession? {
didSet {
if let session = watchSession {
session.delegate = self
session.activate()
}
}
}
// MARK: Initialization
override init() {
super.init()
queue.maxConcurrentOperationCount = 1
queue.name = "MotionManagerQueue"
self.start()
}
// MARK: WKInterfaceController
override func awake(withContext context: Any?) {
super.awake(withContext: context)
self.watchSession = WCSession.default
}
override func willActivate() {
super.willActivate()
active = true
}
override func didDeactivate() {
super.didDeactivate()
active = false
}
func start() {
jumpsArray = []
jumpLabel.setTitle("\(jumpsArray.count)")
// If we have already started the workout, then do nothing.
if (session != nil) {
return
}
// Configure the workout session.
let workoutConfiguration = HKWorkoutConfiguration()
workoutConfiguration.activityType = .play
workoutConfiguration.locationType = .outdoor
do {
session = try HKWorkoutSession(configuration: workoutConfiguration)
} catch {
fatalError("Unable to create the workout session!")
}
// Start the workout session and device motion updates.
healthStore.start(session!)
if !motionManager.isDeviceMotionAvailable {
print("Device Motion is not available.")
return
}
// Reset everything when we start.
jumpCounter = JumpCounter(upperBound: upperBound, lowerBound: lowerBound, sampleRate: sampleRate, bufferSize: bufferSize, jumpFound: jumpFound)
motionManager.deviceMotionUpdateInterval = TimeInterval(sampleInterval)
motionManager.startAccelerometerUpdates(to: queue) { deviceMotion, error in
if error != nil {
print("Encountered error: \(error!)")
}
if let deviceMotion = deviceMotion {
self.jumpCounter?.input(x: deviceMotion.acceleration.x, y: deviceMotion.acceleration.y, z: deviceMotion.acceleration.z)
}
}
}
@IBAction func stop() {
if (session == nil) {
return
}
// Stop the device motion updates and workout session.
if motionManager.isDeviceMotionAvailable {
motionManager.stopDeviceMotionUpdates()
}
healthStore.end(session!)
// Clear the workout session.
session = nil
// Clear jump counter
jumpCounter = nil
jumpLabel.setTitle("\(0)")
let longestJumpTime = calculateLongestJump()
print("LONGEST: \(longestJumpTime)")
//send numJump to phone
do {
try watchSession!.updateApplicationContext(
[
"totalJumps" : jumpsArray.count,
"longestJump": longestJumpTime
]
)
} catch {
print("ERROR")
}
WKInterfaceController.reloadRootPageControllers(withNames: ["InitialInterfaceController"], contexts: [], orientation: WKPageOrientation.horizontal, pageIndex: 0)
// WKInterfaceController.reloadRootControllers(withNames: ["InitialInterfaceController"], contexts: [])
}
// MARK: Methods
func jumpFound(time: Date) {
jumpsArray.append(time)
jumpLabel.setTitle("\(jumpsArray.count)")
}
@IBAction func incrementJumpLabel() {
#if DEBUG
jumpsArray.append(Date())
jumpLabel.setTitle("\(jumpsArray.count)")
#endif
}
func calculateLongestJump() -> Double {
var longestJumpTime : Double = 0.0
var index = 0
while index < jumpsArray.count - 1 {
let firstJumpTime: Date = jumpsArray[index]
let secondJumpTime: Date = jumpsArray[index+1]
let jumpDuration = secondJumpTime.timeIntervalSince(firstJumpTime)
if (jumpDuration > longestJumpTime) {
longestJumpTime = jumpDuration
}
index += 1
}
return longestJumpTime
}
}
extension ChallengeInterfaceController: WCSessionDelegate {
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
print("Session activation did complete")
}
}
extension TimeInterval {
public var milliseconds: Int {
return Int((truncatingRemainder(dividingBy: 1)) * 1000)
}
public var seconds: Int {
return Int(self) % 60
}
private var minutes: Int {
return (Int(self) / 60 ) % 60
}
private var hours: Int {
return Int(self) / 3600
}
var stringTime: String {
if hours != 0 {
return "\(hours)h \(minutes)m \(seconds)s"
} else if minutes != 0 {
return "\(minutes)m \(seconds)s"
} else if milliseconds != 0 {
return "\(seconds)s \(milliseconds)ms"
} else {
return "\(seconds)s"
}
}
}
| 28.178571 | 169 | 0.579848 |
3a6d317218b2ebbe5636cc2ca4a6da710994f860 | 928 | //
// PokemonNumberGenerator.swift
// Domain
//
// Created by Tomosuke Okada on 2020/04/29.
//
import Foundation
enum PokemonNumberGenerator {
static func generate(from url: String) -> Int {
if let number = self.generate(fromPokemon: url) {
return number
}
if let number = self.generate(fromPokemonSpecies: url) {
return number
}
return 0
}
private static func generate(fromPokemon url: String) -> Int? {
var removePrefix = url.replacingOccurrences(of: "https://pokeapi.co/api/v2/pokemon/", with: "")
removePrefix.removeLast()
return Int(removePrefix)
}
private static func generate(fromPokemonSpecies url: String) -> Int? {
var removePrefix = url.replacingOccurrences(of: "https://pokeapi.co/api/v2/pokemon-species/", with: "")
removePrefix.removeLast()
return Int(removePrefix)
}
}
| 27.294118 | 111 | 0.634698 |
8746e4819c93f04bf3ec5875b829b0d2a0393f22 | 468 | import Foundation
/// Categories of physical activity, organized by physiologic classification.
public enum PhysicalActivityCategory: String, PhysicalActivityCategoryOrThingOrText {
case aerobic = "AerobicActivity"
case anaerobic = "AnaerobicActivity"
case balance = "Balance"
case flexibility = "Flexibility"
case leisureTime = "LeisureTimeActivity"
case occupational = "OccupationalActivity"
case strengthTraining = "StrengthTraining"
}
| 36 | 85 | 0.775641 |
5d7db2fdfd290d671e57252f16cb1429695276dd | 2,468 | //
// HandlerHelpers.swift
// Perfect-App-Template
//
// Created by Jonathan Guthrie on 2017-04-01.
//
//
import PerfectHTTP
import StORM
import LocalAuthentication
extension Handlers {
static func extras(_ request: HTTPRequest) -> [String : Any] {
return [
"token": request.session?.token ?? "",
"csrfToken": request.session?.data["csrf"] as? String ?? ""
]
}
static func appExtras(_ request: HTTPRequest) -> [String : Any] {
var priv = ""
var isAdmin = false
let id = request.session?.userid ?? ""
if !id.isEmpty {
let user = Account()
try? user.get(id)
priv = "\(user.usertype)"
if user.usertype == .admin {
isAdmin = true
}
}
return [
"configTitle": configTitle,
"configLogo": configLogo,
"configLogoSrcSet": configLogoSrcSet,
"priv": priv,
"admin": isAdmin
]
}
static func errorJSON(_ request: HTTPRequest, _ response: HTTPResponse, msg: String) {
_ = try? response.setBody(json: ["error": msg])
response.completed()
}
static func error(_ request: HTTPRequest, _ response: HTTPResponse, error: String, code: HTTPResponseStatus = .badRequest) {
do {
response.status = code
try response.setBody(json: ["error": "\(error)"])
} catch {
print(error)
}
response.completed()
}
static func unimplemented(data: [String:Any]) throws -> RequestHandler {
return {
request, response in
response.status = .notImplemented
response.completed()
}
}
// Common helper function to dump rows to JSON
static func nestedDataDict(_ rows: [StORM]) -> [Any] {
var d = [Any]()
for i in rows {
d.append(i.asDataDict())
}
return d
}
// Used for healthcheck functionality for monitors and load balancers.
// Do not remove unless you have an alternate plan
static func healthcheck(data: [String:Any]) throws -> RequestHandler {
return {
request, response in
let _ = try? response.setBody(json: ["health": "ok"])
response.completed()
}
}
// Handles psuedo redirects.
// Will serve up alternate content, for example if you wish to report an error condition, like missing data.
static func redirectRequest(_ request: HTTPRequest, _ response: HTTPResponse, msg: String, template: String, additional: [String:String] = [String:String]()) {
var context: [String : Any] = [
"msg": msg
]
for i in additional {
context[i.0] = i.1
}
response.renderMustache(template: template, context: context)
response.completed()
return
}
}
| 23.283019 | 160 | 0.668152 |
486cf279a1b73218145720a9f305d84049ed5405 | 635 | class Solution {
func oddCells(_ n: Int, _ m: Int, _ indices: [[Int]]) -> Int {
var arr = Array<Array<Int>>(repeating: Array<Int>(repeating: 0, count: m), count: n)
indices.forEach { xy in
let x = xy[0]
let y = xy[1]
for i in 0..<n {
arr[i][y] += 1
}
for j in 0..<m {
arr[x][j] += 1
}
}
var ans = 0
arr.forEach { row in
row.forEach { ele in
if (ele % 2 == 1) {
ans += 1
}
}
}
return ans
}
} | 26.458333 | 92 | 0.352756 |
89ccb0541a027884eb35a06d37a20ac4c9efe2bd | 617 | //
// VideoClientState.swift
// AmazonChimeSDK
//
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//
import Foundation
@objc enum VideoClientState: Int32 {
case uninitialized = -1
case initialized = 0
case started = 1
case stopped = 2
var description: String {
switch self {
case .uninitialized:
return "uninitialized"
case .initialized:
return "initialized"
case .started:
return "started"
case .stopped:
return "stopped"
}
}
}
| 20.566667 | 70 | 0.593193 |
0e33d0ac9a496312301836249f4e6880c83984e5 | 1,418 | //
// FastOrderUITests.swift
// FastOrderUITests
//
// Created by Mina Ashna on 18/11/2020.
//
import XCTest
class FastOrderUITests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// UI tests must launch the application that they test.
let app = XCUIApplication()
app.launch()
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testLaunchPerformance() throws {
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTApplicationLaunchMetric()]) {
XCUIApplication().launch()
}
}
}
}
| 32.976744 | 182 | 0.656559 |
e22ac848db2df2d1640dc44ba2b7e3e9f5accd65 | 630 | import Foundation
// MARK: - GraphQL.Operation Extensions
extension GraphQLOperation {
public var queryString: String {
return description
}
public var description: String {
let operationName = name.isEmpty ? "" : " \(name)"
return "\(type)\(operationName)\(renderOperationArgumentsList(arguments))\(renderSelectionSet(selectionSet))"
}
public var debugDescription: String {
switch type {
case .mutation:
return "GraphQL.Mutation(\(description))"
case .query:
return "GraphQL.Query(\(description))"
}
}
}
| 25.2 | 117 | 0.609524 |
562865fd2fb68ac4b18cc20a37285cc61da0738b | 2,379 | //
// AppDelegate.swift
// AddressPicker
//
// Created by Cavan on 2018/11/18.
// Copyright © 2018 cavanlee. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
self.window = UIWindow(frame: UIScreen.main.bounds)
// Override point for customization after application launch.
self.window!.backgroundColor = UIColor.white
self.window!.makeKeyAndVisible()
window?.rootViewController = ViewController()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.647059 | 285 | 0.749475 |
8aec438d5ea7f021d95cae623f6f6d1fb5e1348a | 3,627 | import UIKit
class UserInformationView: UIView {
let viewModel: SimplifiedLoginViewModel
private let isPhone: Bool = UIDevice.current.userInterfaceIdiom == .phone
lazy var internalConstraints: [NSLayoutConstraint] = {
return [avatarView.heightAnchor.constraint(equalToConstant: 48),
avatarView.widthAnchor.constraint(equalToConstant: 48),
avatarView.leadingAnchor.constraint(lessThanOrEqualTo: leadingAnchor, constant: isPhone ? 45 : 15),
avatarView.leadingAnchor.constraint(greaterThanOrEqualTo: leadingAnchor, constant: 10),
initialsLabel.centerXAnchor.constraint(equalTo: avatarView.centerXAnchor),
initialsLabel.centerYAnchor.constraint(equalTo: avatarView.centerYAnchor),
nameLabel.topAnchor.constraint(equalTo: topAnchor, constant: 5),
nameLabel.leadingAnchor.constraint(equalTo: avatarView.trailingAnchor, constant: 16),
nameLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -16),
emailLabel.leadingAnchor.constraint(equalTo: avatarView.trailingAnchor, constant: 16),
emailLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -16),
emailLabel.topAnchor.constraint(equalTo: nameLabel.bottomAnchor, constant: 2),
emailLabel.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -5)
]
}()
// MARK: User information
private lazy var avatarView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.layer.cornerRadius = 23
view.backgroundColor = SchibstedColor.blue.value
return view
}()
private lazy var initialsLabel: UILabel = {
let view = UILabel()
view.text = viewModel.initials
view.isAccessibilityElement = false
view.font = UIFont.boldSystemFont(ofSize: 17)
view.textAlignment = .center
view.textColor = .white
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
private lazy var nameLabel: UILabel = {
let view = UILabel()
view.text = viewModel.displayName
view.font = UIFont.preferredFont(forTextStyle: .callout).bold()
view.textAlignment = .left
view.lineBreakMode = .byWordWrapping
view.numberOfLines = 0
view.sizeToFit()
view.textColor = SchibstedColor.textDarkGrey.value
view.translatesAutoresizingMaskIntoConstraints = false
view.adjustsFontForContentSizeCategory = true
return view
}()
private lazy var emailLabel: UILabel = {
let view = UILabel()
view.text = viewModel.email
view.font = UIFont.preferredFont(forTextStyle: .footnote)
view.textAlignment = .left
view.lineBreakMode = .byCharWrapping
view.numberOfLines = 0
view.sizeToFit()
view.textColor = SchibstedColor.textLightGrey.value
view.translatesAutoresizingMaskIntoConstraints = false
view.adjustsFontForContentSizeCategory = true
return view
}()
init(viewModel: SimplifiedLoginViewModel) {
self.viewModel = viewModel
super.init(frame: .zero)
translatesAutoresizingMaskIntoConstraints = false
avatarView.addSubview(initialsLabel)
addSubview(avatarView)
addSubview(nameLabel)
addSubview(emailLabel)
}
required init(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
}
| 40.3 | 115 | 0.669424 |
9be34a491db13401e5a80a2b7b745d3d4c28fcbf | 1,453 | //
// PDFLayoutIndentations+Equatable_Spec.swift
// TPPDF_Tests
//
// Created by Philip Niedertscheider on 14/11/2017.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import Quick
import Nimble
@testable import TPPDF
class PDFLayoutIndentations_Equatable_Spec: QuickSpec {
override func spec() {
describe("PDFLayoutIndentations") {
context("Equatable") {
let indentation = PDFLayoutIndentations()
it("is equal") {
let otherIndentation = PDFLayoutIndentations()
expect(indentation) == otherIndentation
}
it("is not equal with different header") {
var otherIndentation = PDFLayoutIndentations()
otherIndentation.header = (10, 20)
expect(indentation) != otherIndentation
}
it("is not equal with different footer") {
var otherIndentation = PDFLayoutIndentations()
otherIndentation.content = (10, 20)
expect(indentation) != otherIndentation
}
it("is not equal with different content value") {
var otherIndentation = PDFLayoutIndentations()
otherIndentation.footer = (10, 20)
expect(indentation) != otherIndentation
}
}
}
}
}
| 29.653061 | 66 | 0.54852 |
23039f539b255491d5c78a0b8ed0c2f40a461ff4 | 1,521 | //
// HelperExtensions.swift
// CloudFunctions
//
// Created by Robert Canton on 2017-09-13.
// Copyright © 2017 Robert Canton. All rights reserved.
//
import Foundation
import UIKit
extension UIButton {
private func imageWithColor(color: UIColor) -> UIImage {
let rect = CGRect(x: 0.0,y: 0.0,width: 1.0,height: 1.0)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context!.setFillColor(color.cgColor)
context!.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
func setBackgroundColor(color: UIColor, forUIControlState state: UIControlState) {
self.setBackgroundImage(imageWithColor(color: color), for: state)
}
}
extension UIView {
/**
Adds a vertical gradient layer with two **UIColors** to the **UIView**.
- Parameter topColor: The top **UIColor**.
- Parameter bottomColor: The bottom **UIColor**.
*/
func addVerticalGradientLayer(topColor:UIColor, bottomColor:UIColor) {
let gradient = CAGradientLayer()
gradient.frame = self.bounds
gradient.colors = [
topColor.cgColor,
bottomColor.cgColor
]
gradient.locations = [0.0, 1.0]
gradient.startPoint = CGPoint(x: 0, y: 0)
gradient.endPoint = CGPoint(x: 0, y: 1)
self.layer.insertSublayer(gradient, at: 0)
}
}
| 27.654545 | 86 | 0.629849 |
20568ff3ff0a0b50d4c70ead57c85924c8a0387c | 3,584 | //
// ViewController.swift
// NFCDemo
//
// Created by Piotr Dębosz on 07/06/2017.
// Copyright © 2017 Applicator. All rights reserved.
//
import UIKit
import CoreNFC
import SnapKit
class MainViewController: UIViewController {
private var manager: NFCManager?
private let tableView: UITableView = UITableView()
private var messages: [NFCNDEFMessage] = []
override func viewDidLoad() {
super.viewDidLoad()
self.setUpNavigationBar()
self.setUpUI()
self.manager = NFCManager(didDetectTag: { [unowned self] (message) in
self.addNewMessage(message: message)
}, didInvalidateWithError: { (error) in
print("Error: \(error)")
})
}
private func addNewMessage(message: NFCNDEFMessage) {
self.messages.append(message)
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
private func setUpNavigationBar() {
self.title = "Tags"
let refreshButton = UIBarButtonItem(image: #imageLiteral(resourceName: "refresh"), style: .plain, target: self, action: #selector(refresh))
let cleanButton = UIBarButtonItem(image: #imageLiteral(resourceName: "broom"), style: .plain, target: self, action: #selector(clean))
self.navigationItem.leftBarButtonItem = cleanButton
self.navigationItem.rightBarButtonItem = refreshButton
self.navigationController?.navigationBar.tintColor = .black
}
@objc private func refresh() {
self.manager?.startLookingForTag()
}
private func setUpUI() {
self.view.addSubview(self.tableView)
self.tableView.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
}
self.tableView.register(RecordTableViewCell.self, forCellReuseIdentifier: "RecordCell")
self.tableView.dataSource = self
self.tableView.delegate = self
}
}
extension MainViewController {
@objc private func clean() {
self.messages.removeAll()
self.tableView.reloadData()
}
}
extension MainViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return self.messages.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.messages[section].records.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "RecordCell", for: indexPath) as? RecordTableViewCell else {
fatalError("Cannot dequeue record cell!")
}
let record = self.messages[indexPath.section].records[indexPath.row]
cell.configure(identifier: record.identifierString(), type: record.typeString())
return cell
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return SectionHeaderView(section: section)
}
}
extension MainViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let detailViewController = DetailViewController(record: self.messages[indexPath.section].records[indexPath.row])
self.navigationController?.pushViewController(detailViewController, animated: true)
}
}
| 32.581818 | 147 | 0.659877 |
87b6b5453888e0d1083a65c772f8d58f5cab6072 | 3,311 | //
// Stem
//
// Copyright (c) 2017 linhay - https://github.com/linhay
//
// 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
import UIKit
public extension UITextField{
/// 占位文字颜色
public var placeholderColor: UIColor? {
get{
guard var attr = attributedPlaceholder?.attributes(at: 0, effectiveRange: nil),
let color = attr[NSAttributedString.Key.foregroundColor] as? UIColor else{ return textColor }
return color
}
set {
guard let placeholder = self.placeholder, let color = newValue else { return }
if var attr = attributedPlaceholder?.attributes(at: 0, effectiveRange: nil) {
attr[NSAttributedString.Key.foregroundColor] = newValue
attributedPlaceholder = NSAttributedString(string: placeholder, attributes: attr)
return
}
let attr = [NSAttributedString.Key.foregroundColor: color]
attributedPlaceholder = NSAttributedString(string: placeholder, attributes: attr)
}
}
/// 占位文字字体
public var placeholderFont: UIFont? {
get{
guard var attr = attributedPlaceholder?.attributes(at: 0, effectiveRange: nil),
let ft = attr[.font] as? UIFont else{ return font }
return ft
}
set {
guard let placeholder = self.placeholder, let font = newValue else { return }
if var attr = attributedPlaceholder?.attributes(at: 0, effectiveRange: nil) {
attr[NSAttributedString.Key.font] = newValue
attributedPlaceholder = NSAttributedString(string: placeholder, attributes: attr)
return
}
let attr = [NSAttributedString.Key.font: font]
attributedPlaceholder = NSAttributedString(string: placeholder, attributes: attr)
}
}
/// 左边间距
@IBInspectable var leftPadding: CGFloat {
get {
return leftView?.frame.size.width ?? 0
}
set {
let view = UIView(frame: CGRect(x: 0, y: 0, width: newValue, height: frame.size.height))
leftView = view
leftViewMode = .always
}
}
/// 右边间距
@IBInspectable var rightPadding: CGFloat {
get {
return rightView?.frame.size.width ?? 0
}
set {
let view = UIView(frame: CGRect(x: 0, y: 0, width: newValue, height: frame.size.height))
rightView = view
rightViewMode = .always
}
}
}
| 35.602151 | 101 | 0.687104 |
031caeb3c6c04b28b2e9dd41f71f248ab6e5ccb7 | 8,356 | import UIKit
import SwiftAdditions
import SwiftDate
public protocol FormViewControllerDelegate: class {
func customizeMonthYearInputView(_ inputView: MonthYearInputView, for textField: UITextField)
func customizeDateInputView(_ inputView: UIDatePicker, for textField: UITextField)
func customizeListInputView(_ inputView: ListInputView, for textField: UITextField)
}
/// This class is meant to be subclassed only
open class FormViewController: UITableViewController {
public enum FormEntry: Int { // tag textfields in storyboard with these numbers
case `default` = 0, state = 10, country = 20, date = 30, monthYear = 40, list = 50
}
public enum FormState {
case none, editing, done, saving
}
@IBOutlet private var textFields: [TextField]! {
didSet {
self.textFields.forEach {
$0.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
$0.addTarget(self, action: #selector(textFieldDidBeginEditing), for: .editingDidBegin)
$0.addTarget(self, action: #selector(textFieldDidEndEditing), for: .editingDidEnd)
$0.addTarget(self, action: #selector(textFieldDidReturn), for: .editingDidEndOnExit)
}
}
}
private let textFieldInputAccessoryView: InputAccessoryView = InputAccessoryView()
private var hideRows: Bool = false
private var isCountryUS = true
public weak var delegate: FormViewControllerDelegate?
public var state: FormState = .none {
didSet {
formStateDidChange()
}
}
open override func numberOfSections(in tableView: UITableView) -> Int {
return self.hideRows ? 0 : super.numberOfSections(in: tableView)
}
open override var inputAccessoryView: UIView? {
self.textFieldInputAccessoryView.formDoneTitle = "Done"
self.textFieldInputAccessoryView.doneHandler = { textField in
self.view.endEditing(true)
}
self.textFieldInputAccessoryView.moveToNextHandler = { current in
guard
let current = current as? TextField,
let index = self.textFields.firstIndex(of: current)
else { return }
if (index + 1) < self.textFields.count {
let textField = self.textFields[safe: index + 1]
textField?.becomeFirstResponder()
} else {
let textField = self.textFields[safe: 0]
textField?.becomeFirstResponder()
}
}
self.textFieldInputAccessoryView.moveToPreviousHandler = { current in
guard
let current = current as? TextField,
let index = self.textFields.firstIndex(of: current)
else { return }
if (index - 1) > -1 {
let textField = self.textFields[safe: index - 1]
textField?.becomeFirstResponder()
} else {
let textField = self.textFields[safe: self.textFields.count - 1]
textField?.becomeFirstResponder()
}
}
return self.textFieldInputAccessoryView
}
open func formStateDidChange() {
/* to be overriden */
}
open func handleFormSubmit(_ textField: UITextField) {
/* to be overriden */
}
open func isEntriesValid() -> Bool {
return self.textFields.filter { !$0.validate() }.isEmpty
}
private func updateInputView(_ textField: UITextField) {
guard let entry = FormEntry(rawValue: textField.tag) else { return }
self.textFieldInputAccessoryView.inputType = .form
self.textFieldInputAccessoryView.view = textField
switch entry {
case .state where self.isCountryUS:
let states = ResourceUtils.states.map { $0.name }.sorted()
listInputView(for: textField, items: states)
textField.placeholder = "State"
case .state where !self.isCountryUS:
textField.placeholder = "Province/Region"
textField.inputView = nil
case .country:
var countries = ResourceUtils.countries.map { $0.region }.sorted()
countries.insert("United States", at: 0)
listInputView(for: textField, items: countries)
case .date:
dateInputView(for: textField)
case .monthYear:
monthYearInputView(for: textField)
case .list:
listInputView(for: textField)
default:
textField.inputView = nil
}
}
private func checkIfCountryIsUS(_ textField: UITextField) {
guard textField.tag == FormEntry.country.rawValue else { return }
self.isCountryUS = textField.text?.lowercased() == "united states"
self.textFields.forEach {
if $0.tag == FormEntry.state.rawValue {
$0.placeholder = self.isCountryUS ? "State" : "Province/Region"
}
}
}
}
extension FormViewController {
@objc open func textFieldDidChange(_ sender: UITextField) {
self.state = !self.textFields.filter { $0.text.isNilOrEmpty }.isEmpty ? .editing : .done
}
@objc open func textFieldDidBeginEditing(_ textField: UITextField) {
updateInputView(textField)
}
@objc open func textFieldDidEndEditing(_ textField: UITextField) {
/* to be overriden, if needed */
}
@objc open func textFieldDidReturn(_ textField: UITextField) {
guard
let current = textField as? TextField,
let index = self.textFields.firstIndex(of: current)
else { return }
if (index + 1) < self.textFields.count {
let textField = self.textFields[safe: index + 1]
textField?.becomeFirstResponder()
} else if textField.returnKeyType == .done || textField.returnKeyType == .send || textField.returnKeyType == .go {
handleFormSubmit(textField)
} else if textField.returnKeyType == .default {
textField.resignFirstResponder()
} else {
let textField = self.textFields[safe: 0]
textField?.becomeFirstResponder()
}
}
}
extension FormViewController {
private func listInputView(for textField: UITextField, items: [String] = []) {
let listInputView = ListInputView(frame: CGRect(width: self.view.bounds.width, height: 232))
listInputView.items = items
textField.inputView = listInputView
if let entry = FormEntry(rawValue: textField.tag), entry == .list {
self.delegate?.customizeListInputView(listInputView, for: textField)
}
listInputView.didSelectItem = { value in
textField.text = value
self.state = .editing
self.textFieldDidChange(textField)
self.checkIfCountryIsUS(textField)
}
}
private func dateInputView(for textField: UITextField) {
let datePickerView = UIDatePicker()
datePickerView.datePickerMode = .date
datePickerView.minuteInterval = 30
datePickerView.backgroundColor = .white
textField.inputView = datePickerView
self.delegate?.customizeDateInputView(datePickerView, for: textField)
datePickerView.addTarget(self, action: #selector(dateValueChanged(_:)), for: .valueChanged)
}
private func monthYearInputView(for textField: UITextField) {
let monthYearPickerView = MonthYearInputView()
textField.inputView = monthYearPickerView
self.delegate?.customizeMonthYearInputView(monthYearPickerView, for: textField)
monthYearPickerView.valueDidChange = { month, year in
textField.text = String(format: "%02d/%d", month, year)
self.state = .editing
self.textFieldDidChange(textField)
}
}
@objc private func dateValueChanged(_ datePickerView: UIDatePicker) {
guard let inputAccessoryView = self.inputAccessoryView as? InputAccessoryView,
let textField = inputAccessoryView.view as? UITextField else { return }
textField.text = datePickerView.date.toString(.custom(.defaultDateFormat))
self.state = .editing
self.textFieldDidChange(textField)
}
}
| 37.303571 | 122 | 0.631044 |
5b5be3b35445d39a0953c3ab453b46fbba65bb19 | 10,444 | //
// ViewController.m
// mobile_ios_sample_swift
//
// Created by 大塚 恒平 on 2017/02/22.
// Copyright © 2017年 TileMapJp. All rights reserved.
//
import UIKit
import CoreLocation
import MaplatView
var BaseLongitude = 141.1529555
var BaseLatitude = 39.7006006
class ViewController : UIViewController, MaplatViewDelegate, CLLocationManagerDelegate {
var locationManager: CLLocationManager?
var nowMap: String?
var nowDirection: CDouble?
var nowRotation: CDouble?
var defaultLongitude: CDouble?
var defaultLatitude: CDouble?
var maplatView: MaplatView?
override func loadView() {
super.loadView()
let setting = ["app_name":"モバイルアプリ", "sources":["gsi","osm",["mapID":"morioka_ndl"]], "pois":[]] as [String : Any]
self.maplatView = MaplatView(frame: UIScreen.main.bounds, appID: "mobile", setting: setting)
self.maplatView!.delegate = self
self.view = self.maplatView
self.nowMap = "morioka_ndl"
self.nowDirection = 0
self.nowRotation = 0
// テストボタンの生成
for i in 1...7 {
let button: UIButton = UIButton()
button.tag = i
button.frame = CGRect(x:10, y:CGFloat(i*60), width:120, height:40)
button.alpha = 0.8
button.backgroundColor = UIColor.lightGray
switch i {
case 1:
button.setTitle("地図切替", for: .normal)
break
case 2:
button.setTitle("マーカー追加", for: .normal)
break
case 3:
button.setTitle("マーカー消去", for: .normal)
break
case 4:
button.setTitle("地図移動", for: .normal)
break
case 5:
button.setTitle("東を上", for: .normal)
break
case 6:
button.setTitle("右を上", for: .normal)
break
case 7:
button.setTitle("表示地図情報", for: .normal)
break
default:
button.setTitle("button \(i)", for: .normal)
break
}
button.addTarget(self, action:#selector(testButton(_:)) , for: .touchUpInside)
self.view.addSubview(button)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//[NSThread sleepForTimeInterval:10]; //Safariのデバッガを繋ぐための時間。本番では不要。
self.defaultLongitude = 0
self.defaultLatitude = 0
self.locationManager = CLLocationManager()
self.locationManager!.delegate = self
self.locationManager!.desiredAccuracy = kCLLocationAccuracyBestForNavigation
self.locationManager!.distanceFilter = kCLDistanceFilterNone
if self.locationManager!.responds(to: #selector(CLLocationManager.requestWhenInUseAuthorization)) {
self.locationManager!.requestWhenInUseAuthorization()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - MaplatBridgeDelegate
func onReady() {
self.addMarkers()
self.locationManager!.startUpdatingLocation()
}
func onClickMarker(markerId: String, markerData: Any?) {
let message = "clickMarker ID:\(markerId) DATA:\(markerData ?? "")"
self.toast(message)
}
func onChangeViewpoint(x: Double, y: Double, latitude: Double, longitude: Double, mercatorX mercator_x: Double, mercatorY mercator_y: Double, zoom: Double, mercZoom merc_zoom: Double, direction: Double, rotation: Double) {
print("XY: (\(x), \(y)) LatLong: (\(latitude), \(longitude)) Mercator (\(mercator_x), \(mercator_y)) zoom: \(zoom) mercZoom: \(merc_zoom) direction: \(direction) rotation \(rotation)")
}
func onOutOfMap() {
self.toast("地図範囲外です")
}
func onClickMap(latitude: Double, longitude: Double) {
let message: String = "clickMap latitude:\(latitude) longitude:\(longitude)"
self.toast(message)
}
func addMarkers() {
self.maplatView!.addLineWithLngLat([[141.1501111,39.69994722],[141.1529555,39.7006006]], stroke: nil)
self.maplatView!.addLineWithLngLat([[141.151995,39.701599],[141.151137,39.703736],[141.1521671,39.7090232]], stroke: ["color":"#ffcc33", "width":2])
self.maplatView!.addMarkerWithLatitude(39.69994722, longitude: 141.1501111, markerId: 1, stringData: "001")
self.maplatView!.addMarkerWithLatitude(39.7006006, longitude: 141.1529555, markerId: 5, stringData: "005")
self.maplatView!.addMarkerWithLatitude(39.701599, longitude: 141.151995, markerId: 6, stringData: "006")
self.maplatView!.addMarkerWithLatitude(39.703736, longitude: 141.151137, markerId: 7, stringData: "007")
self.maplatView!.addMarkerWithLatitude(39.7090232, longitude: 141.1521671, markerId: 9, stringData: "009")
}
// MARK: - Location Manager
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let newLocation = locations[0]
if newLocation.horizontalAccuracy < 0 {
return
}
let locationAge: TimeInterval = -newLocation.timestamp.timeIntervalSinceNow
if locationAge > 5.0 {
return
}
print("location updated. newLocation:\(newLocation)")
var latitude: CDouble
var longitude: CDouble
if self.defaultLatitude == 0 || self.defaultLongitude == 0 {
self.defaultLatitude = newLocation.coordinate.latitude
self.defaultLongitude = newLocation.coordinate.longitude
latitude = BaseLatitude
longitude = BaseLongitude
} else {
latitude = BaseLatitude-self.defaultLatitude!+newLocation.coordinate.latitude
longitude = BaseLongitude-self.defaultLongitude!+newLocation.coordinate.longitude
}
self.maplatView!.setGPSMarkerWithLatitude(latitude, longitude: longitude, accuracy: newLocation.horizontalAccuracy)
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
if ((error as NSError).code != CLError.locationUnknown.rawValue) {
self.locationManager!.stopUpdatingLocation()
self.locationManager!.delegate = nil
}
}
// MARK: - test
// テストボタン アクション
@objc
func testButton(_ button: UIButton) {
var nextMap: String
var nextDirection: CDouble
var nextRotation: CDouble
switch Int32(button.tag) {
case 1:
nextMap = self.nowMap == "morioka_ndl" ? "gsi" : "morioka_ndl"
self.maplatView!.changeMap(nextMap)
self.nowMap = nextMap
break
case 2:
self.addMarkers()
break
case 3:
self.maplatView!.clearLine()
self.maplatView!.clearMarker()
break
case 4:
self.maplatView!.setViewpointWithLatitude(39.69994722, longitude: 141.1501111)
break
case 5:
if self.nowDirection == 0 {
nextDirection = -90
button.setTitle("南を上", for: .normal)
} else if self.nowDirection == -90 {
nextDirection = 180
button.setTitle("西を上", for: .normal)
} else if self.nowDirection == 180 {
nextDirection = 90
button.setTitle("北を上", for: .normal)
} else {
nextDirection = 0
button.setTitle("東を上", for: .normal)
}
self.maplatView!.setDirection(nextDirection)
self.nowDirection = nextDirection
break
case 6:
if self.nowRotation == 0 {
nextRotation = -90
button.setTitle("下を上", for: .normal)
} else if self.nowRotation == -90 {
nextRotation = 180
button.setTitle("左を上", for: .normal)
} else if self.nowRotation == 180 {
nextRotation = 90
button.setTitle("上を上", for: .normal)
} else {
nextRotation = 0
button.setTitle("右を上", for: .normal)
}
self.maplatView!.setRotation(nextRotation)
self.nowRotation = nextRotation
break
case 7:
self.maplatView!.currentMapInfo({ (value: [String: Any]?) -> () in
if let value = value, let jsonData = try? JSONSerialization.data(withJSONObject: value, options: []) {
let text = String(data: jsonData, encoding: .utf8)!
self.toast(text)
}
})
break
default:
break;
}
}
// トースト
func toast(_ message: String) {
var alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
var duration = 1
// duration in seconds
self.present(alert, animated: true, completion: {
let deadlineTime = DispatchTime.now() + DispatchTimeInterval.seconds(duration)
DispatchQueue.main.asyncAfter(deadline: deadlineTime) {
alert.dismiss(animated: true, completion: nil)
}
})
}
}
extension UIView {
func firstAvailableUIViewController() -> UIViewController? {
// convenience function for casting and to "mask" the recursive function
return (self.traverseResponderChainForUIViewController() as? UIViewController)
}
func traverseResponderChainForUIViewController() -> Any? {
if let nextResponder = self.next {
if (nextResponder.isKind(of: UIViewController.self)) {
return nextResponder
} else if (nextResponder.isKind(of: UIView.self)) {
return (nextResponder as! UIView).traverseResponderChainForUIViewController()
}
}
return nil
}
}
| 37.3 | 226 | 0.577748 |
f9f7c0d0f08f17e331a88693d8a33ed28b1f92f5 | 1,076 | //
// SettingViewController.swift
// catacomb2018
//
// Created by xyu on 09/05/2018.
// Copyright © 2018 xyu. All rights reserved.
//
import UIKit
class SettingViewController: UIViewController{
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
addBackground()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func addBackground() {
let width = UIScreen.main.bounds.size.width
let height = UIScreen.main.bounds.size.height
let imageViewBackground = UIImageView(frame: CGRect(x:0, y:0, width: width, height: height))
imageViewBackground.image = UIImage(named: "bg_heart.png")
// you can change the content mode:
imageViewBackground.contentMode = UIViewContentMode.scaleAspectFill
self.view.addSubview(imageViewBackground)
self.view.sendSubview(toBack: imageViewBackground)
}
}
| 27.589744 | 100 | 0.663569 |
03888cc457abd782229d5c1d6d5b617354e985d1 | 5,425 | //
// TableViewController.swift
// MLNetworkService
//
// Created by apple on 2021/5/8.
//
import UIKit
class TableViewController: UITableViewController {
lazy var taskList: [TaskItem] = {
return [
TaskItem(name: "任务1", task: try! service.addDownloadTask(url: URL(string: "https://dl.motrix.app/release/Motrix-1.5.15.dmg")!, completion: { (result) in
switch result {
case .success(let result):
print(result)
case .failure(let err):
print(err)
}
})),
TaskItem(name: "任务2", task: try! service.addDownloadTask(url: URL(string: "https://dl.motrix.app/release/Motrix-1.5.15.dmg")!)),
TaskItem(name: "任务3", task: try! service.addDownloadTask(url: URL(string: "https://download.jetbrains.com.cn/idea/ideaIU-2021.1.1.dmg")!)),
TaskItem(name: "任务4", task: try! service.addDownloadTask(url: URL(string: "https://download.jetbrains.com.cn/idea/ideaIU-2021.1.1.dmg")!)),
]
}()
lazy var service = MLNetworkService()
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return taskList.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let identifier = "TaskTableViewCell"
let cell = tableView.dequeueReusableCell(withIdentifier: identifier) as! TaskTableViewCell
let item = taskList[indexPath.row]
var task = item.task
func changeButtonTitle(state: MLNetworkTaskState) {
DispatchQueue.main.async {
let title: String
switch state {
case .ready:
title = "等待下载中"
case .running:
title = "正在下载"
case .suspend:
title = "已暂停"
case .cancel:
title = "已取消"
case .completed:
title = "已完成"
}
cell.actionBtn.setTitle(title, for: .normal)
}
}
task.progress = {
(bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) in
DispatchQueue.main.async {
cell.downloadSpeedLabel?.text = "\(bytesWritten / 1024) kB"
cell.progressView.progress = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)
}
}
task.didChangeState = {
changeButtonTitle(state: $0)
}
cell.didChangeDownloadState = {
switch task.state {
case .ready: fallthrough
case .running:
try? task.suspend()
case .suspend:
try? task.resume()
case .cancel: break
case .completed:break
}
}
cell.nameLabel?.text = item.name
changeButtonTitle(state: task.state)
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
| 36.166667 | 164 | 0.596313 |
9b96878f26e068a8da1e29942bc90a1a55991037 | 734 | //
// SettingController.swift
// Chromatic
//
// Created by Lakr Aream on 2021/8/29.
// Copyright © 2021 Lakr Aream. All rights reserved.
//
import UIKit
class SettingController: UIViewController {
let setting = SettingView()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(light: .systemGray6, dark: .black)
title = NSLocalizedString("SETTING", comment: "Setting")
view.addSubview(setting)
setting.snp.makeConstraints { x in
x.edges.equalToSuperview()
}
setting.updateContentSize()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
setting.updateContentSize()
}
}
| 22.9375 | 73 | 0.651226 |
ac16ecad8cbd9cdbd950cb8052530e7995c27754 | 4,873 | //
// tweetsDetailsViewController.swift
// TwitterDemo
//
// Created by Sarah Gemperle on 2/19/17.
// Copyright © 2017 Sarah Gemperle. All rights reserved.
//
import UIKit
class tweetsDetailsViewController: UIViewController {
@IBOutlet weak var viewContainer: UIView!
@IBOutlet weak var profileImageView: UIImageView!
@IBOutlet weak var handleLabel: UILabel!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var tweetLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var favImageView: UIImageView!
@IBOutlet weak var numRetweetsLabel: UILabel!
@IBOutlet weak var numFavsLabel: UILabel!
@IBOutlet weak var replyImageView: UIImageView!
@IBOutlet weak var retweetImageView: UIImageView!
var tweet: Tweet?
var retweetCount: Int = 0
var favoriteCount: Int = 0
override func viewDidLoad() {
super.viewDidLoad()
let retweetTapRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(TableViewCell.onRetweetTap))
let favoriteTapRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(TableViewCell.onFavoriteTap))
self.retweetImageView.addGestureRecognizer(retweetTapRecognizer)
self.favImageView.addGestureRecognizer(favoriteTapRecognizer)
ProfileViewController.currUser = tweet!.tweeter!
retweetCount = tweet!.retweet
favoriteCount = tweet!.favorites
if tweet != nil {
setup()
}
}
func setup() {
profileImageView.layer.cornerRadius = 6
profileImageView.setImageWith(tweet!.tweeter!.profileURL!)
nameLabel.text = tweet!.tweeter!.name as String?
handleLabel.text = tweet!.tweeter!.screenName as String?
numRetweetsLabel.text = "\(tweet!.retweet)"
numFavsLabel.text = "\(tweet!.favorites)"
dateLabel.text = tweet!.dateTweeted
tweetLabel.text = tweet!.tweetText!
profileImageView.layer.cornerRadius = 5
if(tweet!.isFavorited) {
favImageView.image = #imageLiteral(resourceName: "favor-icon-red")
} else {
favImageView.image = #imageLiteral(resourceName: "favor-icon")
}
if(tweet!.isRetweeted) {
retweetImageView.image = #imageLiteral(resourceName: "retweet-icon-green")
} else {
retweetImageView.image = #imageLiteral(resourceName: "retweet-icon")
}
replyImageView.image = #imageLiteral(resourceName: "reply-icon")
}
func refreshTweetStatus() {
if tweet!.isFavorited {
favImageView.image = #imageLiteral(resourceName: "favor-icon-red")
} else {
favImageView.image = #imageLiteral(resourceName: "favor-icon")
}
numFavsLabel.text = "\(favoriteCount)"
if tweet!.isRetweeted {
retweetImageView.image = #imageLiteral(resourceName: "retweet-icon-green")
} else {
retweetImageView.image = #imageLiteral(resourceName: "retweet-icon")
}
numRetweetsLabel.text = "\(retweetCount)"
}
@IBAction func profImageTapped(_ sender: AnyObject) {
ProfileViewController.currUser = User.currentUser
performSegue(withIdentifier: "ProfileSegue", sender: self)
}
func onRetweetTap() {
if tweet!.isRetweeted {
return
}
let client = TwitterClient.sharedInstance!
client.retweet(currTweet: self.tweet!, success: { (int: Int) in
self.retweetCount = int
self.tweet?.isRetweeted = true
self.refreshTweetStatus()
}) { (error: Error?) in
print("Error retweeting: \(error)")
}
}
func onFavoriteTap() {
if tweet!.isFavorited {
return
}
let client = TwitterClient.sharedInstance!
client.favorite(currTweet: self.tweet!, success: { (int: Int) in
self.favoriteCount = int
self.tweet?.isFavorited = true
self.refreshTweetStatus()
}) { (error: Error?) in
print("Error favoriting: \(error)")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 32.925676 | 144 | 0.625487 |
1c54692cb500643fb6f7d4bebf0868e436ee0fa5 | 775 | //
// TwilioVerifyConfig.swift
// TwilioVerify
//
// Copyright © 2020 Twilio.
//
// 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.
//
let version = "1.2.0"
let bundleName = "TwilioVerify"
let bundleVersion = "1"
let baseURL = "https://verify.twilio.com/v2/"
| 32.291667 | 76 | 0.71871 |
ff2c7f4534e7efcd24593586d6d77ba645f6010c | 4,302 | //
// DetailController.swift
// Marvel Heroes
//
// Created by Thiago Vaz on 03/06/20.
// Copyright © 2020 Thiago Santos. All rights reserved.
//
import UIKit
import Hero
import LBTATools
func + (left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x + right.x, y: left.y + right.y)
}
class DetailController: CollectionViewController {
var presenter: DetailPresenterInput!
var idHero: String = ""
let backgroundImageView: UIImageView = {
let imageView = UIImageView(image: UIImage(named: "spider-man"))
imageView.contentMode = .scaleAspectFill
return imageView
}()
let navigationBar = UIView(frame: .zero)
let backButton = UIButton(image: UIImage(named: "back")!, tintColor: .white, target: self, action: #selector(didTap(_:)))
var panGR: UIPanGestureRecognizer!
override func viewDidLoad() {
super.viewDidLoad()
presenter.viewDidLoad()
setupLayout()
}
fileprivate func setupLayout() {
self.hero.isEnabled = true
self.view.hero.modifiers = [.cascade]
view.backgroundColor = .black
collectionView.backgroundColor = .black
backgroundImageView.hero.id = idHero
backgroundImageView.hero.isEnabled = true
panGR = UIPanGestureRecognizer(target: self,
action: #selector(handlePan(gestureRecognizer:)))
view.addGestureRecognizer(panGR)
navigationBar.backgroundColor = .black
navigationBar.translatesAutoresizingMaskIntoConstraints = false
backButton.backgroundColor = .clear
backButton.translatesAutoresizingMaskIntoConstraints = false
navigationBar.addSubview(backButton)
view.addSubview(navigationBar)
NSLayoutConstraint.activate( [
navigationBar.topAnchor.constraint(equalTo: view.topAnchor),
navigationBar.leadingAnchor.constraint(equalTo: view.leadingAnchor),
navigationBar.trailingAnchor.constraint(equalTo: view.trailingAnchor),
navigationBar.heightAnchor.constraint(equalToConstant: 90),
backButton.leadingAnchor.constraint(equalTo: navigationBar.leadingAnchor, constant: 24),
backButton.topAnchor.constraint(equalTo: navigationBar.topAnchor, constant: 40),
backButton.widthAnchor.constraint(equalToConstant: 30),
backButton.heightAnchor.constraint(equalToConstant: 44)
]
)
}
@objc func didTap(_ sender: Any?){
presenter.didTap()
}
@objc func handlePan(gestureRecognizer:UIPanGestureRecognizer) {
let translation = panGR.translation(in: nil)
let progress = translation.y / 2 / view.bounds.height
switch panGR.state {
case .began:
guard translation.y > 0 else {
return
}
dismiss(animated: true, completion: nil)
case .changed:
Hero.shared.update(progress)
default:
if progress + panGR.velocity(in: nil).y / view.bounds.height > 0.3 {
Hero.shared.finish()
} else {
Hero.shared.cancel()
}
}
}
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
let denominator: CGFloat = 50 //your offset treshold
let alpha = min(1, scrollView.contentOffset.y / denominator)
self.setNavbar(backgroundColorAlpha: alpha)
}
private func setNavbar(backgroundColorAlpha alpha: CGFloat) {
let newColor = UIColor(red: 0, green: 0, blue: 0, alpha: alpha) //your color
navigationBar.backgroundColor = newColor
}
}
extension DetailController: DetailPresenterOuput {
func loadView(sections: [Sections]) {
self.sections = sections
collectionView.reloadData()
}
func showBackgroundView(idHero: String, image: String) {
collectionView.backgroundView = backgroundImageView
backgroundImageView.image = UIImage(named: image)
backgroundImageView.hero.id = idHero
let gradientView = GradientView(frame: collectionView.frame)
collectionView.backgroundView?.addSubview(gradientView)
}
}
| 34.416 | 125 | 0.643654 |
5d82aab11426dd98d90bd6a413cfff215c630c75 | 253 | //
// MovieGridCell.swift
// Flix
//
// Created by B34ST9 on 9/23/19.
// Copyright © 2019 Santiago Bruno. All rights reserved.
//
import UIKit
class MovieGridCell: UICollectionViewCell {
@IBOutlet weak var posterView: UIImageView!
}
| 15.8125 | 57 | 0.679842 |
39f4dc0624f296761bf38248c8bb4614047227c4 | 492 | //
// ReportMessageSchema.swift
// Niceter
//
// Created by uuttff8 on 4/9/20.
// Copyright © 2020 Anton Kuzmin. All rights reserved.
//
import Foundation
@frozen
public struct ReportMessageSchema: Codable {
let id: String
let sent: String
let weight: Int
let reporterUserId: String
let reporterUser: UserSchema
let messageId: String
let messageUserId: String
let messageUser: UserSchema
let messageText: String
let message: RoomRecreateSchema
}
| 20.5 | 55 | 0.711382 |
395b7922d87470a282d5a0d49ea0bb198352b7a1 | 2,666 | //
// Created by Daniel Heredia on 2/27/18.
// Copyright © 2018 Daniel Heredia. All rights reserved.
//
// T9
import Foundation
extension String {
subscript(i: Int) -> Character {
get {
let index = self.index(self.startIndex, offsetBy: i)
return self[index]
}
}
var isNumber: Bool {
return !self.isEmpty && self.rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) == nil
}
}
// MARK: - Precompute data
let t9Letters: [[Character]] = [
[], //0
[], //1
["a", "b", "c"], //2
["d", "e", "f"], //3
["g", "h", "i"], //4
["j", "k", "l"], //5
["m", "n", "o"], //6
["p", "q", "r", "s"], //7
["t", "u", "v"], //8
["w", "x", "y", "z"] //9
]
func createCharToNumberDictionary() -> [Character: Character] {
var dictionary = [Character: Character]()
for i in 0..<t9Letters.count {
let number = "\(i)"[0]
let numberLetters = t9Letters[i]
for letter in numberLetters {
dictionary[letter] = number
}
}
return dictionary
}
func convertToNumber(word: String, charDictionary: [Character: Character]) -> String {
var number = ""
for character in word {
if let digit = charDictionary[character] {
number.append(digit)
} else {
preconditionFailure()
}
}
return number
}
func createT9Dictionary(words: [String]) -> [String: [String]] {
let charDictionary = createCharToNumberDictionary()
var numbersDictionary = [String: [String]]()
for word in words {
let number = convertToNumber(word: word, charDictionary: charDictionary)
if numbersDictionary[number] == nil {
numbersDictionary[number] = [word]
} else {
numbersDictionary[number]!.append(word)
}
}
return numbersDictionary
}
// MARK: - Look up number
func getWords(forNumber number: String, t9Dictionary: [String: [String]]) -> [String]? {
precondition(number.isNumber)
return t9Dictionary[number]
}
// MARK: - Test
let words = ["dog", "doh", "cat", "fridge"]
let t9Dictionary = createT9Dictionary(words: words)
let number = "364"
print("Words for number \(number):")
if let words = getWords(forNumber: number, t9Dictionary: t9Dictionary) {
print(words)
} else {
print("(None)")
}
| 28.666667 | 103 | 0.511253 |
f47818680b85502947ed1f6ef594f6c007f17abe | 2,368 | // Copyright SIX DAY LLC. All rights reserved.
import Foundation
import Result
import TrustKeystore
import TrustCore
protocol Keystore {
var hasWallets: Bool { get }
var wallets: [Wallet] { get }
var keysDirectory: URL { get }
var recentlyUsedWallet: Wallet? { get set }
static var current: Wallet? { get }
@available(iOS 10.0, *)
func createAccount(with password: String, completion: @escaping (Result<Account, KeystoreError>) -> Void)
func create12wordsAccount(with password: String) -> Account
func importWallet(type: ImportType, completion: @escaping (Result<Wallet, KeystoreError>) -> Void)
func keystore(for privateKey: String, password: String, completion: @escaping (Result<String, KeystoreError>) -> Void)
func importKeystore(value: String, password: String, newPassword: String, completion: @escaping (Result<Account, KeystoreError>) -> Void)
func createAccout(password: String) -> Account
func importKeystore(value: String, password: String, newPassword: String) -> Result<Account, KeystoreError>
func export(account: Account, password: String, newPassword: String) -> Result<String, KeystoreError>
func export(account: Account, password: String, newPassword: String, completion: @escaping (Result<String, KeystoreError>) -> Void)
func exportData(account: Account, password: String, newPassword: String) -> Result<Data, KeystoreError>
func exportPrivateKey(account: Account) -> Result<Data, KeystoreError>
func exportMnemonics(account: Account) -> Result<String, KeystoreError>
func delete(wallet: Wallet) -> Result<Void, KeystoreError>
func delete(wallet: Wallet, completion: @escaping (Result<Void, KeystoreError>) -> Void)
func updateAccount(account: Account, password: String, newPassword: String) -> Result<Void, KeystoreError>
func signPersonalMessage(_ data: Data, for account: Account) -> Result<Data, KeystoreError>
func signMessage(_ data: Data, for account: Account) -> Result<Data, KeystoreError>
func signHash(_ hash: Data, for account: Account) -> Result<Data, KeystoreError>
func signTransaction(_ signTransaction: SignTransaction) -> Result<Data, KeystoreError>
func getPassword(for account: Account) -> String?
func convertPrivateKeyToKeystoreFile(privateKey: String, passphrase: String) -> Result<[String: Any], KeystoreError>
}
| 64 | 141 | 0.742399 |
fb6a8bc59095ad0dcb84e3002a137111260fa313 | 5,847 | /**
* Copyright (c) 2016 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 WatchKit
import WatchConnectivity
import CoreMotion
// WatchConnectivity requires NSObject
class PedometerData: NSObject, WCSessionDelegate {
let pedometer = CMPedometer()
// sample pedometer data: set these two properties to zero
var totalSteps = 0
var totalDistance: CGFloat = 0.0
var steps = 0
var distance: CGFloat = 0.0
var prevTotalSteps = 0
var prevTotalDistance: CGFloat = 0.0
let distanceUnit = Locale.current.usesMetricSystem ? "km" : "mi"
var appStartDate: Date!
var startOfDay: Date!
var endOfDay: Date!
let calendar = Calendar()
var session: WCSession?
override init() {
super.init()
if (WCSession.isSupported()) {
session = WCSession.default
session!.delegate = self
session!.activate()
}
setStartAndEndOfDay()
if !loadSavedData() {
appStartDate = startOfDay
saveData()
startLiveUpdates()
}
}
func setStartAndEndOfDay() {
startOfDay = calendar.startOfToday as Date!
endOfDay = calendar.startOfNextDay(startOfDay)
}
// MARK: Pedometer Data
enum PedometerDataType { case live, history }
func updateProperties(from data: CMPedometerData, ofType type: PedometerDataType) {
switch type {
case .live: // 1
totalSteps = data.numberOfSteps.intValue
steps = totalSteps - prevTotalSteps
if let rawDistance = data.distance?.intValue, rawDistance > 0 {
totalDistance = CGFloat(rawDistance) / 1000.0
distance = totalDistance - prevTotalDistance
}
case .history: // 2
steps = data.numberOfSteps.intValue
totalSteps = steps + prevTotalSteps
if let rawDistance = data.distance?.intValue, rawDistance > 0 {
distance = CGFloat(rawDistance) / 1000.0
totalDistance = distance + prevTotalDistance
}
}
}
func startLiveUpdates() {
guard CMPedometer.isStepCountingAvailable() else { return }
pedometer.startUpdates(from: appStartDate) { data, error in
if let data = data {
// 1
if self.calendar.isDate(data.endDate, afterDate: self.endOfDay) {
// 2
self.pedometer.stopUpdates()
// 3
self.queryHistory(from: self.startOfDay, to: self.endOfDay)
return
}
self.updateProperties(from: data, ofType: .live)
self.sendData(false)
}
}
}
func queryHistory(from start: Date, to end: Date) {
guard CMPedometer.isStepCountingAvailable() else {
return
}
pedometer.queryPedometerData(from: start, to: end) { data, error in
if let data = data {
self.updateProperties(from: data, ofType: .history)
self.sendData(true)
// update and save day-dependent properties
self.setStartAndEndOfDay()
self.prevTotalSteps = self.totalSteps
self.prevTotalDistance = self.totalDistance
self.saveData()
self.startLiveUpdates()
}
}
}
// MARK: - Watch Connectivity
func sendData(_ dayEnded: Bool) {
guard let session = session else {
return
}
let applicationDict: [String : Any] = ["dayEnded": dayEnded, "steps":steps,
"distance":distance, "totalSteps": totalSteps,
"totalDistance": totalDistance]
session.transferUserInfo(applicationDict)
}
// WCSessionDelegate method
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
}
// MARK: - Data Persistence
func saveData() {
UserDefaults.standard.set(appStartDate, forKey: "appStartDate")
UserDefaults.standard.set(startOfDay, forKey: "startOfDay")
UserDefaults.standard.set(endOfDay, forKey: "endOfDay")
UserDefaults.standard.set(prevTotalSteps, forKey: "prevTotalSteps")
UserDefaults.standard.set(prevTotalDistance, forKey: "prevTotalDistance")
}
func loadSavedData() -> Bool {
guard let savedAppStartDate = UserDefaults.standard.object(forKey: "appStartDate") as? Date else {
return false
}
appStartDate = savedAppStartDate
let savedStartOfDay = UserDefaults.standard.object(forKey: "startOfDay") as! Date
let savedEndOfDay = UserDefaults.standard.object(forKey: "endOfDay") as! Date
if calendar.isDate(calendar.now, afterDate: savedEndOfDay) {
// query history to finalize data for missing day
queryHistory(from: savedStartOfDay, to: savedEndOfDay)
} else {
prevTotalSteps = UserDefaults.standard.object(forKey: "prevTotalSteps") as! Int
prevTotalDistance = UserDefaults.standard.object(forKey: "prevTotalDistance") as! CGFloat
startLiveUpdates()
}
return true
}
}
| 33.033898 | 122 | 0.688387 |
e9d7e79b49efa30980f5ed241bd8d8cbea2b56ef | 1,758 | //
// AppDelegate.swift
// MLRealityTest
//
// Created by Zheng on 4/2/21.
//
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
}
| 42.878049 | 285 | 0.751991 |
76c71edab02ee0912af7db1caa9a6b91f4378b7e | 553 | //
// Images.swift
// WeTrade
//
// Created by Felipe Joglar on 8/4/22.
//
import Foundation
struct Images {
let logo = "logo"
let welcomeBackground = "welcomeBackground"
let loginBackground = "loginBackground"
let homeAlk = "homeAlk"
let homeBa = "homeBa"
let homeCcl = "homeCcl"
let homeDal = "homeDal"
let homeEadsy = "homeEadsy"
let homeExp = "homeExp"
let homeIllos = "homeIllos"
let homeJblu = "homeJblu"
let homeMar = "homeMar"
let homeRcl = "homeRcl"
let homeTrvl = "homeTrvl"
}
| 20.481481 | 47 | 0.63472 |
d66a4b50be1e4fd6087c7ed6cac5546501541ad4 | 3,709 | //
// AVLTree.swift
// XLLKit_Example
//
// Created by XL ZZCM on 2019/9/17.
// Copyright © 2019 CocoaPods. All rights reserved.
//
import Foundation
class AVLTree: BalanceBinarySearchTree {
override func createNode(_ element: Int, _ parent: TreeNode? = nil) -> TreeNode {
return AVLNode(element, parent)
}
override func afterAdd(_ node: TreeNode) {
var cur: TreeNode? = node.parent
while cur != nil {
if isBalanced(cur!) { // 如果是平衡,就更新一下高度
updateHeight(cur!)
} else { // 如果不平衡,需要恢复平衡
// reBalanceOfRotate(cur!)
reBalance(cur!)
break
}
cur = cur?.parent
}
}
override func afterRemove(_ node: TreeNode) {
var cur: TreeNode? = node.parent
while cur != nil {
if isBalanced(cur!) { // 如果是平衡,就更新一下高度
updateHeight(cur!)
} else { // 如果不平衡,需要恢复平衡
reBalanceOfRotate(cur!)
// reBalance(cur!)
}
cur = cur?.parent
}
}
override func afterRotate(_ grand: TreeNode?, _ parent: TreeNode?, _ child: TreeNode?) {
super.afterRotate(grand, parent, child)
// 更新高度
if grand != nil {
updateHeight(grand!)
}
if parent != nil {
updateHeight(parent!)
}
}
override func rotate(_ r: TreeNode?, _ a: TreeNode?, _ b: TreeNode?, _ c: TreeNode?, _ d: TreeNode?, _ e: TreeNode?, _ f: TreeNode?, _ g: TreeNode?) {
super.rotate(r, a, b, c, d, e, f, g)
// 更新高度
updateHeight(b!)
updateHeight(f!)
updateHeight(d!)
}
}
extension AVLTree {
private func isBalanced(_ node: TreeNode) -> Bool {
return abs((node as! AVLNode).balanceFactor()) <= 1 ? true : false
}
private func updateHeight(_ node: TreeNode) {
(node as! AVLNode).updateHeight()
}
}
extension AVLTree {
// MARK: - 恢复平衡方法1
/// 恢复平衡1
private func reBalanceOfRotate(_ grand: TreeNode) {
let parent = (grand as! AVLNode).tallerChildNode()
let child = parent?.tallerChildNode()
if parent?.isLeftChild ?? false {
if child?.isLeftChild ?? false { // LL:grand 右旋
rightRotate(grand)
} else { // LR:parent 先左旋,grand 再右旋
leftRotate(parent)
rightRotate(grand)
}
} else {
if child?.isRightChild ?? false { // RR:grand 左旋
leftRotate(grand)
} else { // RL:parent 先右旋,grand 再左旋
rightRotate(parent)
leftRotate(grand)
}
}
}
// MARK: - 恢复平衡方法2
/// 恢复平衡2
private func reBalance(_ grand: TreeNode) {
let parent = (grand as! AVLNode).tallerChildNode()
let child = parent?.tallerChildNode()
if parent?.isLeftChild ?? false {
if child?.isLeftChild ?? false { // LL:grand 右旋
rotate(grand, child?.left, child, child?.right, parent, parent?.right, grand, grand.right)
} else { // LR:parent 先左旋,grand 再右旋
rotate(grand, parent?.left, parent, child?.left, child, child?.right, grand, grand.right)
}
} else {
if child?.isRightChild ?? false { // RR:grand 左旋
rotate(grand, grand.left, grand, parent?.left, parent, child?.left, child, child?.right)
} else { // RL:parent 先右旋,grand 再左旋
rotate(grand, grand.left, grand, child?.left, child, child?.right, parent, parent?.right)
}
}
}
}
| 29.672 | 154 | 0.52413 |
1871f100cbb92957ea9a06310081937af897d85d | 374 | @testable import VinylShop
import Nimble
import Quick
class ShoppingBarViewSpec: QuickSpec {
override func spec() {
describe("ShoppingBarView") {
describe("required initializer") {
it("should return nil") {
expect(ShoppingBarView(coder: NSCoder())).to(beNil())
}
}
}
}
}
| 20.777778 | 73 | 0.540107 |
9b946c300c8e2660231df96789f2c5deb7b81169 | 6,285 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Hummingbird server framework project
//
// Copyright (c) 2021-2021 the Hummingbird authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See hummingbird/CONTRIBUTORS.txt for the list of Hummingbird authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import ExtrasBase64
import Hummingbird
import HummingbirdWSCore
import NIOCore
import NIOPosix
import NIOSSL
import NIOWebSocket
/// Manages WebSocket client creation
public enum HBWebSocketClient {
/// Connect to WebSocket
/// - Parameters:
/// - url: URL of websocket
/// - configuration: Configuration of connection
/// - eventLoop: eventLoop to run connection on
/// - Returns: EventLoopFuture which will be fulfilled with `HBWebSocket` once connection is made
public static func connect(url: HBURL, configuration: Configuration, on eventLoop: EventLoop) -> EventLoopFuture<HBWebSocket> {
let wsPromise = eventLoop.makePromise(of: HBWebSocket.self)
do {
let url = try SplitURL(url: url)
let bootstrap = try createBootstrap(url: url, configuration: configuration, on: eventLoop)
bootstrap
.channelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
.channelOption(ChannelOptions.socket(IPPROTO_TCP, TCP_NODELAY), value: 1)
.channelInitializer { channel in
return Self.setupChannelForWebsockets(url: url, channel: channel, wsPromise: wsPromise, on: eventLoop)
}
.connect(host: url.host, port: url.port)
.cascadeFailure(to: wsPromise)
} catch {
wsPromise.fail(error)
}
return wsPromise.futureResult
}
/// create bootstrap
static func createBootstrap(url: SplitURL, configuration: Configuration, on eventLoop: EventLoop) throws -> NIOClientTCPBootstrap {
if let clientBootstrap = ClientBootstrap(validatingGroup: eventLoop) {
let sslContext = try NIOSSLContext(configuration: configuration.tlsConfiguration)
let tlsProvider = try NIOSSLClientTLSProvider<ClientBootstrap>(context: sslContext, serverHostname: url.host)
let bootstrap = NIOClientTCPBootstrap(clientBootstrap, tls: tlsProvider)
if url.tlsRequired {
bootstrap.enableTLS()
}
return bootstrap
}
preconditionFailure("Failed to create web socket bootstrap")
}
/// setup for channel for websocket. Create initial HTTP request and include upgrade for when it is successful
static func setupChannelForWebsockets(
url: SplitURL,
channel: Channel,
wsPromise: EventLoopPromise<HBWebSocket>,
on eventLoop: EventLoop
) -> EventLoopFuture<Void> {
let upgradePromise = eventLoop.makePromise(of: Void.self)
upgradePromise.futureResult.cascadeFailure(to: wsPromise)
// initial HTTP request handler, before upgrade
let httpHandler: WebSocketInitialRequestHandler
do {
httpHandler = try WebSocketInitialRequestHandler(
url: url,
upgradePromise: upgradePromise
)
} catch {
upgradePromise.fail(Error.invalidURL)
return upgradePromise.futureResult
}
// create random key for request key
let requestKey = (0..<16).map { _ in UInt8.random(in: .min ..< .max) }
let base64Key = String(base64Encoding: requestKey, options: [])
let websocketUpgrader = NIOWebSocketClientUpgrader(requestKey: base64Key) { channel, _ in
let webSocket = HBWebSocket(channel: channel, type: .client)
return channel.pipeline.addHandler(WebSocketHandler(webSocket: webSocket)).map { _ -> Void in
wsPromise.succeed(webSocket)
upgradePromise.succeed(())
}
}
let config: NIOHTTPClientUpgradeConfiguration = (
upgraders: [websocketUpgrader],
completionHandler: { _ in
channel.pipeline.removeHandler(httpHandler, promise: nil)
}
)
// add HTTP handler with web socket upgrade
return channel.pipeline.addHTTPClientHandlers(withClientUpgrade: config).flatMap {
channel.pipeline.addHandler(httpHandler)
}
}
/// Possible Errors returned by websocket connection
public enum Error: Swift.Error {
case invalidURL
case websocketUpgradeFailed
}
/// WebSocket connection configuration
public struct Configuration {
/// TLS setup
let tlsConfiguration: TLSConfiguration
/// initialize Configuration
public init(
tlsConfiguration: TLSConfiguration = TLSConfiguration.makeClientConfiguration()
) {
self.tlsConfiguration = tlsConfiguration
}
}
/// Processed URL split into sections we need for connection
struct SplitURL {
let host: String
let pathQuery: String
let port: Int
let tlsRequired: Bool
init(url: HBURL) throws {
guard let host = url.host else { throw HBWebSocketClient.Error.invalidURL }
self.host = host
if let port = url.port {
self.port = port
} else {
if url.scheme == .https || url.scheme == .wss {
self.port = 443
} else {
self.port = 80
}
}
self.tlsRequired = url.scheme == .https || url.scheme == .wss ? true : false
self.pathQuery = url.path + (url.query.map { "?\($0)" } ?? "")
}
/// return "Host" header value. Only include port if it is different from the default port for the request
var hostHeader: String {
if (self.tlsRequired && self.port != 443) || (!self.tlsRequired && self.port != 80) {
return "\(self.host):\(self.port)"
}
return self.host
}
}
}
| 38.796296 | 135 | 0.608751 |
e4734436cecebd975071e20372d23059d6935542 | 493 | //
// Combine.swift
// LucidTestKit
//
// Created by Théophane Rupin on 11/5/20.
// Copyright © 2020 Scribd. All rights reserved.
//
import Foundation
#if !LUCID_REACTIVE_KIT
import Combine
public extension Future {
convenience init(just output: Output) {
self.init { fulfill in
fulfill(.success(output))
}
}
convenience init(failed error: Failure) {
self.init { fulfill in
fulfill(.failure(error))
}
}
}
#endif
| 17 | 49 | 0.612576 |
fc80c7c3486d3f5914203cc14ef5a548a628ab2c | 14,075 | //
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
//
import UIKit
// MARK: LargeTitleView
/// Large Header and custom profile button container
class LargeTitleView: UIView {
enum Style: Int {
case light, dark
}
private struct Constants {
static let horizontalSpacing: CGFloat = 10
static let compactAvatarSize: MSFAvatarSize = .small
static let avatarSize: MSFAvatarSize = .medium
// Once we are iOS 14 minimum, we can use Fonts.largeTitle.withSize() function instead
static let compactTitleFont = UIFont.systemFont(ofSize: 26, weight: .bold)
static let titleFont = UIFont.systemFont(ofSize: 30, weight: .bold)
}
var personaData: Persona? {
didSet {
updateProfileButtonVisibility()
if let avatarState = avatar?.state {
avatarState.primaryText = personaData?.name
avatarState.secondaryText = personaData?.email
avatarState.image = personaData?.image
avatarState.imageBasedRingColor = personaData?.imageBasedRingColor
avatarState.hasRingInnerGap = personaData?.hasRingInnerGap ?? true
avatarState.isRingVisible = personaData?.isRingVisible ?? false
avatarState.presence = personaData?.presence ?? .none
avatarState.isOutOfOffice = personaData?.isOutOfOffice ?? false
let color = personaData?.color
avatarState.backgroundColor = color
avatarState.ringColor = color
}
}
}
var avatarSize: NavigationBar.ElementSize = .automatic {
didSet {
switch avatarSize {
case .automatic:
return
case .contracted:
avatar?.state.size = Constants.compactAvatarSize
case .expanded:
avatar?.state.size = Constants.avatarSize
}
}
}
var avatarHeightConstraint: NSLayoutConstraint?
var avatarWidthConstraint: NSLayoutConstraint?
var avatarAccessibilityLabel: String? {
return avatarCustomAccessibilityLabel ?? "Accessibility.LargeTitle.ProfileView".localized
}
var avatarCustomAccessibilityLabel: String? {
didSet {
updateAvatarAccessibility()
}
}
var avatarOverrideStyle: MSFAvatarStyle? {
didSet {
if let style = avatarOverrideStyle {
updateProfileButtonVisibility()
avatar?.state.style = style
}
}
}
var style: Style = .light {
didSet {
titleButton.setTitleColor(colorForStyle, for: .normal)
avatar?.state.style = style == .light ? .default : .accent
}
}
var titleSize: NavigationBar.ElementSize = .automatic {
didSet {
switch titleSize {
case .automatic:
return
case .contracted:
titleButton.titleLabel?.font = Constants.compactTitleFont
case .expanded:
titleButton.titleLabel?.font = Constants.titleFont
}
}
}
var onAvatarTapped: (() -> Void)? { // called in response to a tap on the MSFAvatar's view
didSet {
updateAvatarViewPointerInteraction()
updateAvatarAccessibility()
}
}
public func visibleAvatarView() -> UIView? {
if !showsProfileButton {
return nil
}
return avatar?.view
}
private var colorForStyle: UIColor {
switch style {
case .light:
return Colors.Navigation.Primary.title
case .dark:
return Colors.Navigation.System.title
}
}
private var avatar: MSFAvatar? // circular view displaying the profile information
private let titleButton = UIButton() // button used to display the title of the current navigation item
private let contentStackView = UIStackView() // containing stack view
private let tapGesture = UITapGestureRecognizer() // tap used to trigger expansion. Applied to entire navigation bar
private var showsProfileButton: Bool = true { // whether to display the customizable profile button
didSet {
avatar?.view.isHidden = !showsProfileButton
}
}
private var hasLeftBarButtonItems: Bool = false {
didSet {
updateProfileButtonVisibility()
}
}
private var respondsToTaps: Bool = true // whether to respond to the various tap gestures/actions that are incorproated into the navigation bar
override init(frame: CGRect) {
super.init(frame: frame)
initBase()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initBase()
}
/// Base function for initialization
private func initBase() {
setupLayout()
setupAccessibility()
}
// MARK: - Base Construction Methods
// Constructs various constants based on initial conditions
// Applies constants via autolayout to constructed views
// Also constructs gesture recognizers
private func setupLayout() {
// contentStackView layout
contentStackView.spacing = Constants.horizontalSpacing
contentStackView.alignment = .center
contain(view: contentStackView, withInsets: UIEdgeInsets(top: 0,
left: 8,
bottom: 0,
right: 8))
// Avatar setup
let preferredFallbackImageStyle: MSFAvatarStyle = style == .light ? .default : .accent
let avatar = MSFAvatar(style: preferredFallbackImageStyle,
size: Constants.avatarSize)
let avatarState = avatar.state
avatarState.primaryText = personaData?.name
avatarState.secondaryText = personaData?.email
avatarState.image = personaData?.image
if let color = personaData?.color {
avatarState.backgroundColor = color
avatarState.ringColor = color
}
self.avatar = avatar
let avatarView = avatar.view
avatarView.translatesAutoresizingMaskIntoConstraints = false
avatarView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleAvatarViewTapped)))
contentStackView.addArrangedSubview(avatarView)
avatarView.centerYAnchor.constraint(equalTo: contentStackView.centerYAnchor).isActive = true
let avatarHeightConstraint = NSLayoutConstraint(item: avatarView,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: Constants.avatarSize.size)
avatarView.addConstraint(avatarHeightConstraint)
avatarHeightConstraint.isActive = true
self.avatarHeightConstraint = avatarHeightConstraint
let avatarWidthConstraint = NSLayoutConstraint(item: avatarView,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: Constants.avatarSize.size)
avatarView.addConstraint(avatarWidthConstraint)
avatarWidthConstraint.isActive = true
self.avatarWidthConstraint = avatarWidthConstraint
// title button setup
contentStackView.addArrangedSubview(titleButton)
titleButton.setTitle(nil, for: .normal)
titleButton.titleLabel?.font = Constants.titleFont
titleButton.setTitleColor(colorForStyle, for: .normal)
titleButton.titleLabel?.textAlignment = .left
titleButton.contentHorizontalAlignment = .left
titleButton.titleLabel?.adjustsFontSizeToFitWidth = true
titleButton.addTarget(self, action: #selector(LargeTitleView.titleButtonTapped(sender:)), for: .touchUpInside)
titleButton.setContentCompressionResistancePriority(.required,
for: .horizontal)
// tap gesture for entire titleView
tapGesture.addTarget(self, action: #selector(LargeTitleView.handleTitleViewTapped(sender:)))
addGestureRecognizer(tapGesture)
titleButton.showsLargeContentViewer = true
updateAvatarViewPointerInteraction()
}
private func expansionAnimation() {
if titleSize == .automatic {
titleButton.titleLabel?.font = Constants.titleFont
}
if avatarSize == .automatic {
avatar?.state.size = Constants.avatarSize
avatarWidthConstraint?.constant = Constants.avatarSize.size
avatarHeightConstraint?.constant = Constants.avatarSize.size
}
layoutIfNeeded()
}
private func contractionAnimation() {
if titleSize == .automatic {
titleButton.titleLabel?.font = Constants.compactTitleFont
}
if avatarSize == .automatic {
avatar?.state.size = Constants.compactAvatarSize
avatarWidthConstraint?.constant = Constants.compactAvatarSize.size
avatarHeightConstraint?.constant = Constants.compactAvatarSize.size
}
layoutIfNeeded()
}
private func updateAvatarViewPointerInteraction() {
avatar?.state.hasPointerInteraction = onAvatarTapped != nil
}
private func updateAvatarAccessibility() {
if let avatar = avatar {
let accessibilityLabel = avatarAccessibilityLabel
let avatarState = avatar.state
avatarState.accessibilityLabel = accessibilityLabel
avatarState.hasButtonAccessibilityTrait = onAvatarTapped != nil
let avatarView = avatar.view
avatarView.showsLargeContentViewer = true
avatarView.largeContentTitle = accessibilityLabel
}
}
// MARK: - UIActions
/// Target for the tap gesture on the avatar view, as it is not a button
///
/// - Parameter gesture: tap gesture on the AvatarView
@objc private func handleAvatarViewTapped(gesture: UITapGestureRecognizer) {
onAvatarTapped?()
}
/// Target for the Title Button's touchUpInside
///
/// - Parameter sender: title button
@objc private func titleButtonTapped(sender: UIButton) {
guard respondsToTaps else {
return
}
requestExpansion()
}
/// Target for the NavigationBar tap gesture
///
/// - Parameter sender: the tap gesture
@objc private func handleTitleViewTapped(sender: UITapGestureRecognizer) {
guard respondsToTaps else {
return
}
requestExpansion()
}
/// Posts a notification requesting that the navigation bar be animated into its larger state
private func requestExpansion() {
NotificationCenter.default.post(name: .accessoryExpansionRequested, object: self)
}
// MARK: - Content Update Methods
private func updateProfileButtonVisibility() {
showsProfileButton = !hasLeftBarButtonItems && (personaData != nil || avatarOverrideStyle != nil)
}
/// Sets the interface with the provided item's details
///
/// - Parameter navigationItem: instance of UINavigationItem providing inteface information
func update(with navigationItem: UINavigationItem) {
hasLeftBarButtonItems = !(navigationItem.leftBarButtonItems?.isEmpty ?? true)
titleButton.setTitle(navigationItem.title, for: .normal)
}
// MARK: - Expansion/Contraction Methods
/// Calls the expansion animation block, optionally animated
///
/// - Parameter animated: to animate the block or not
func expand(animated: Bool) {
// Exit early if neither element's size is automatic
guard titleSize == .automatic || avatarSize == .automatic else {
return
}
if animated {
UIView.animate(withDuration: NavigationBar.expansionContractionAnimationDuration,
animations: expansionAnimation)
} else {
expansionAnimation()
}
}
/// Calls the contraction animation block, optionally animated
///
/// - Parameter animated: to animate the block or not
func contract(animated: Bool) {
// Exit early if neither element's size is automatic
guard titleSize == .automatic || avatarSize == .automatic else {
return
}
if animated {
UIView.animate(withDuration: NavigationBar.expansionContractionAnimationDuration,
animations: contractionAnimation)
} else {
contractionAnimation()
}
}
// MARK: - Accessibility
/// Updates various properties of the TitleView to properly conform to accessibility requirements
private func setupAccessibility() {
titleButton.accessibilityTraits = .header
// Sets the accessibility elements in the same order as they are laid you in the content view.
accessibilityElements = contentStackView.arrangedSubviews
updateAvatarAccessibility()
}
}
// MARK: - Notification.Name Declarations
extension NSNotification.Name {
static let accessoryExpansionRequested = Notification.Name("microsoft.fluentui.accessoryExpansionRequested")
}
| 36.089744 | 147 | 0.61286 |
89961d085bea91788d19022a6e7714bcb62a3249 | 654 | import XCTest
import Foundation
import Testing
import HTTP
@testable import Vapor
@testable import App
/// This file shows an example of testing
/// routes through the Droplet.
class RouteTests: TestCase {
let drop = try! Droplet.testable()
func testObservations() throws {
try drop
.testResponse(to: .get, at: "observations")
.assertStatus(is: .ok)
}
}
// MARK: Manifest
extension RouteTests {
/// This is a requirement for XCTest on Linux
/// to function properly.
/// See ./Tests/LinuxMain.swift for examples
static let allTests = [
("observations", testObservations),
]
}
| 21.096774 | 55 | 0.657492 |
edd44c772367477ee3b4d18e0d24699ed86fa4fa | 1,948 | //
// UIKitExtensions.swift
// EasyTipView
//
// Created by Teodor Patras on 29/06/16.
// Copyright © 2016 teodorpatras. All rights reserved.
//
import Foundation
import UIKit
// MARK: - UIBarItem extension -
extension UIBarItem {
var view: UIView? {
if let item = self as? UIBarButtonItem, let customView = item.customView {
return customView
}
return self.value(forKey: "view") as? UIView
}
}
// MARK:- UIView extension -
extension UIView {
func hasSuperview(_ superview: UIView) -> Bool{
return viewHasSuperview(self, superview: superview)
}
fileprivate func viewHasSuperview(_ view: UIView, superview: UIView) -> Bool {
if let sview = view.superview {
if sview === superview {
return true
}else{
return viewHasSuperview(sview, superview: superview)
}
}else{
return false
}
}
}
// MARK:- CGRect extension -
extension CGRect {
var x: CGFloat {
get {
return self.origin.x
}
set {
self.origin.x = newValue
}
}
var y: CGFloat {
get {
return self.origin.y
}
set {
self.origin.y = newValue
}
}
//
// var width: CGFloat {
// get {
// return self.size.width
// }
//
// set {
// self.size.width = newValue
// }
// }
//
// var height: CGFloat {
// get {
// return self.size.height
// }
//
// set{
// self.size.height = newValue
// }
// }
// var maxX: CGFloat {
// return self.maxX
// }
//
// var maxY: CGFloat {
// return self.maxY
// }
var center: CGPoint {
return CGPoint(x: self.x + self.width / 2, y: self.y + self.height / 2)
}
}
| 19.877551 | 82 | 0.4923 |
714dc2a0787208ba3eb5c06765725c3b51f6d3eb | 4,287 | //
// GroupProfileTableHeaderContainer.swift
// Pigeon-project
//
// Created by Roman Mizin on 3/13/18.
// Copyright © 2018 Roman Mizin. All rights reserved.
//
import UIKit
class GroupProfileTableHeaderContainer: UIView {
lazy var profileImageView: UIImageView = {
let profileImageView = UIImageView()
profileImageView.translatesAutoresizingMaskIntoConstraints = false
profileImageView.contentMode = .scaleAspectFill
profileImageView.layer.masksToBounds = true
profileImageView.layer.borderWidth = 1
profileImageView.layer.borderColor = ThemeManager.currentTheme().generalSubtitleColor.cgColor//ThemeManager.currentTheme().inputTextViewColor.cgColor
profileImageView.layer.cornerRadius = 48
profileImageView.isUserInteractionEnabled = true
return profileImageView
}()
let addPhotoLabelAdminText = "Add\nphoto"
let addPhotoLabelRegularText = "No photo\nprovided"
let addPhotoLabel: UILabel = {
let addPhotoLabel = UILabel()
addPhotoLabel.translatesAutoresizingMaskIntoConstraints = false
addPhotoLabel.numberOfLines = 2
addPhotoLabel.textColor = FalconPalette.defaultBlue
addPhotoLabel.textAlignment = .center
return addPhotoLabel
}()
var name: PasteRestrictedTextField = {
let name = PasteRestrictedTextField()
name.enablesReturnKeyAutomatically = true
name.font = UIFont(name: "Avenir-Book", size: 14)
name.translatesAutoresizingMaskIntoConstraints = false
name.textAlignment = .center
name.attributedPlaceholder = NSAttributedString(string:"Group name", attributes:[NSAttributedString.Key.foregroundColor: ThemeManager.currentTheme().generalSubtitleColor])
name.borderStyle = .none
name.autocorrectionType = .no
name.returnKeyType = .done
name.keyboardAppearance = ThemeManager.currentTheme().keyboardAppearance
return name
}()
let userData: UIView = {
let userData = UIView()
userData.translatesAutoresizingMaskIntoConstraints = false
userData.layer.cornerRadius = 30
userData.layer.borderWidth = 1
userData.layer.borderColor = ThemeManager.currentTheme().generalSubtitleColor.cgColor
return userData
}()
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(addPhotoLabel)
addSubview(profileImageView)
addSubview(userData)
userData.addSubview(name)
backgroundColor = ThemeManager.currentTheme().generalBackgroundColor
addPhotoLabel.text = addPhotoLabelAdminText
NSLayoutConstraint.activate([
profileImageView.topAnchor.constraint(equalTo: topAnchor, constant: 30),
profileImageView.widthAnchor.constraint(equalToConstant: 100),
profileImageView.heightAnchor.constraint(equalToConstant: 100),
addPhotoLabel.centerXAnchor.constraint(equalTo: profileImageView.centerXAnchor),
addPhotoLabel.centerYAnchor.constraint(equalTo: profileImageView.centerYAnchor),
addPhotoLabel.widthAnchor.constraint(equalToConstant: 100),
addPhotoLabel.heightAnchor.constraint(equalToConstant: 100),
userData.topAnchor.constraint(equalTo: profileImageView.topAnchor, constant: 0),
userData.leftAnchor.constraint(equalTo: profileImageView.rightAnchor, constant: 10),
userData.bottomAnchor.constraint(equalTo: profileImageView.bottomAnchor, constant: 0),
name.centerYAnchor.constraint(equalTo: userData.centerYAnchor, constant: 0),
name.leftAnchor.constraint(equalTo: userData.leftAnchor, constant: 0),
name.rightAnchor.constraint(equalTo: userData.rightAnchor, constant: 0),
name.heightAnchor.constraint(equalToConstant: 50),
])
if #available(iOS 11.0, *) {
NSLayoutConstraint.activate([
profileImageView.leadingAnchor.constraint(equalTo: safeAreaLayoutGuide.leadingAnchor, constant: 10),
userData.trailingAnchor.constraint(equalTo: safeAreaLayoutGuide.trailingAnchor, constant: -10),
])
} else {
NSLayoutConstraint.activate([
profileImageView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 10),
userData.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -10),
])
}
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
}
| 36.641026 | 173 | 0.749942 |
0eeba6a0118bb36a7b047204a241b983dc558d0e | 397 | import Foundation
struct Asset {
var name: String // icon.check
var path: String // Common/icon.check.imageset
var type: AssetType
var key: String { // icon_check
return name
.components(separatedBy: CharacterSet.alphanumerics.inverted)
.map({ $0.prefix(1).lowercased() + $0.dropFirst(1) })
.joined(separator: "_")
}
}
| 26.466667 | 73 | 0.59194 |
799d43a350851dba88cbaa5e9bdd08e3a4628588 | 2,372 | //
// DetalhesFilmeViewController.swift
// StarMovies
//
// Created by Pedro Spim Costa on 07/01/21.
// Copyright © 2021 Pedro Spim Costa. All rights reserved.
//
import UIKit
import Alamofire
class DetalhesFilmeViewController: UIViewController {
//MARK: - Outlets
@IBOutlet weak var imageBackground: UIImageView!
@IBOutlet weak var labelTitulo: UILabel!
@IBOutlet weak var labelTagline: UILabel!
@IBOutlet weak var labelData: UILabel!
@IBOutlet weak var labelBudget: UILabel!
@IBOutlet weak var labelRevenue: UILabel!
@IBOutlet weak var labelGenero: UILabel!
@IBOutlet weak var labelSinopse: UITextView!
@IBOutlet weak var imagePoster: UIImageView!
@IBOutlet weak var labelNota: UILabel!
//MARK: - Variaveis
var filmeSelecionado:Filme? = nil
//MARK: - Funcoes
override func viewDidLoad() {
super.viewDidLoad()
if let filme = filmeSelecionado {
labelTitulo.text = filme.titulo
labelNota.text = "\(filme.nota)"
labelTagline.text = filme.tagline
labelData.text = filme.data
labelBudget.text = filme.getBudgetFormatado()
labelRevenue.text = filme.getRevenueFormatado()
labelGenero.text = filme.generos
labelSinopse.text = filme.sinopse
if let imageUrl = FilmeAPI().gerarURLImagem(link: filme.caminhoImagemPoster){
imagePoster.af_setImage(withURL: imageUrl)
imagePoster.layer.shadowColor = UIColor.black.cgColor
imagePoster.layer.shadowOpacity = 1
imagePoster.layer.shadowOffset = .zero
imagePoster.layer.shadowRadius = 5
}
if let imageUrl = FilmeAPI().gerarURLImagem(link: filme.caminhoImagemBg) {
imageBackground.af_setImage(withURL: imageUrl)
}
}
labelGenero.adjustsFontSizeToFitWidth = true
labelBudget.adjustsFontSizeToFitWidth = true
labelRevenue.adjustsFontSizeToFitWidth = true
}
@IBAction func buttonFecharDetalhes(_ sender: UIButton) {
self.navigationController?.popViewController(animated: true)
}
}
| 28.238095 | 89 | 0.61172 |
8fdba9a15d96bb8f6e72efc8fc45b691c2a16add | 5,228 | //
// Copyright © 2017 UserReport. All rights reserved.
//
import UIKit
import UserReport
class ViewController: UserReportViewController {
// MARK: Property
@IBOutlet weak var testModeSwitch: UISwitch!
// Display mode buttons
@IBOutlet weak var alertDisplayModeButton: UIButton!
@IBOutlet weak var fullscreenDisplayModeButton: UIButton!
// Display session info
@IBOutlet weak var totalScreensLabel: UILabel!
@IBOutlet weak var expectedTotalScreensLabel: UILabel!
@IBOutlet weak var sessionScreensLabel: UILabel!
@IBOutlet weak var expectedSessionScreensLabel: UILabel!
@IBOutlet weak var totalTimeLabel: UILabel!
@IBOutlet weak var expectedTotalTimeLabel: UILabel!
@IBOutlet weak var sessionTimeLabel: UILabel!
@IBOutlet weak var expectedSessionTimeLabel: UILabel!
@IBOutlet weak var quarantineTimeLabel: UILabel!
@IBOutlet weak var expectedQuarantineTimeLabel: UILabel!
// Timer for update session info
private var timer: Timer?
// MARK: View lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// Update navigationBar style and add logo
self.setupNavigationBar()
// Setup base state for testMode switch
UserReport.shared?.testMode = true
self.testModeSwitch.isOn = (UserReport.shared?.testMode)!
// Setup base state for Display mode buttons
let isAlertMode = UserReport.shared?.displayMode == .alert
self.alertDisplayModeButton.isSelected = isAlertMode
self.fullscreenDisplayModeButton.isSelected = !isAlertMode
self.updateSessionInfo()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.updateSessionInfo), userInfo: nil, repeats: true)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.timer?.invalidate()
self.timer = nil
}
// MARK: Setup views
private func setupNavigationBar() {
// Add logo
let logo = UIImageView(image: UIImage(named: "logo_navigation_bar"))
self.navigationItem.titleView = logo
// Update style
self.navigationController?.navigationBar.setBackgroundImage(UIImage(named: "bg_white"), for: .any, barMetrics: .default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.layer.shadowColor = UIColor.black.withAlphaComponent(0.3).cgColor
self.navigationController?.navigationBar.layer.shadowRadius = 5.0
self.navigationController?.navigationBar.layer.shadowOpacity = 1.0
self.navigationController?.navigationBar.layer.shadowOffset = CGSize(width: 0, height: 0)
}
// MARK: Update
@objc private func updateSessionInfo() {
// Session information about the running time of the application and screen views
guard let session = UserReport.shared?.session else { return }
self.totalScreensLabel.text = "\(session.totalScreenView) screens"
self.sessionScreensLabel.text = "\(session.screenView) screens"
self.totalTimeLabel.text = session.totalSecondsInApp.stringTime()
self.sessionTimeLabel.text = session.sessionSeconds.stringTime()
self.quarantineTimeLabel.text = Date().description
// Get current settings for appear survey
guard let settings = session.settings else { return }
self.expectedTotalScreensLabel.text = "\(settings.inviteAfterTotalScreensViewed) screens"
self.expectedSessionScreensLabel.text = "\(settings.sessionScreensView) screens"
self.expectedTotalTimeLabel.text = settings.inviteAfterNSecondsInApp.stringTime()
self.expectedSessionTimeLabel.text = settings.sessionNSecondsLength.stringTime()
self.expectedQuarantineTimeLabel.text = session.localQuarantineDate.description
}
// MARK: Actions
@IBAction func showUserReport(_ sender: Any) {
// Display manually
UserReport.shared?.tryInvite()
}
@IBAction func changeTestMode(_ sender: Any) {
UserReport.shared?.testMode = self.testModeSwitch.isOn
}
@IBAction func selectAlertDisplayMode(_ sender: Any) {
// Change display mode survey in UserReport SDK
UserReport.shared?.displayMode = .alert
// Update buttons
self.alertDisplayModeButton.isSelected = true
self.fullscreenDisplayModeButton.isSelected = false
}
@IBAction func selectFullscreenDisplayMode(_ sender: Any) {
// Change display mode survey in UserReport SDK
UserReport.shared?.displayMode = .fullscreen
// Update buttons
self.alertDisplayModeButton.isSelected = false
self.fullscreenDisplayModeButton.isSelected = true
}
@IBAction func trackScreen(_ sender: Any) {
UserReport.shared?.trackScreen()
self.updateSessionInfo()
}
}
| 36.816901 | 147 | 0.683244 |
f591a63e7cf2ed7a29c361e6849d97ecedca5f88 | 898 | //
// CurrencyFormatterTests.swift
// BankeyUnitTests
//
// Created by jrasmusson on 2021-11-10.
//
import Foundation
import XCTest
@testable import Bankey
class Test: XCTestCase {
var formatter: CurrencyFormatter!
override func setUp() {
super.setUp()
formatter = CurrencyFormatter()
}
func testBreakDollarsIntoCents() throws {
let result = formatter.breakIntoDollarsAndCents(929466.23)
XCTAssertEqual(result.0, "929,466")
XCTAssertEqual(result.1, "23")
}
// Challenge: You write
func testDollarsFormatted() throws {
let result = formatter.dollarsFormatted(929466.23)
XCTAssertEqual(result, "$929,466.23")
}
// Challenge: You write
func testZeroDollarsFormatted() throws {
let result = formatter.dollarsFormatted(0.00)
XCTAssertEqual(result, "$0.00")
}
}
| 23.025641 | 66 | 0.64922 |
2000afc2fa04855c3bf4fc21d39eb1612aa22d05 | 478 |
import AppKit.NSApplication
import Omnibus
public enum RecordOrStopMacro {
public static func execute() {
DispatchQueue.main.asyncAfter(deadline: .now(), execute: {
if macroManager.coordinator.state == .recording {
macroManager.coordinator.macro?.eraseLast()
macroManager.stop()
} else if macroManager.coordinator.state == .idle {
macroManager.record()
}
})
}
private static var macroManager: MacroManager! {
return Backdoor.bus?.access()
}
}
| 21.727273 | 60 | 0.719665 |
79e20672a508a16c2792e5ba9613b9f9a02eead9 | 665 | //
// Settings.swift
// TradernetApiTest
//
// Created by User on 06.09.2020.
// Copyright © 2020 Binira. All rights reserved.
//
import Foundation
let kApiURLString = "https://ws3.tradernet.ru/"
/// Returns list of tickres as comma-separated string
let kTickersIDsString = "RSTI,GAZP,MRKZ,RUAL,HYDR,MRKS,SBER,FEES,TGKA,VTBR,ANH.US,VICL.US,BURG. US,NBL.US,YETI.US,WSFS.US,NIO.US,DXC.US,MIC.US,HSBC.US,EXPN.EU,GSK.EU,SH P.EU,MAN.EU,DB1.EU,MUV2.EU,TATE.EU,KGF.EU,MGGT.EU,SGGD.EU"
/// Returns list of tickers as `[String]`
let kTickersIDsArray: [String] = {
let splittedString = kTickersIDsString.components(separatedBy: ",")
return splittedString
}()
| 31.666667 | 227 | 0.720301 |
c1d881fbcd98776e2c1fc328e408e46f5f52f1ca | 6,027 | //
// PreviewController.swift
// SelectPhoto
//
// Created by 杨新财 on 2018/2/26.
// Copyright © 2018年 杨新财. All rights reserved.
//
import UIKit
import Photos
class PreviewController: UIViewController,UICollectionViewDataSource,UICollectionViewDelegate, UICollectionViewDelegateFlowLayout,PhotoPreviewCellDelegate {
@IBOutlet weak var bottomBarBottom: NSLayoutConstraint!
@IBOutlet weak var bottomBarHeight: NSLayoutConstraint!
@IBOutlet weak var view_blue_dot: UIView!
@IBOutlet weak var lb_original: UILabel!
@IBOutlet weak var lb_num: UILabel!
@IBOutlet weak var btn_send: UIButton!
@IBOutlet weak var btn_selected: UIButton!
@IBOutlet weak var collection_photo: UICollectionView!
var photosChangeHandle:(() -> ())!
var photoImages:[PHAsset] = [PHAsset]()
var currentPage:Int = 0
var isOnlyPreview:Bool = false
override func viewDidLoad() {
super.viewDidLoad()
self.automaticallyAdjustsScrollViewInsets = false
self.configNavigationBar()
self.collection_photo.contentSize = CGSize(width: self.view.bounds.width * CGFloat(self.photoImages.count), height: self.view.bounds.height)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.collection_photo.setContentOffset(CGPoint(x: CGFloat(self.currentPage) * self.view.bounds.width, y: 0), animated: false)
let asset:PHAsset = self.photoImages[currentPage]
self.btn_selected.isSelected = AlbumPhotoImage.shared.selectedImage.contains(asset)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.onImageSingleTap()
}
private func configNavigationBar(){
// UIApplication.shared.statusBarStyle = .lightContent
// self.navigationController?.navigationBar.barStyle = .black
// self.navigationController?.navigationBar.tintColor = UIColor.white
self.bottomBarHeight.constant = isIphoneX() ? 74 : 40
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// UIApplication.shared.statusBarStyle = .default
// self.navigationController?.navigationBar.barStyle = .default
// self.navigationController?.navigationBar.tintColor = PhotoConfig.systemBlue
}
@IBAction func selectedAction(_ sender: Any) {
self.btn_selected.isSelected = !self.btn_selected.isSelected
if self.btn_selected.isSelected {
AlbumPhotoImage.shared.selectedImage.append(self.photoImages[currentPage])
} else {
let asset:PHAsset = self.photoImages[currentPage]
AlbumPhotoImage.shared.selectedImage.remove(at: AlbumPhotoImage.shared.selectedImage.index(of: asset)!)
}
self.photosChangeHandle()
}
@IBAction func backAction(_ sender: Any) {
self.navigationController?.popViewController(animated: true)
}
@IBAction func sendAction(_ sender: Any) {
DYPhotoPickerManager.shared.selectedComplete!(AlbumPhotoImage.shared.selectedImage)
DYPhotoPickerManager.shared.dismissPicker(controller: self)
}
@IBAction func originalImageAction(_ sender: Any) {
self.view_blue_dot.isHidden = !self.view_blue_dot.isHidden
if !self.view_blue_dot.isHidden {
self.calculateCurrentImageData()
} else {
self.lb_original.text = "原图"
}
}
// MARK: - collectionView dataSource delagate
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.photoImages.count
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotoPreviewCell", for: indexPath) as! PhotoPreviewCell
cell.delegate = self
let asset = self.photoImages[indexPath.row]
cell.renderModel(asset: asset)
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return self.view.bounds.size
}
// MARK: - Photo Preview Cell Delegate
func onImageSingleTap() {
let status = !(self.navigationController?.navigationBar.isHidden)!
UIApplication.shared.setStatusBarHidden(status, with: .fade)
self.navigationController?.setNavigationBarHidden(status, animated: true)
UIView.animate(withDuration: 0.3) {
self.bottomBarBottom.constant = status ? (isIphoneX() ? -74 : -40) : 0
self.view.layoutIfNeeded()
}
}
// MARK: - scroll page
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offset = scrollView.contentOffset
let lastPage:Int = self.currentPage
self.currentPage = Int(offset.x / self.view.bounds.width)
if lastPage != self.currentPage {
if self.view_blue_dot.isHidden {
self.lb_original.text = "原图"
} else {
self.calculateCurrentImageData()
}
let asset:PHAsset = self.photoImages[currentPage]
self.btn_selected.isSelected = AlbumPhotoImage.shared.selectedImage.contains(asset)
}
}
func calculateCurrentImageData() {
PHImageManager.default().requestImageData(for: self.photoImages[currentPage], options: nil) { (imageData, name, imageOrientation, info) in
var photoSize:String = ""
var size:CGFloat = 0.0
size = size + CGFloat((imageData?.count)!)/1000.0
if size > 1000 {
photoSize = String.init(format: "%.1fMB", size/1000.0)
} else {
photoSize = String.init(format: "%.1fKB", size)
}
self.lb_original.text = "原图(\(photoSize))"
}
}
}
| 41.565517 | 160 | 0.675129 |
387dd1f9c104dea9880cdebddd3d49a43cd3349c | 1,027 | // swift-tools-version:5.5
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "Erebor",
platforms: [.iOS(.v15)],
products: [
// Products define the executables and libraries a package produces, and make them visible to other packages.
.library(
name: "Erebor",
targets: ["Erebor"]),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages this package depends on.
.target(
name: "Erebor",
dependencies: []),
.testTarget(
name: "EreborTests",
dependencies: ["Erebor"]),
]
)
| 34.233333 | 117 | 0.609542 |
67c32fd5e48cf9e389d97fe683bc08be3657eac0 | 14,489 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import XCTest
import TSCBasic
import TSCUtility
import SPMTestSupport
import PackageModel
import PackageLoading
class PackageDescriptionNextLoadingTests: PackageDescriptionLoadingTests {
override var toolsVersion: ToolsVersion {
.v5_3
}
func testResources() throws {
let stream = BufferedOutputByteStream()
stream <<< """
import PackageDescription
let package = Package(
name: "Foo",
targets: [
.target(
name: "Foo",
resources: [
.copy("foo.txt"),
.process("bar.txt"),
.process("biz.txt", localization: .default),
.process("baz.txt", localization: .base),
]
),
.testTarget(
name: "FooTests",
resources: [
.process("testfixture.txt"),
]
),
]
)
"""
loadManifest(stream.bytes) { manifest in
let resources = manifest.targets[0].resources
XCTAssertEqual(resources[0], TargetDescription.Resource(rule: .copy, path: "foo.txt"))
XCTAssertEqual(resources[1], TargetDescription.Resource(rule: .process, path: "bar.txt"))
XCTAssertEqual(resources[2], TargetDescription.Resource(rule: .process, path: "biz.txt", localization: .default))
XCTAssertEqual(resources[3], TargetDescription.Resource(rule: .process, path: "baz.txt", localization: .base))
let testResources = manifest.targets[1].resources
XCTAssertEqual(testResources[0], TargetDescription.Resource(rule: .process, path: "testfixture.txt"))
}
}
func testBinaryTargetsTrivial() {
let stream = BufferedOutputByteStream()
stream <<< """
import PackageDescription
let package = Package(
name: "Foo",
products: [
.library(name: "Foo1", targets: ["Foo1"]),
.library(name: "Foo2", targets: ["Foo2"])
],
targets: [
.binaryTarget(
name: "Foo1",
path: "../Foo1.xcframework"),
.binaryTarget(
name: "Foo2",
url: "https://foo.com/Foo2-1.0.0.zip",
checksum: "839F9F30DC13C30795666DD8F6FB77DD0E097B83D06954073E34FE5154481F7A"),
]
)
"""
loadManifest(stream.bytes) { manifest in
let targets = Dictionary(uniqueKeysWithValues: manifest.targets.map({ ($0.name, $0) }))
let foo1 = targets["Foo1"]!
let foo2 = targets["Foo2"]!
XCTAssertEqual(foo1, TargetDescription(
name: "Foo1",
dependencies: [],
path: "../Foo1.xcframework",
url: nil,
exclude: [],
sources: nil,
resources: [],
publicHeadersPath: nil,
type: .binary,
pkgConfig: nil,
providers: nil,
settings: [],
checksum: nil))
XCTAssertEqual(foo2, TargetDescription(
name: "Foo2",
dependencies: [],
path: nil,
url: "https://foo.com/Foo2-1.0.0.zip",
exclude: [],
sources: nil,
resources: [],
publicHeadersPath: nil,
type: .binary,
pkgConfig: nil,
providers: nil,
settings: [],
checksum: "839F9F30DC13C30795666DD8F6FB77DD0E097B83D06954073E34FE5154481F7A"))
}
}
func testBinaryTargetsValidation() {
do {
let stream = BufferedOutputByteStream()
stream <<< """
import PackageDescription
let package = Package(
name: "Foo",
products: [
.library(name: "FooLibrary", type: .static, targets: ["Foo"]),
],
targets: [
.binaryTarget(name: "Foo", path: "Foo.xcframework"),
]
)
"""
XCTAssertManifestLoadThrows(stream.bytes) { _, diagnostics in
diagnostics.check(diagnostic: "invalid type for binary product 'FooLibrary'; products referencing only binary targets must have a type of 'library'", behavior: .error)
}
}
do {
let stream = BufferedOutputByteStream()
stream <<< """
import PackageDescription
let package = Package(
name: "Foo",
products: [
.executable(name: "FooLibrary", targets: ["Foo"]),
],
targets: [
.binaryTarget(name: "Foo", path: "Foo.xcframework"),
]
)
"""
XCTAssertManifestLoadThrows(stream.bytes) { _, diagnostics in
diagnostics.check(diagnostic: "invalid type for binary product 'FooLibrary'; products referencing only binary targets must have a type of 'library'", behavior: .error)
}
}
do {
let stream = BufferedOutputByteStream()
stream <<< """
import PackageDescription
let package = Package(
name: "Foo",
products: [
.library(name: "FooLibrary", type: .static, targets: ["Foo", "Bar"]),
],
targets: [
.binaryTarget(name: "Foo", path: "Foo.xcframework"),
.target(name: "Bar"),
]
)
"""
XCTAssertManifestLoadNoThrows(stream.bytes)
}
do {
let stream = BufferedOutputByteStream()
stream <<< """
import PackageDescription
let package = Package(
name: "Foo",
products: [
.library(name: "Foo", targets: ["Foo"]),
],
targets: [
.binaryTarget(name: "Foo", path: " "),
]
)
"""
XCTAssertManifestLoadThrows(stream.bytes) { _, diagnostics in
diagnostics.check(diagnostic: "invalid location for binary target 'Foo'", behavior: .error)
}
}
do {
let stream = BufferedOutputByteStream()
stream <<< """
import PackageDescription
let package = Package(
name: "Foo",
products: [
.library(name: "Foo", targets: ["Foo"]),
],
targets: [
.binaryTarget(name: "Foo", url: "http://foo.com/foo.zip", checksum: "checksum"),
]
)
"""
XCTAssertManifestLoadThrows(stream.bytes) { _, diagnostics in
diagnostics.check(diagnostic: "invalid URL scheme for binary target 'Foo'; valid schemes are: https", behavior: .error)
}
}
do {
let stream = BufferedOutputByteStream()
stream <<< """
import PackageDescription
let package = Package(
name: "Foo",
products: [
.library(name: "Foo", targets: ["Foo"]),
],
targets: [
.binaryTarget(name: "Foo", path: "../Foo"),
]
)
"""
XCTAssertManifestLoadThrows(stream.bytes) { _, diagnostics in
diagnostics.check(diagnostic: "unsupported extension for binary target 'Foo'; valid extensions are: xcframework", behavior: .error)
}
}
do {
let stream = BufferedOutputByteStream()
stream <<< """
import PackageDescription
let package = Package(
name: "Foo",
products: [
.library(name: "Foo", targets: ["Foo"]),
],
targets: [
.binaryTarget(
name: "Foo",
url: "https://foo.com/foo-1",
checksum: "839F9F30DC13C30795666DD8F6FB77DD0E097B83D06954073E34FE5154481F7A"),
]
)
"""
XCTAssertManifestLoadThrows(stream.bytes) { _, diagnostics in
diagnostics.check(diagnostic: "unsupported extension for binary target 'Foo'; valid extensions are: zip", behavior: .error)
}
}
do {
let stream = BufferedOutputByteStream()
stream <<< """
import PackageDescription
let package = Package(
name: "Foo",
products: [
.library(name: "Foo", targets: ["Foo"]),
],
targets: [
.binaryTarget(name: "Foo", path: "../Foo.a"),
]
)
"""
XCTAssertManifestLoadThrows(stream.bytes) { _, diagnostics in
diagnostics.check(diagnostic: "unsupported extension for binary target 'Foo'; valid extensions are: xcframework", behavior: .error)
}
}
do {
let stream = BufferedOutputByteStream()
stream <<< """
import PackageDescription
let package = Package(
name: "Foo",
products: [
.library(name: "Foo", targets: ["Foo"]),
],
targets: [
.binaryTarget(
name: "Foo",
url: "https://foo.com/foo-1.0.0.xcframework",
checksum: "839F9F30DC13C30795666DD8F6FB77DD0E097B83D06954073E34FE5154481F7A"),
]
)
"""
XCTAssertManifestLoadThrows(stream.bytes) { _, diagnostics in
diagnostics.check(diagnostic: "unsupported extension for binary target 'Foo'; valid extensions are: zip", behavior: .error)
}
}
}
func testConditionalTargetDependencies() throws {
let stream = BufferedOutputByteStream()
stream <<< """
import PackageDescription
let package = Package(
name: "Foo",
dependencies: [
.package(path: "/Baz"),
],
targets: [
.target(name: "Foo", dependencies: [
.target(name: "Biz"),
.target(name: "Bar", condition: .when(platforms: [.linux])),
.product(name: "Baz", package: "Baz", condition: .when(platforms: [.macOS])),
.byName(name: "Bar", condition: .when(platforms: [.watchOS, .iOS])),
]),
.target(name: "Bar"),
.target(name: "Biz"),
]
)
"""
loadManifest(stream.bytes) { manifest in
let dependencies = manifest.targets[0].dependencies
XCTAssertEqual(dependencies[0], .target(name: "Biz"))
XCTAssertEqual(dependencies[1], .target(name: "Bar", condition: .init(platformNames: ["linux"], config: nil)))
XCTAssertEqual(dependencies[2], .product(name: "Baz", package: "Baz", condition: .init(platformNames: ["macos"])))
XCTAssertEqual(dependencies[3], .byName(name: "Bar", condition: .init(platformNames: ["watchos", "ios"])))
}
}
func testDefaultLocalization() throws {
let stream = BufferedOutputByteStream()
stream <<< """
import PackageDescription
let package = Package(
name: "Foo",
defaultLocalization: "fr",
targets: [
.target(name: "Foo"),
]
)
"""
XCTAssertManifestLoadNoThrows(stream.bytes) { manifest, _ in
XCTAssertEqual(manifest.defaultLocalization, "fr")
}
}
func testTargetPathsValidation() throws {
let manifestItemToDiagnosticMap = [
"sources: [\"/foo.swift\"]": "invalid relative path '/foo.swift",
"resources: [.copy(\"/foo.txt\")]": "invalid relative path '/foo.txt'",
"exclude: [\"/foo.md\"]": "invalid relative path '/foo.md",
]
for (manifestItem, expectedDiag) in manifestItemToDiagnosticMap {
let stream = BufferedOutputByteStream()
stream <<< """
import PackageDescription
let package = Package(
name: "Foo",
targets: [
.target(
name: "Foo",
\(manifestItem)
),
]
)
"""
XCTAssertManifestLoadThrows(stream.bytes) { error, _ in
switch error {
case let pathError as PathValidationError:
XCTAssertMatch(pathError.description, .contains(expectedDiag))
default:
XCTFail("\(error)")
}
}
}
}
}
| 37.246787 | 183 | 0.459038 |
e8e131b95f14a6a52f2f5c96c4940f4212616342 | 5,354 | //
// AppDelegate.swift
// PotaMaps
//
// Created by Benjamin Montgomery on 12/5/18.
// Copyright © 2018 Benjamin Montgomery. All rights reserved.
//
import UIKit
import CoreData
import SwiftyJSON
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
static var locationManager: LocationService = {
return $0
}(LocationService())
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let userDefaults = UserDefaults.standard
self.window = UIWindow(frame: UIScreen.main.bounds)
var mainStoryboard: UIStoryboard
if userDefaults.bool(forKey: "dataLoaded") == false {
mainStoryboard = UIStoryboard(name: "LoadingData", bundle: nil)
} else {
mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
}
let viewController = mainStoryboard.instantiateInitialViewController()
self.window?.rootViewController = viewController
self.window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "PotaMaps")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
extension Notification.Name {
static var dataLoaded: Notification.Name {
return .init(rawValue: "PotaMaps.dataLoaded")
}
}
| 45.760684 | 285 | 0.684348 |
0a6a97de818166885db25856a8726d95b5e72a01 | 5,820 | //
// ConnectivityMessagePresentationController.swift
// MyMonero
//
// Created by Paul Shapiro on 8/6/17.
// Copyright (c) 2014-2019, MyMonero.com
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//
import UIKit
import Reachability
//
class ConnectivityMessagePresentationController
{
//
// Static
static let shared = ConnectivityMessagePresentationController()
//
// Properties
var viewController: ConnectivityMessageViewController?
var reachability = Reachability()!
//
fileprivate var _isTransitioningPresentation = false
//
// Lifecycle - Init
required init()
{
self.setup()
}
func setup()
{
self.startObserving()
// we do not appear to need to do this:
// self._configurePresentationWithReachability()
}
func startObserving()
{
NotificationCenter.default.addObserver(
self,
selector: #selector(reachabilityChanged),
name: Notification.Name.reachabilityChanged,
object: self.reachability
)
do {
try self.reachability.startNotifier()
} catch let e {
assert(false, "Unable to start notification with error \(e)")
}
}
//
// Lifecycle - Deinit
deinit
{
self.teardown()
}
func teardown()
{
self.stopObserving()
}
func stopObserving()
{
self.reachability.stopNotifier()
NotificationCenter.default.removeObserver(
self,
name: Notification.Name.reachabilityChanged,
object: self.reachability
)
}
//
// Imperatives - Presentation
func _configurePresentationWithReachability()
{
// commented for debug
if self.reachability.connection != .none { // There is apparently a bug appearing in iOS 10 simulated apps by which reconnection is not detected - https://github.com/ashleymills/Reachability.swift/issues/151 - this looks to be fixed in iOS 11 / Swift 4
self.__dismiss()
} else {
self.__present()
}
}
func __present()
{
if Thread.isMainThread == false {
DispatchQueue.main.async { [weak self] in
guard let thisSelf = self else {
return
}
thisSelf.__present()
}
return
}
if self.viewController != nil {
DDLog.Info("ConnectivityMessage", "Asked to \(#function) but already presented.")
return // already presented
}
if self._isTransitioningPresentation {
assert(false)
return // already asked to present before this method could finish… odd… called after returning onto main thread?
}
self._isTransitioningPresentation = true
DDLog.Info("ConnectivityMessage", "Presenting")
let viewController = ConnectivityMessageViewController()
self.viewController = viewController
self.___present_tryToAddChildViewController_andFinish()
}
func ___present_tryToAddChildViewController_andFinish()
{
assert(self.viewController != nil, "self.viewController != nil")
let viewController = self.viewController!
//
guard let window = UIApplication.shared.delegate!.window! else {
DDLog.Info("ConnectivityMessage", "Waiting for window and/or parentViewController")
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute:
{
self.___present_tryToAddChildViewController_andFinish() // try again…
})
return // bail
}
DDLog.Info("ConnectivityMessage", "Actually presenting")
// parentViewController.addChildViewController(viewController)
window.addSubview(viewController.view)
// ^-- I looked into making this a view instead of viewController but some odd delay in layout/presentation occurs… *shrug*
self._isTransitioningPresentation = false
}
func __dismiss()
{
if Thread.isMainThread == false {
DispatchQueue.main.async { [weak self] in
guard let thisSelf = self else {
return
}
thisSelf.__dismiss()
}
return
}
if self.viewController == nil {
// DDLog.Info("ConnectivityMessage", "Asked to \(#function) but not presented.")
return
}
if self._isTransitioningPresentation {
assert(false)
return // already asked to present before this method could finish… odd… called after returning onto main thread?
}
self._isTransitioningPresentation = true
DDLog.Info("ConnectivityMessage", "Dismissing")
// self.viewController!.removeFromParentViewController()
self.viewController!.view!.removeFromSuperview()
self.viewController = nil
self._isTransitioningPresentation = false
}
//
// Delegation
@objc func reachabilityChanged()
{
self._configurePresentationWithReachability()
}
}
| 31.978022 | 254 | 0.742096 |
5dd07e8496c4b1b0519fae47a61b5bac60c39154 | 261 | //
// DLog.swift
// Vanir
//
// Created by James Barrow on 2017-12-05.
// Copyright © 2017 Frostlight Solutions AB. All rights reserved.
//
import Foundation
public func DLog(_ message: @autoclosure () -> String) {
#if DEBUG
NSLog(message())
#endif
}
| 16.3125 | 66 | 0.666667 |
5d03ab3ff7b9d37640d6375ccd538e938e432cf5 | 453 | import ArgumentParser
import Foundation
import TSCBasic
struct MigrationCommand: ParsableCommand {
static var configuration: CommandConfiguration {
CommandConfiguration(commandName: "migration",
abstract: "A set of utilities to assist on the migration of Xcode projects to Tuist.", subcommands: [
MigrationSettingsToXCConfigCommand.self,
])
}
}
| 34.846154 | 130 | 0.629139 |
036d81826531df737aeb163b3e5d8fa420551555 | 9,480 | /*
* Copyright (c) 2014-present 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 UIKit
// A delay function
func delay(_ seconds: Double, completion: @escaping ()->Void) {
DispatchQueue.main.asyncAfter(deadline: .now() + seconds, execute: completion)
}
class ViewController: UIViewController {
// MARK: IB outlets
@IBOutlet var loginButton: UIButton!
@IBOutlet var heading: UILabel!
@IBOutlet var username: UITextField!
@IBOutlet var password: UITextField!
@IBOutlet var cloud1: UIImageView!
@IBOutlet var cloud2: UIImageView!
@IBOutlet var cloud3: UIImageView!
@IBOutlet var cloud4: UIImageView!
// MARK: further UI
let spinner = UIActivityIndicatorView(style: .whiteLarge)
let status = UIImageView(image: UIImage(named: "banner"))
let label = UILabel()
let messages = ["Connecting ...", "Authorizing ...", "Sending credentials ...", "Failed"]
var statusPosition = CGPoint.zero
// MARK: view controller methods
override func viewDidLoad() {
super.viewDidLoad()
//set up the UI
loginButton.layer.cornerRadius = 8.0
loginButton.layer.masksToBounds = true
spinner.frame = CGRect(x: -20.0, y: 6.0, width: 20.0, height: 20.0)
spinner.startAnimating()
spinner.alpha = 0.0
loginButton.addSubview(spinner)
status.isHidden = true
status.center = loginButton.center
view.addSubview(status)
label.frame = CGRect(x: 0.0, y: 0.0, width: status.frame.size.width, height: status.frame.size.height)
label.font = UIFont(name: "HelveticaNeue", size: 18.0)
label.textColor = UIColor(red: 0.89, green: 0.38, blue: 0.0, alpha: 1.0)
label.textAlignment = .center
status.addSubview(label)
statusPosition = status.center
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// 手动给heading添加layer动画
// 1. 定义一个x轴方向的基本动画
let flyRight = CABasicAnimation(keyPath: "position.x")
// 2. 设置初始位置
flyRight.fromValue = -view.bounds.size.width/2
// 3. 设置目的位置
flyRight.toValue = view.bounds.size.width/2
// 4. 设置动画经过的时间
flyRight.duration = 0.5
// 5. 将动画添加到 heading 控件上
heading.layer.add(flyRight, forKey: nil)
// 隐藏三个控件
//heading.center.x -= view.bounds.width
username.center.x -= view.bounds.width
password.center.x -= view.bounds.width
cloud1.alpha = 0.0
cloud2.alpha = 0.0
cloud3.alpha = 0.0
cloud4.alpha = 0.0
loginButton.center.y += 30.0
loginButton.alpha = 0.0
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
//
// UIView.animate(withDuration: 0.5) {
// self.heading.center.x += self.view.bounds.width
// }
// // self.username.center.x += self.view.bounds.width
// UIView.animate(withDuration: 0.5, delay: 0.3, options: [], animations: {
// self.username.center.x += self.view.bounds.width
// }, completion: nil)
//
// // .repeat, .autoreverse, .curveEaseIn
// UIView.animate(withDuration: 0.5, delay: 0.4, options: [], animations: {
// self.password.center.x += self.view.bounds.width
// }, completion: nil)
UIView.animate(withDuration: 0.5, delay: 0.3, usingSpringWithDamping: 0.6, initialSpringVelocity: 0.0, options: [], animations: {
self.username.center.x += self.view.bounds.width
}, completion: nil)
UIView.animate(withDuration: 0.5, delay: 0.4, usingSpringWithDamping: 0.6, initialSpringVelocity: 0.0, options: [], animations: {
self.password.center.x += self.view.bounds.width
}, completion: nil)
UIView.animate(withDuration: 0.5, delay: 0.5, options: [], animations: {
self.cloud1.alpha = 1.0
}, completion: nil)
UIView.animate(withDuration: 0.5, delay: 0.7, options: [], animations: {
self.cloud2.alpha = 1.0
}, completion: nil)
UIView.animate(withDuration: 0.5, delay: 0.9, options: [], animations: {
self.cloud3.alpha = 1.0
}, completion: nil)
UIView.animate(withDuration: 0.5, delay: 1.1, options: [], animations: {
self.cloud4.alpha = 1.0
}, completion: nil)
// 登录按钮动画
UIView.animate(withDuration: 0.5, delay: 0.5, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.0, options: [], animations: {
self.loginButton.center.y -= 30.0
self.loginButton.alpha = 1.0
}, completion: nil)
//
animateCloud(cloud1)
animateCloud(cloud2)
animateCloud(cloud3)
animateCloud(cloud4)
}
func showMessage(index: Int) {
label.text = messages[index]
// transitionCurlDown
UIView.transition(with: status, duration: 0.33, options: [.curveEaseOut, .transitionFlipFromBottom], animations: {
self.status.isHidden = false
}, completion: { _ in
//transition completion
delay(2.0) {
// 遍历 messages,显示各种信息
if index < self.messages.count-1 {
self.removeMessage(index: index)
} else {
//reset form
self.resetForm()
}
}
})
}
func removeMessage(index: Int) {
UIView.animate(withDuration: 0.33, delay: 0.0, options: [], animations: {
self.status.center.x += self.view.frame.size.width
}, completion: { _ in
self.status.isHidden = true
self.status.center = self.statusPosition
self.showMessage(index: index+1)
})
}
func resetForm() {
UIView.transition(with: status, duration: 0.2, options: .transitionFlipFromTop, animations: {
self.status.isHidden = true
self.status.center = self.statusPosition
}, completion: nil)
UIView.animate(withDuration: 0.2, delay: 0.0, options: [], animations: {
self.spinner.center = CGPoint(x: -20.0, y: 16.0)
self.spinner.alpha = 0.0
self.loginButton.backgroundColor = UIColor(red: 0.63, green: 0.84, blue: 0.35, alpha: 1.0)
self.loginButton.bounds.size.width -= 80.0
self.loginButton.center.y -= 60.0
}, completion: nil)
}
func animateCloud(_ cloud: UIImageView) {
// 云移动的速度
let cloudSpeed = 60.0/view.frame.size.width
let duration = (view.frame.size.width - cloud.frame.origin.x) * cloudSpeed
//
UIView.animate(withDuration: TimeInterval(duration), delay: 0.0, options: .curveLinear, animations: {
// 从右边消失后,动画结束
cloud.frame.origin.x = self.view.frame.size.width
}, completion: { _ in
// 从右边消失后,从左边出现
cloud.frame.origin.x = -cloud.frame.size.width
// 再次嵌套调用
self.animateCloud(cloud)
})
}
// MARK: further methods
@IBAction func login() {
view.endEditing(true)
// 登录按钮动画
UIView.animate(withDuration: 1.5, delay: 0.0, usingSpringWithDamping: 0.2, initialSpringVelocity: 0.0, options: [], animations: {
self.loginButton.bounds.size.width += 80.0
}, completion: { _ in
self.showMessage(index: 0)
})
UIView.animate(withDuration: 0.33, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.0, options: [], animations: {
self.loginButton.center.y += 60.0
self.loginButton.backgroundColor = UIColor(red: 0.85, green: 0.83, blue: 0.45, alpha: 1.0)
self.spinner.center = CGPoint(x: 40.0, y: self.loginButton.frame.size.height/2)
self.spinner.alpha = 1.0
}, completion: nil)
}
// MARK: UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
let nextField = (textField === username) ? password : username
nextField?.becomeFirstResponder()
return true
}
}
| 37.03125 | 138 | 0.598734 |
ef1bf73b703bc84fa4f50705dd0b9523c4631e7c | 1,669 | //
// ViewController.swift
// ViewControllerTransition
//
// Created by landixing on 2017/6/27.
// Copyright © 2017年 WJQ. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
fileprivate lazy var dissolveFromVC: DissolveFirstVC = DissolveFirstVC()
fileprivate lazy var bottomFirstVC: BottomFirstVC = BottomFirstVC()
fileprivate lazy var swipeFirstVC: SwipeFirstVC = SwipeFirstVC()
fileprivate lazy var fromRightFirstVC: FromRightFirstVC = FromRightFirstVC()
fileprivate lazy var topVC: FromTopFirstVC = FromTopFirstVC()
fileprivate lazy var adaptiveVC : AdaptiveFirstControl = AdaptiveFirstControl()
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func present_Bottom() {
navigationController?.pushViewController(bottomFirstVC, animated: true)
}
@IBAction func from_Right() {
navigationController?.pushViewController(fromRightFirstVC, animated: true)
}
@IBAction func Dissolve() {
navigationController?.pushViewController(dissolveFromVC, animated: true)
}
@IBAction func Swipe() {
// navigationController?.pushViewController(swipeFirstVC, animated: true)
}
@IBAction func Top() {
navigationController?.pushViewController(topVC, animated: true)
}
@IBAction func Adaptive() {
navigationController?.pushViewController(adaptiveVC, animated: true)
}
}
| 26.492063 | 83 | 0.682445 |
c14d6cfb23646a64d5b506ebe383ac2c658f6868 | 405 | //
// Update.swift
// Eureka
//
// Created by Поляков Лев on 24.11.2021.
// Copyright © 2021 Xmartlabs. All rights reserved.
//
import Foundation
public final class Update {
public let tags: [String]
public let updateBlock: (Form) -> Void
public init(on tags: [String], by updateBlock: @escaping (Form) -> Void) {
self.tags = tags
self.updateBlock = updateBlock
}
}
| 20.25 | 78 | 0.639506 |
0a544565fee4052049f977b17fd8571c5aacd44e | 15,211 | import Dispatch
import Foundation
import CCurl
import JWT
import Crypto
import Console
import Service
open class VaporAPNS: Service {
fileprivate var options: Options
private var lastGeneratedToken: (date: Date, token: String)?
fileprivate var curlHandle: UnsafeMutableRawPointer!
public init(options: Options) throws {
self.options = options
if !options.disableCurlCheck {
if options.forceCurlInstall {
// let curlupdater = CurlUpdater()
// curlupdater.updateCurl()
} else {
// let curlVersionChecker = CurlVersionHelper()
// curlVersionChecker.checkVersion()
}
}
self.curlHandle = curl_multi_init()
curlHelperSetMultiOpt(curlHandle, CURLMOPT_PIPELINING, CURLPIPE_MULTIPLEX)
}
deinit {
curl_multi_cleanup(self.curlHandle)
}
// MARK: CURL Config
private func configureCurlHandle(for message: ApplePushMessage,
to deviceToken: String,
completionHandler: @escaping (Result) -> Void) -> Connection? {
guard let handle = curl_easy_init() else { return nil }
curlHelperSetOptBool(handle, CURLOPT_VERBOSE, options.debugLogging ? CURL_TRUE : CURL_FALSE)
if self.options.usesCertificateAuthentication {
curlHelperSetOptString(handle, CURLOPT_SSLCERT, options.certPath)
curlHelperSetOptString(handle, CURLOPT_SSLCERTTYPE, "PEM")
curlHelperSetOptString(handle, CURLOPT_SSLKEY, options.keyPath)
curlHelperSetOptString(handle, CURLOPT_SSLKEYTYPE, "PEM")
}
curlHelperSetOptInt(handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0)
let url = self.hostURL(message.sandbox, token: deviceToken)
curlHelperSetOptString(handle, CURLOPT_URL, url)
// force set port to 443
curlHelperSetOptInt(handle, CURLOPT_PORT, options.port.rawValue)
// Follow location
curlHelperSetOptBool(handle, CURLOPT_FOLLOWLOCATION, CURL_TRUE)
// set POST request
curlHelperSetOptBool(handle, CURLOPT_POST, CURL_TRUE)
// Pipeline
curlHelperSetOptInt(handle, CURLOPT_PIPEWAIT, 1)
// setup payload
// Use CURLOPT_COPYPOSTFIELDS so Swift can release str and let CURL take
// care of the rest. This implies we need to set CURLOPT_POSTFIELDSIZE
// first
let serialized = try! message.payload.makeJSON()
guard let str = String(bytes: serialized, encoding: .utf8) else { return nil }
curlHelperSetOptInt(handle, CURLOPT_POSTFIELDSIZE, str.utf8.count)
curlHelperSetOptString(handle, CURLOPT_COPYPOSTFIELDS, str.cString(using: .utf8))
// Tell CURL to add headers
curlHelperSetOptBool(handle, CURLOPT_HEADER, CURL_TRUE)
//Headers
let headers = self.requestHeaders(for: message)
var curlHeaders: UnsafeMutablePointer<curl_slist>?
if !options.usesCertificateAuthentication {
let token: String
if let recentToken = lastGeneratedToken, abs(recentToken.date.timeIntervalSinceNow) < 59 * 60 {
token = recentToken.token
} else {
//let privateKey = Data(options.privateKey!.utf8)//options.privateKey!.bytes.base64Decoded
//let publicKey = Data(options.publicKey!.utf8)//options.publicKey!.bytes.base64Decoded
let jwt = JWT(header: JWTHeader(alg: "ES256", typ: nil, cty: nil, crit: nil, kid: options.keyId!), payload: APNSJWTPayload(iss: IssuerClaim(value: options.teamId!)))
let signed = try! jwt.sign(using: .es256(key: options.privateKey!))
guard let tokenString = String(bytes: signed, encoding: .utf8) else { return nil }
do {
_ = try JWT<APNSJWTPayload>(from: signed, verifiedUsing: .es256(key: options.publicKey!))
} catch {
print ("Couldn't verify token. This is a non-fatal error, we'll try to send the notification anyway.")
if options.debugLogging {
print("\(error)")
}
}
token = tokenString.replacingOccurrences(of: " ", with: "")
lastGeneratedToken = (date: Date(), token: token)
}
curlHeaders = curl_slist_append(curlHeaders, "Authorization: bearer \(token)")
}
curlHeaders = curl_slist_append(curlHeaders, "User-Agent: VaporAPNS")
for header in headers {
curlHeaders = curl_slist_append(curlHeaders, "\(header.key): \(header.value)")
}
curlHeaders = curl_slist_append(curlHeaders, "Accept: application/json")
curlHeaders = curl_slist_append(curlHeaders, "Content-Type: application/json");
curlHelperSetOptList(handle, CURLOPT_HTTPHEADER, curlHeaders)
return Connection(handle: handle,
message: message,
token: deviceToken,
headers: curlHeaders,
completionHandler: completionHandler)
}
private func requestHeaders(for message: ApplePushMessage) -> [String: String] {
var headers: [String : String] = [
"apns-id": message.messageId,
"apns-expiration": "\(Int(message.expirationDate?.timeIntervalSince1970.rounded() ?? 0))",
"apns-push-type": "\(message.type.rawValue)",
"apns-topic": message.topic ?? options.topic
]
if let priority = message.priority {
headers["apns-priority"] = "\(priority.rawValue)"
}
if let collapseId = message.collapseIdentifier {
headers["apns-collapse-id"] = collapseId
}
return headers
}
// MARK: Connections
private let connectionQueue: DispatchQueue = DispatchQueue(label: "VaporAPNS.connection-managment")
private class Connection: Equatable, Hashable {
private(set) var data: Data = Data()
let handle: UnsafeMutableRawPointer
let headers: UnsafeMutablePointer<curl_slist>?
let messageId: String
let token: String
let completionHandler: (Result) -> Void
fileprivate func append(bytes: [UInt8]) {
data.append(contentsOf: bytes)
}
init(handle: UnsafeMutableRawPointer, message: ApplePushMessage, token: String, headers: UnsafeMutablePointer<curl_slist>?, completionHandler: @escaping (Result) -> Void) {
self.handle = handle
self.messageId = message.messageId
self.token = token
self.completionHandler = completionHandler
self.headers = headers
}
deinit {
// if the connection get's dealloced we can clenaup the
// curl structures as well
curl_slist_free_all(headers)
curl_easy_cleanup(handle)
}
func hash(into hasher: inout Hasher) {
return messageId.hash(into: &hasher)
}
static func == (lhs: Connection, rhs: Connection) -> Bool {
return lhs.messageId == rhs.messageId && lhs.token == rhs.token
}
}
private var connections: Set<Connection> = Set()
private func complete(connection: Connection) {
connectionQueue.async {
guard self.connections.contains(connection) else { return }
self.connections.remove(connection)
self.performQueue.async {
curl_multi_remove_handle(self.curlHandle, connection.handle)
self.handleCompleted(connection: connection)
}
}
}
private func handleCompleted(connection: Connection) {
// Create string from Data
let str = String.init(data: connection.data, encoding: .utf8)!
// Split into two pieces by '\r\n\r\n' as the response has two newlines before the returned data. This causes us to have two pieces, the headers/crap and the server returned data
let splittedString = str.components(separatedBy: "\r\n\r\n")
let result: Result!
// Ditch the first part and only get the useful data part
let dataString: String?
if splittedString.count > 1 {
dataString = splittedString[1]
} else {
dataString = nil
}
if let responseData = dataString,
responseData != "",
let data = responseData.data(using: .utf8),
let json = try? JSONSerialization.jsonObject(with: data, options: []),
let responseJSON = json as? [String: Any] {
// Get JSON from loaded data string
if let reason = responseJSON["reason"] as? String {
result = Result.error(apnsId: connection.messageId,
deviceToken: connection.token,
error: APNSError.init(errorReason: reason))
} else {
result = Result.success(apnsId: connection.messageId,
deviceToken: connection.token,
serviceStatus: .success)
}
} else {
result = Result.success(apnsId: connection.messageId,
deviceToken: connection.token,
serviceStatus: .success)
}
connection.completionHandler(result)
}
// MARK: Running cURL Multi
private let performQueue: DispatchQueue = DispatchQueue(label: "VaporAPNS.curl_multi_perform")
private var runningConnectionsCount: Int32 = 0
private var repeats = 0
/// Core cURL-multi Loop is done here
private func performActiveConnections() {
var code: CURLMcode = CURLM_CALL_MULTI_PERFORM
var numfds: Int32 = 0
code = curl_multi_perform(self.curlHandle, &self.runningConnectionsCount)
if code == CURLM_OK {
code = curl_multi_wait(self.curlHandle, nil, 0, 1000, &numfds);
}
if code != CURLM_OK {
print("curl_multi_wait failed with error code \(code): \(String(cString: curl_multi_strerror(code)))")
return
}
if numfds != 0 {
self.repeats += 1
} else {
self.repeats = 0
}
var numMessages: Int32 = 0
var curlMessage: UnsafeMutablePointer<CURLMsg>?
repeat {
curlMessage = curl_multi_info_read(self.curlHandle, &numMessages)
if let message = curlMessage {
let handle = message.pointee.easy_handle
let msg = message.pointee.msg
if msg == CURLMSG_DONE {
self.connectionQueue.async {
guard let connection = self.connections.first(where: { $0.handle == handle }) else {
self.performQueue.async {
print("Warning: Removing handle not in connection list")
curl_multi_remove_handle(self.curlHandle, handle)
}
return
}
self.complete(connection: connection)
}
} else {
print("Connection failiure: \(msg) \(String(cString: curl_easy_strerror(message.pointee.data.result)))")
}
}
} while numMessages > 0
if self.runningConnectionsCount > 0 {
performQueue.async {
if self.repeats > 1 {
self.performQueue.asyncAfter(deadline: DispatchTime.now() + 0.1) {
self.performActiveConnections()
}
} else {
self.performActiveConnections()
}
}
}
}
// MARK: API
@available(*, unavailable, renamed: "send(to:completionHandler:)")
open func send(_ message: ApplePushMessage, to deviceToken: String) -> Result {
send(message, to: deviceToken, completionHandler: { _ in })
return Result.networkError(error: SimpleError.string(message: "API is deprecated use send(to:completionHandler:)"))
}
open func send(_ message: ApplePushMessage, to deviceToken: String, completionHandler: @escaping (Result) -> Void) {
guard let connection = configureCurlHandle(for: message, to: deviceToken, completionHandler: completionHandler) else {
completionHandler(Result.networkError(error: SimpleError.string(message: "Could not configure cURL")))
return
}
connectionQueue.async {
self.connections.insert(connection)
let ptr = Unmanaged<Connection>.passUnretained(connection).toOpaque()
let _ = curlHelperSetOptWriteFunc(connection.handle, ptr) { (ptr, size, nMemb, privateData) -> Int in
let realsize = size * nMemb
let pointee = Unmanaged<Connection>.fromOpaque(privateData!).takeUnretainedValue()
var bytes: [UInt8] = [UInt8](repeating: 0, count: realsize)
memcpy(&bytes, ptr!, realsize)
pointee.append(bytes: bytes)
return realsize
}
self.performQueue.async {
// curlHandle should only be touched on performQueue
curl_multi_add_handle(self.curlHandle, connection.handle)
self.performActiveConnections()
}
}
}
open func send(_ message: ApplePushMessage, to deviceTokens: [String], perDeviceResultHandler: @escaping ((_ result: Result) -> Void)) {
for deviceToken in deviceTokens {
self.send(message, to: deviceToken, completionHandler: perDeviceResultHandler)
}
}
// MARK: Helpers
private func toNullTerminatedUtf8String(_ str: [UTF8.CodeUnit]) -> Data? {
return str.withUnsafeBufferPointer() { buffer -> Data? in
return buffer.baseAddress != nil ? Data(bytes: buffer.baseAddress!, count: buffer.count) : nil
}
}
}
extension VaporAPNS {
fileprivate func hostURL(_ development: Bool, token deviceToken: String) -> String {
if development {
return "https://api.sandbox.push.apple.com/3/device/\(deviceToken)"
} else {
return "https://api.push.apple.com/3/device/\(deviceToken)"
}
}
}
| 39.819372 | 186 | 0.571823 |
0a8c015dc391c5c6cfe0cb918313460acdacdfcc | 10,355 | //
// ConcentricGridViewWalker.swift
//
// Created by Gutsulyak Dmitry on 3/17/15.
// Copyright (c) 2015 SHAPE GmbH. All rights reserved.
//
import Foundation
import QuartzCore
/**
The ConcentricGridViewWalker class implements a Walker abstraction and basic methods for moving through the grid.
The entity is used for walking around the grid starting from the central cell and memorizing passed ones.
It might be also used for walking around any grid and not only by spirally concentric algorithm.
*/
class ConcentricGridViewWalker {
/// The ongoing figure that is used for walking around.
var figure: ConcentricGridViewFigure
/// The ongoing cell of the figure on which Walker is standing.
var cell: ConcentricGridViewCell
// The central cell of the grid - usually is used only for the first step.
var centralCell: CGRect
// The peripheral cell of the grid.
var peripheralCell: CGRect
// The size of the grid in pts.
var grid: CGSize
/**
Inits the Walker instance that is already standning on the central cell of the grid. And this cell is already stored into the ongoing figure.
:param: figure A figure that Walker uses for storing passed cells.
:param: centralCell A centrall cell of the grid.
:param: peripheralCell A peripheral cell of the grid.
:param: grid A grid instance that Walker is used for bypassing.
:returns: An initialized instance of the class.
*/
init(figure: ConcentricGridViewFigure, centralCell: CGRect, peripheralCell: CGRect, grid: CGSize) {
self.figure = figure
self.centralCell = centralCell
self.peripheralCell = peripheralCell
self.grid = grid
// Init the central cell
self.cell = ConcentricGridViewCell(
index: 0,
frame: CGRectMake(
centralCell.origin.x,
centralCell.origin.y,
centralCell.width,
centralCell.height
)
)
addToFigure(self.cell)
changeCellOn(figure.getLastCell()!)
}
/**
Allows Walker to step onto a given cell.
:param: frame A frame of a cell for the next step.
:param: memorize Whether a cell should be memorized. The default value is `true`.
*/
func stepToCellWith(frame: CGRect, memorize: Bool = true) {
if let expectedCell = figure.getCellBy(frame) {
changeCellOn(expectedCell)
} else {
// Set the default index to zero in case if this is the central cell
var nextIndex: Int = 0
let gridRectangle = CGRectMake(
0, 0,
grid.width,
grid.height
)
let doesGridContainFullCell = CGRectContainsRect(gridRectangle, frame)
// Get the next index always from the last cell in a rectangle or go to a previous to get one.
if let lastCell = figure.getLastCell() {
nextIndex = lastCell.index + 1
} else if let previous = figure.previous {
if let lastPreviousCell = previous.getLastCell() {
nextIndex = lastPreviousCell.index + 1
}
}
let newCell = ConcentricGridViewCell(
index: nextIndex,
frame: frame
)
if (memorize && doesGridContainFullCell) {
addToFigure(newCell)
changeCellOn(figure.getLastCell()!)
} else {
changeCellOn(newCell)
}
}
}
/**
Adds a given cell to the figure.
:param: newCell A cell to add to the figure.
*/
func addToFigure(newCell: ConcentricGridViewCell) {
figure.addCell(newCell)
}
/**
Changes the cell to given one.
:param: newOne A cell to change.
*/
func changeCellOn(newOne: ConcentricGridViewCell) {
cell = newOne
}
/**
Allows Walker to jump onto the opposite side.
:param: memorize Whether need to memorize the destination cell. The default value is `true`.
*/
func jumpToOppositeBottomCell(memorize: Bool = true) {
moveRelativeTo(0, -figure.frame.height + cell.frame.height, memorize)
}
/**
Allows Walker to jump to the top left corner of the current rect.
:param: memorize Whether need to memorize the destination cell. The default value is `true`.
*/
func jumpToTopLeftCornerIn(#rectangle: CGRect?, memorize: Bool = true) {
let frame = (rectangle != nil) ? rectangle! : figure.frame
moveAbsoluteTo(
CGRectGetMinX(frame),
CGRectGetMinY(frame),
memorize
)
}
/**
Allows Walker to jump onto a top right corner of the current figure.
:param: rectangle A rectangle to jump.
:param: memorize Whether need to memorize the destination cell. The default value is `true`.
*/
func jumpToTopRightCornerIn(#rectangle: CGRect?, memorize: Bool = true) {
let frame = (rectangle != nil) ? rectangle! : figure.frame
moveAbsoluteTo(
CGRectGetMaxX(frame) - peripheralCell.width,
CGRectGetMinY(frame),
memorize
)
}
/**
Allows Walker to jump onto a bottom right corner of the current figure.
:param: rectangle A rectangle to jump.
:param: memorize Whether need to memorize the destination cell. The default value is `true`.
*/
func jumpToBottomRightCornerIn(#rectangle: CGRect?, memorize: Bool = true) {
let frame = (rectangle != nil) ? rectangle! : figure.frame
moveAbsoluteTo(
CGRectGetMaxX(frame) - peripheralCell.width,
CGRectGetMaxY(frame) - peripheralCell.height,
memorize
)
}
/**
Allows Walker to jump onto a bottom left corner of the current rect.
:param: rectangle A rectangle to jump.
:param: memorize Whether need to memorize the destination cell. The default value is `true`.
*/
func jumpToBottomLeftCornerIn(#rectangle: CGRect?, memorize: Bool = true) {
let frame = (rectangle != nil) ? rectangle! : figure.frame
moveAbsoluteTo(
CGRectGetMinX(frame),
CGRectGetMaxY(frame) - peripheralCell.height,
memorize
)
}
/**
Allows Walker to make one step in the right direction. This method is used for convenience as a wrapper.
:param: memorize Whether need to memorize the destination cell. The default value is `true`.
*/
func halfStepToRight(memorize: Bool = true) {
moveRelativeTo(peripheralCell.width / 2, 0, memorize)
}
/**
Allows Walker to make one step in the right direction. This method is used for convenience as a wrapper.
:param: memorize Whether need to memorize the destination cell. The default value is `true`.
*/
func stepToRight(memorize: Bool = true) -> Void {
moveRelativeTo(peripheralCell.width, 0, memorize)
}
/**
Allows Walker to make one step in the bottom direction. This method is used for convenience as a wrapper.
:param: memorize Whether need to memorize the destination cell. The default value is `true`.
*/
func stepToBottom(memorize: Bool = true) {
moveRelativeTo(0, peripheralCell.height, memorize)
}
/**
Allows Walker to make a half-step in the bottom direction. This method is used for convenience as a wrapper.
:param: memorize Whether need to memorize the destination cell. The default value is `true`.
*/
func halfStepToBottom(memorize: Bool = true) {
moveRelativeTo(0, peripheralCell.height / 2, memorize)
}
/**
Allows Walker to make one step in the left direction. This method is used for convenience as a wrapper.
:param: memorize Whether need to memorize the destination cell. The default value is `true`.
*/
func stepToLeft(memorize: Bool = true) {
moveRelativeTo(-peripheralCell.width, 0, memorize)
}
/**
Allows Walker to make a half-step in the left direction. This method is used for convenience as a wrapper.
:param: memorize Whether need to memorize the destination cell. The default value is `true`.
*/
func halfStepToLeft(memorize: Bool = true) {
moveRelativeTo(-peripheralCell.width / 2, 0, memorize)
}
/**
Allows Walker to make one step in the top direction. This method is used for convenience as a wrapper.
:param: memorize Whether need to memorize the destination cell. The default value is `true`.
*/
func stepToTop(memorize: Bool = true) {
moveRelativeTo(0, -peripheralCell.height, memorize)
}
/**
Allows Walker to make a half-step in the top direction. This method is used for convenience as a wrapper.
:param: memorize Whether need to memorize the destination cell. The default value is `true`.
*/
func halfStepToTop(memorize: Bool = true) {
moveRelativeTo(0, -peripheralCell.height / 2, memorize)
}
/**
Moves Walker to a given cell relatively to the current one.
:param: dx A delta of x-coordinate to go.
:param: dy A delta of y-coordinate to go.
:param: memorize Whether it should memorize a new cell.
*/
func moveRelativeTo(dx: CGFloat, _ dy: CGFloat, _ memorize: Bool = true) {
let frame = CGRectOffset(
CGRectMake(
cell.frame.origin.x,
cell.frame.origin.y,
peripheralCell.width,
peripheralCell.height
), dx, dy
)
stepToCellWith(frame, memorize: memorize)
}
/**
Moves Walker to a given cell relatively to a device screen.
:param: x An x-coordinate to go
:param: y An y-coordinate to go
:param: memorize Whether it shoud memorize a new cell.
*/
func moveAbsoluteTo(x: CGFloat, _ y: CGFloat, _ memorize: Bool = true) {
let frame = CGRectMake(
x, y,
peripheralCell.width,
peripheralCell.height
)
stepToCellWith(frame, memorize: memorize)
}
}
| 33.729642 | 145 | 0.62395 |
757d7c4bbb088efaf1b99db6d1930de170945c47 | 3,177 | import UIKit
//import NumPad
public class LibraryDemoViewController: UIViewController {
lazy var containerView: UIView = { [unowned self] in
let containerView = UIView()
containerView.layer.borderColor = self.borderColor.cgColor
containerView.layer.borderWidth = 1
self.view.addSubview(containerView)
containerView.constrainToEdges()
return containerView
}()
lazy var textField: UITextField = { [unowned self] in
let textField = UITextField()
textField.translatesAutoresizingMaskIntoConstraints = false
textField.textAlignment = .right
textField.textColor = UIColor(white: 0.3, alpha: 1)
textField.font = .systemFont(ofSize: 40)
textField.placeholder = "0".currency()
textField.isEnabled = false
self.containerView.addSubview(textField)
return textField
}()
lazy var numPad: NumPad = { [unowned self] in
let numPad = DefaultNumPad()
numPad.delegate = self
numPad.translatesAutoresizingMaskIntoConstraints = false
numPad.backgroundColor = self.borderColor
self.containerView.addSubview(numPad)
return numPad
}()
let borderColor = UIColor(white: 0.9, alpha: 1)
public override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .white
self.title = "NumPad Demo"
let views: [String : Any] = ["textField": textField, "numPad": numPad]
containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-20-[textField]-20-|", options: [], metrics: nil, views: views))
containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[numPad]|", options: [], metrics: nil, views: views))
containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-20-[textField(==120)][numPad]|", options: [], metrics: nil, views: views))
self.view.bringSubviewToFront(self.closeButton)
}
public override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(true, animated: animated)
}
public override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
numPad.invalidateLayout()
}
@IBOutlet private weak var closeButton: UIButton!
@IBAction private func closeButtonDidTap() {
self.navigationController?.popViewController(animated: true)
}
}
extension LibraryDemoViewController: NumPadDelegate {
public func numPad(_ numPad: NumPad, itemTapped item: Item, atPosition position: Position) {
switch (position.row, position.column) {
case (3, 0):
textField.text = nil
default:
let item = numPad.item(for: position)!
let string = textField.text!.sanitized() + item.title!
if Int(string) == 0 {
textField.text = nil
} else {
textField.text = string.currency()
}
}
}
}
| 35.3 | 165 | 0.640541 |
790126ac1ad141c6b58c1e694466fdd0986429b3 | 2,798 | //
// Live.swift
// CodeEditModules/ShellClient
//
// Created by Marco Carnevali on 27/03/22.
//
import Foundation
import Combine
// TODO: DOCS (Marco Carnevali)
// swiftlint:disable missing_docs
public extension ShellClient {
static func live() -> Self {
func generateProcessAndPipe(_ args: [String]) -> (Process, Pipe) {
var arguments = ["-c"]
arguments.append(contentsOf: args)
let task = Process()
let pipe = Pipe()
task.standardOutput = pipe
task.standardError = pipe
task.arguments = arguments
task.executableURL = URL(fileURLWithPath: "/bin/zsh")
return (task, pipe)
}
var cancellables: [UUID: AnyCancellable] = [:]
return ShellClient(
runLive: { args in
let subject = PassthroughSubject<String, Never>()
let (task, pipe) = generateProcessAndPipe(args)
let outputHandler = pipe.fileHandleForReading
// wait for the data to come in and then notify
// the Notification with Name: `NSFileHandleDataAvailable`
outputHandler.waitForDataInBackgroundAndNotify()
let id = UUID()
cancellables[id] = NotificationCenter
.default
.publisher(for: .NSFileHandleDataAvailable, object: outputHandler)
.sink { _ in
let data = outputHandler.availableData
// swiftlint:disable:next empty_count
guard data.count > 0 else {
// if no data is available anymore
// we should cancel this cancellable
// and mark the subject as finished
cancellables.removeValue(forKey: id)
subject.send(completion: .finished)
return
}
if let line = String(data: data, encoding: .utf8)?
.split(whereSeparator: \.isNewline) {
line
.map(String.init)
.forEach(subject.send(_:))
}
outputHandler.waitForDataInBackgroundAndNotify()
}
task.launch()
return subject.eraseToAnyPublisher()
}, run: { args in
let (task, pipe) = generateProcessAndPipe(args)
try task.run()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
return String(data: data, encoding: .utf8) ?? ""
}
)
}
}
| 39.971429 | 86 | 0.499285 |
79be0de5b0798288d9756f331634dce0f32f8a24 | 3,732 | //
// DIDPool.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
public class DIDPool: Codable {
public enum State: String, Codable {
case active = "active"
case inactive = "inactive"
case deleted = "deleted"
}
public enum Provider: String, Codable {
case pureCloud = "PURE_CLOUD"
case pureCloudVoice = "PURE_CLOUD_VOICE"
}
/** The globally unique identifier for the object. */
public var _id: String?
/** The name of the entity. */
public var name: String?
/** The division to which this entity belongs. */
public var division: Division?
/** The resource's description. */
public var _description: String?
/** The current version of the resource. */
public var version: Int?
/** The date the resource was created. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z */
public var dateCreated: Date?
/** The date of the last modification to the resource. Date time is represented as an ISO-8601 string. For example: yyyy-MM-ddTHH:mm:ss[.mmm]Z */
public var dateModified: Date?
/** The ID of the user that last modified the resource. */
public var modifiedBy: String?
/** The ID of the user that created the resource. */
public var createdBy: String?
/** Indicates if the resource is active, inactive, or deleted. */
public var state: State?
/** The application that last modified the resource. */
public var modifiedByApp: String?
/** The application that created the resource. */
public var createdByApp: String?
/** The starting phone number for the range of this DID pool. Must be in E.164 format */
public var startPhoneNumber: String?
/** The ending phone number for the range of this DID pool. Must be in E.164 format */
public var endPhoneNumber: String?
public var comments: String?
/** The provider for this DID pool */
public var provider: Provider?
/** The URI for this object */
public var selfUri: String?
public init(_id: String?, name: String?, division: Division?, _description: String?, version: Int?, dateCreated: Date?, dateModified: Date?, modifiedBy: String?, createdBy: String?, state: State?, modifiedByApp: String?, createdByApp: String?, startPhoneNumber: String?, endPhoneNumber: String?, comments: String?, provider: Provider?, selfUri: String?) {
self._id = _id
self.name = name
self.division = division
self._description = _description
self.version = version
self.dateCreated = dateCreated
self.dateModified = dateModified
self.modifiedBy = modifiedBy
self.createdBy = createdBy
self.state = state
self.modifiedByApp = modifiedByApp
self.createdByApp = createdByApp
self.startPhoneNumber = startPhoneNumber
self.endPhoneNumber = endPhoneNumber
self.comments = comments
self.provider = provider
self.selfUri = selfUri
}
public enum CodingKeys: String, CodingKey {
case _id = "id"
case name
case division
case _description = "description"
case version
case dateCreated
case dateModified
case modifiedBy
case createdBy
case state
case modifiedByApp
case createdByApp
case startPhoneNumber
case endPhoneNumber
case comments
case provider
case selfUri
}
}
| 31.627119 | 359 | 0.628349 |
11bbf1e3b58597cb3ec247c797c3ad4ff81d9049 | 357 | //
// NavigationButtonTag.swift
// Mvvm
//
// Created by Sean Davis on 12/7/17.
// Copyright © 2017 Sean Davis. All rights reserved.
//
import UIKit
struct NavigationButtonTag {
static let signUpForRewards = 1
static let myRewards = 2
static let NavigationButtonTitleText: [String] = ["", "SIGN UP FOR REWARDS", "MY REWARDS"]
}
| 18.789474 | 94 | 0.666667 |
18cca63eee72ed57a95d4952da7db19776480e2b | 193 | //
// ShareSDKUtil.swift
// ifanr
//
// Created by sys on 16/7/30.
// Copyright © 2016年 ifanrOrg. All rights reserved.
//
import Foundation
class ShareSDKUtil: NSObject {
} | 12.866667 | 52 | 0.626943 |
d5580fafa54a8167c938b974e6b46089ba5f72f8 | 1,497 | //
// AdaptiveAttribute.swift
// Briggs
//
// Copyright (c) 2017 Ada Turner (https://github.com/auswahlaxiom)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions://
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.//
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
/**
An `AdaptiveAttribute` represents a trait in a `UITraitCollection`.
*/
public protocol AdaptiveAttribute {
/**
Creates a `UITraitCollection` corresponding to the trait `self` represents
*/
func generateTraitCollection() -> UITraitCollection
}
| 39.394737 | 81 | 0.738811 |
ac9ebdcdcf7a66e69b33bac2eed21a84014aa36a | 176 | import Foundation
public extension Data {
static func testJson(_ json: Any) throws -> Data {
try JSONSerialization.data(withJSONObject: json, options: [])
}
}
| 22 | 69 | 0.681818 |
f442875aad92fe533b63a136b6c83a3712bcb68a | 537 | //
// Host.swift
// HostsManager
//
// Created by wenyou on 2016/12/28.
// Copyright © 2016年 wenyou. All rights reserved.
//
import Foundation
class Host: NSObject {
var ip: String
var domain: String
override init() {
ip = ""
domain = ""
super.init()
}
convenience init(ip: String, domain: String) {
self.init()
self.ip = ip
self.domain = domain
}
func toString() -> String {
return "\(self.dictionaryWithValues(forKeys: allKeys()))"
}
}
| 16.272727 | 65 | 0.558659 |
d7d8f409979587b58e929054ff2d9d7a1f70c4bc | 237 | //
// User+CoreDataClass.swift
//
//
// Created by Vivek on 03/06/18.
//
//
import Foundation
import CoreData
@objc(User)
public class User: NSManagedObject {
class func checkUserExist(user: User) {
}
}
| 11.285714 | 43 | 0.603376 |
26b154af61e6cbe3a6692d542c7e4818c49955df | 184 | //
// BridgeChunk2D.swift
//
// Created by Zack Brown on 30/03/2021.
//
import Foundation
import Meadow
import SpriteKit
public class BridgeChunk2D: Chunk2D<BridgeTile2D> {
}
| 13.142857 | 51 | 0.717391 |
64f73b48cb02ca6ac919f6909b7fce984b567a4e | 3,337 | import IGListKit
import SwiftDate
final class TransactionBindingSC: ListBindingSectionController<SortedTransactionModelAlt> {
override init() {
super.init()
dataSource = self
selectionDelegate = self
supplementaryViewSource = self
}
}
// MARK: - ListBindingSectionControllerDataSource
extension TransactionBindingSC: ListBindingSectionControllerDataSource {
func sectionController(_ sectionController: ListBindingSectionController<ListDiffable>, viewModelsFor object: Any) -> [ListDiffable] {
guard let object = object as? SortedTransactionModelAlt else { return [] }
return object.transactions.transactionCellModels
}
func sectionController(_ sectionController: ListBindingSectionController<ListDiffable>, cellForViewModel viewModel: Any, at index: Int) -> UICollectionViewCell & ListBindable {
switch viewModel {
case is SortedSectionModel:
let cell: HeaderCell = collectionContext!.dequeueReusableCell(for: sectionController, at: index)
return cell
case is TransactionCellModel:
let cell: TransactionCell = collectionContext!.dequeueReusableCell(for: sectionController, at: index)
return cell
default:
fatalError()
}
}
func sectionController(_ sectionController: ListBindingSectionController<ListDiffable>, sizeForViewModel viewModel: Any, at index: Int) -> CGSize {
switch viewModel {
case is SortedSectionModel:
return .cellNode(height: 45)
case is TransactionCellModel:
return .cellNode(height: 85)
default:
return .cellNode(height: 40)
}
}
}
// MARK: - ListBindingSectionControllerSelectionDelegate
extension TransactionBindingSC: ListBindingSectionControllerSelectionDelegate {
func sectionController(_ sectionController: ListBindingSectionController<ListDiffable>, didSelectItemAt index: Int, viewModel: Any) {
guard let object = object, viewModel is TransactionCellModel else { return }
let transaction = object.transactions[index]
let controller = TransactionDetailVC(transaction: transaction)
collectionContext?.deselectItem(at: index, sectionController: sectionController, animated: true)
viewController?.navigationController?.pushViewController(controller, animated: true)
}
func sectionController(_ sectionController: ListBindingSectionController<ListDiffable>, didDeselectItemAt index: Int, viewModel: Any) {}
func sectionController(_ sectionController: ListBindingSectionController<ListDiffable>, didHighlightItemAt index: Int, viewModel: Any) {}
func sectionController(_ sectionController: ListBindingSectionController<ListDiffable>, didUnhighlightItemAt index: Int, viewModel: Any) {}
}
// MARK: - ListSupplementaryViewSource
extension TransactionBindingSC: ListSupplementaryViewSource {
func supportedElementKinds() -> [String] {
return [UICollectionView.elementKindSectionHeader]
}
func viewForSupplementaryElement(ofKind elementKind: String, at index: Int) -> UICollectionReusableView {
let view: HeaderView = collectionContext!.dequeueReusableSupplementaryView(ofKind: elementKind, forSectionController: self, atIndex: index)
view.dateText = object?.id.toString(.date(.medium))
return view
}
func sizeForSupplementaryView(ofKind elementKind: String, at index: Int) -> CGSize {
return .cellNode(height: 45)
}
}
| 41.197531 | 178 | 0.779742 |
69af106e1249661fc4a9457dc788cdc13a251c26 | 2,105 | //
// CaptureViewController.swift
// instagram
//
// Created by Vidhu Appalaraju on 9/26/18.
// Copyright © 2018 Vidhu Appalaraju. All rights reserved.
//
import UIKit
import Parse
class CaptureViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet weak var captionText: UITextField!
@IBOutlet weak var postImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [String : Any]) {
// Get the image captured by the UIImagePickerController
let originalImage = info[UIImagePickerControllerOriginalImage] as! UIImage
// Do something with the images (based on your use case)
postImageView.image = originalImage
// Dismiss UIImagePickerController to go back to your original view controller
dismiss(animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onSubmit(_ sender: Any) {
Post.postUserImage(image: postImageView.image, withCaption: captionText.text) { (success: Bool, error: Error?) in
print("whatever")
self.performSegue(withIdentifier: "postSegue", sender: nil)
}
}
@IBAction func onTap(_ sender: Any) {
let vc = UIImagePickerController()
vc.delegate = self
vc.allowsEditing = true
if UIImagePickerController.isSourceTypeAvailable(.camera) {
print("Camera is available 📸")
vc.sourceType = .camera
} else {
print("Camera 🚫 available so we will use photo library instead")
vc.sourceType = .photoLibrary
}
self.present(vc, animated: true, completion: nil)
}
}
| 31.41791 | 121 | 0.64038 |
dbad53c94b9d234bbd9fdef18bcb7a07f79519e5 | 821 | // File created from SimpleUserProfileExample
// $ createScreen.sh Room/UserSuggestion UserSuggestion
//
// Copyright 2021 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
struct UserSuggestionCoordinatorParameters {
let mediaManager: MXMediaManager
let room: MXRoom
}
| 32.84 | 75 | 0.761267 |
2ff2cac2d2812e22a562cbe6922c9cf932be5036 | 721 | //
// DogYearsPerformanceTests.swift
// DogYearsPerformanceTests
//
// Created by Igor Clemente on 07/04/20.
// Copyright © 2020 Razeware. All rights reserved.
//
import XCTest
@testable import DogYears
class DogYearsPerformanceTests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testPerformanceLoadMenu() {
var menu = Menu()
measure {
// Set average
menu.loadDefaultMenu()
}
}
}
| 23.258065 | 111 | 0.643551 |
7ad5b3e58a152188ea96c93b869459b2cc10bc3c | 531 | /* Multiple inheritance
*
* inheriting equitable and customStringConvertible
*
*/
class Person: CustomStringConvertible, Equatable{
var name:String
init(_ name:String){
self.name = name
}
public var description:String{
return self.name
}
}
func ==(_ p1:Person, _ p2: Person)->Bool{
return p1.name == p2.name
}
let yaser:Person = Person("Yaser")
let ehab:Person = Person("Ehab")
if yaser == ehab{
print("\(yaser) and \(ehab) are the same")
}
else{
print("\(yaser) and \(ehab) are not the same")
}
| 17.129032 | 51 | 0.661017 |
3963703c8529987ba0a7199b071d4b86061ec59c | 4,189 | //
// AppCoordinator.swift
// Fotos5
//
// Created by Gary Hanson on 5/17/19.
// Copyright © 2019 Gary Hanson. All rights reserved.
//
import UIKit
import Photos
final class AppCoordinator: NSObject, Coordinator, UINavigationControllerDelegate {
var childCoordinators = [Coordinator]()
var navigationController: UINavigationController
var _loggedIn = false
init(navigationController: UINavigationController) {
self.navigationController = navigationController
}
// initial call from AppDelegate to get things started
func start() {
if self.loggedIn() {
self.showContent()
} else {
self.showAuthentication()
}
}
// let authCoordinator handle login / sign-in
private func showAuthentication() {
let authCoordinator = AuthCoordinator(navigationController: self.navigationController)
self.childCoordinators.append(authCoordinator)
authCoordinator.coordinator = self
authCoordinator.start()
}
func didAuthenticate(coordinator: AuthCoordinator) {
self._loggedIn = true // real world generally requires a bit more effort
self.childCoordinators.removeAll { $0 === coordinator }
//self.childCoordinators.removeAll { type(of: $0) === type(of: coordinator) } // just another way to do this
self.showContent()
}
func menuDidSelectContentPage() {
self.showContent()
}
func menuDidSelectPhotosPage() {
self.showPhotosPage()
}
// show home page and handle callbacks to show different photo screens
private func showContent() {
let mainPage = ViewController.instantiate()
mainPage.coordinator = self
navigationController.viewControllers = [mainPage]
}
func didSelectDejaVuPhoto(assets: [PHAsset]) {
self.showPhotosGroupPage(assets: assets)
}
func didSelectDigestPhoto(assets: [PHAsset]) {
self.showPhotosGroupPage(assets: assets)
}
func didSelectCameraRollPhoto(photoIndex: Int) {
self.showPhotoLibraryPage(photoIndex: photoIndex)
}
private func showPhotosPage() {
let photosController = PhotosCollectionViewController.instantiate()
photosController.coordinator = self
self.navigationController.delegate = self
self.navigationController.pushViewController(photosController, animated: true)
}
private func showPhotosGroupPage(assets: [PHAsset]) {
let photosController = PhotosGroupCollectionViewController.instantiate()
photosController.coordinator = self
photosController.assets = assets
self.navigationController.delegate = self
self.navigationController.pushViewController(photosController, animated: true)
}
private func showPhotoLibraryPage(photoIndex: Int) {
let photoLibraryController = ImagePageViewController.instantiate()
photoLibraryController.coordinator = self
photoLibraryController.currentIndex = photoIndex
self.navigationController.delegate = self
self.navigationController.pushViewController(photoLibraryController, animated: true)
}
// local functionality
private func loggedIn() -> Bool { // probably need something a little better for real work
return self._loggedIn
}
// capture back button from nav controller
func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
guard let fromViewController = navigationController.transitionCoordinator?.viewController(forKey: .from) else {
return
}
// Check whether our view controller array already contains that view controller. If it does it means we’re pushing a different view controller on top rather than popping it, so exit.
if navigationController.viewControllers.contains(fromViewController) {
return
}
// Navigated back from signup page to onboarding page
}
}
| 33.246032 | 191 | 0.680353 |
148dd8bea2db168db75d5c8a6ca4e2eb6aef926e | 1,553 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Distributed Tracing open source project
//
// Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project
// authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2019 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import InstrumentationBaggage
func run(identifier: String) {
measure(identifier: identifier) {
var context = BaggageContext()
// static allocated strings
context[StringKey1.self] = String(repeating: "a", count: 30)
context[StringKey2.self] = String(repeating: "b", count: 12)
context[StringKey3.self] = String(repeating: "c", count: 20)
var numberDone = 1
for _ in 0 ..< 1000 {
let res = take1(context: context)
precondition(res == 42)
numberDone += 1
}
return 1
}
}
| 32.354167 | 80 | 0.524791 |
d501210407800dc94d6f5026576e1be45c2c8a31 | 8,799 | //
// Lexer.swift
// Teddy Compiler
//
// Created on 2/16/17.
// Copyright (c) 2017 Janum Trivedi (http://janumtrivedi.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
public typealias Operator = (String, Int)
public enum Token {
// MARK: - Keywords
case T_Function()
case T_Let()
case T_Var()
case T_Integer()
case T_Float()
case T_Void()
case T_String()
case T_Bool()
case T_Return()
case T_Print()
case T_Enum()
case T_Case()
case T_If()
// MARK: - Expressions
case T_Identifier(String)
case T_IntegerConstant(Int)
case T_FloatConstant(Float)
case T_BoolConstant(Bool)
case T_StringConstant(String)
// MARK: - Operators
case T_Equal()
case T_Operator(Operator)
// MARK: - Symbols
case T_Arrow()
case T_Colon()
case T_Semicolon()
case T_ParensOpen()
case T_ParensClose()
case T_BraceOpen()
case T_BraceClose()
case T_Comma()
case T_Period()
// MARK: - Properties
func rawTokenLength() -> Int {
switch self {
case .T_Function(): return 4 // func
case .T_Let(), .T_Var(): return 3 // let, var
case .T_Integer(): return 3 // int
case .T_Float(): return 5 // float
case .T_Bool(): return 4 // bool
case .T_String(): return 6 // string
case .T_Void(): return 4 // void
case .T_Return(): return 6 // return
case .T_Print(): return 5 // print
case .T_Enum(): return 4 // enum
case .T_Case(): return 4 // case
case .T_If(): return 2 // if
case .T_IntegerConstant(let value): return String(value).characters.count
case .T_FloatConstant(let value): return String(value).characters.count
case .T_BoolConstant(let value): return value ? 4 : 5 // true || flase
case .T_StringConstant(let value): return value.characters.count
case .T_Identifier(let value): return value.characters.count
case .T_Arrow(): return 2
case .T_Colon(), .T_Semicolon(): return 1
case .T_Equal(): return 1
case .T_Operator(_): return 1
case .T_ParensOpen(), .T_ParensClose(): return 1
case .T_BraceOpen(), .T_BraceClose(): return 1
case .T_Comma(): return 1
case .T_Period(): return 1
}
}
// MARK: - Failable init
init?(input: String) {
// MARK: - Whitespace
if let _ = input.match(regex: "[ \t\n]") {
return nil
}
// MARK: - Keywords
else if let _ = input.match(regex: "func") {
self = .T_Function()
}
else if let _ = input.match(regex: "let") {
self = .T_Let()
}
else if let _ = input.match(regex: "var") {
self = .T_Var()
}
else if let _ = input.match(regex: "Int") {
self = .T_Integer()
}
else if let _ = input.match(regex: "Float") {
self = .T_Float()
}
else if let _ = input.match(regex: "Void") {
self = .T_Void()
}
else if let _ = input.match(regex: "Bool") {
self = .T_Bool()
}
else if let _ = input.match(regex: "String") {
self = .T_String()
}
else if let _ = input.match(regex: "return") {
self = .T_Return()
}
else if let _ = input.match(regex: "print") {
self = .T_Print()
}
else if let _ = input.match(regex: "enum") {
self = .T_Enum()
}
else if let _ = input.match(regex: "case") {
self = .T_Case()
}
else if let _ = input.match(regex: "if") {
self = .T_If()
}
else if let _ = input.match(regex: "->") {
// Needs precedence over the minus opreator
self = .T_Arrow()
}
// MARK: - Arithmetic operators
else if let _ = input.match(regex: "\\=") {
self = .T_Equal()
}
else if let _ = input.match(regex: "\\+") {
self = .T_Operator(Operator("+", 20))
}
else if let _ = input.match(regex: "\\-") {
self = .T_Operator(Operator("-", 20))
}
else if let _ = input.match(regex: "\\*") {
self = .T_Operator(Operator("*", 40))
}
else if let _ = input.match(regex: "\\/") {
self = .T_Operator(Operator("/", 40))
}
// MARK: - Symbols
else if let _ = input.match(regex: "\\:") {
self = .T_Colon()
}
else if let _ = input.match(regex: "\\;") {
self = .T_Semicolon()
}
else if let _ = input.match(regex: "\\(") {
self = .T_ParensOpen()
}
else if let _ = input.match(regex: "\\)") {
self = .T_ParensClose()
}
else if let _ = input.match(regex: "\\{") {
self = .T_BraceOpen()
}
else if let _ = input.match(regex: "\\}") {
self = .T_BraceClose()
}
else if let _ = input.match(regex: "\\,") {
self = .T_Comma()
}
else if let _ = input.match(regex: "\\.") {
self = .T_Period()
}
// MARK: - Constants and identifiers
else if let match = input.match(regex: "true|false") {
guard let bool = Bool(match) else { return nil }
self = .T_BoolConstant(bool)
}
else if let match = input.match(regex: "[a-zA-Z][a-zA-Z0-9]*") {
self = .T_Identifier(match)
}
else if let match = input.match(regex: "[0-9]+\\.[0-9]*") {
guard let float = Float(match) else { return nil }
self = .T_FloatConstant(float)
}
else if let match = input.match(regex: "[0-9]+") {
guard let integer = Int(match) else { return nil }
self = .T_IntegerConstant(integer)
}
else if let match = input.match(regex: "\".*\"") {
guard let string = String(match) else { return nil }
self = .T_StringConstant(string)
}
else {
fatalError("Unable to match a valid token for input \"\(input)\"")
}
}
}
public struct Lexer {
public static func tokenize(input: String) -> [Token] {
var tokens = [Token]()
var content = input
while content.characters.count > 0 {
if let token = Token(input: content) {
tokens.append(token)
let stride = token.rawTokenLength()
let range = content.index(content.startIndex, offsetBy: stride)
content = content.substring(from: range)
continue
}
let index = content.index(after: content.startIndex)
content = content.substring(from: index)
}
return tokens
}
}
| 32.349265 | 87 | 0.494488 |
72cb2fdea0e44965def8a124246fec05c2719add | 2,548 | /// Cleanup.swift
///
/// Copyright 2018, The Silt Language Project.
///
/// This project is released under the MIT license, a copy of which is
/// available in the repository.
import Seismography
/// Manages a stack of cleanup values on a per-function basis.
final class CleanupStack {
typealias Handle = Int
private(set) var stack: [Cleanup] = []
init() {}
/// Push a particular cleanup of a value.
func pushCleanup(_ ty: Cleanup.Type, _ value: Value) -> CleanupStack.Handle {
self.stack.append(ty.init(value: value))
return self.stack.count - 1
}
/// Forward a given cleanup, disabling it in the process.
func forwardCleanup(_ handle: CleanupStack.Handle) {
precondition(handle >= 0, "invalid cleanup handle")
let cleanup = self.stack[handle]
assert(cleanup.state == .alive, "cannot forward dead cleanup")
cleanup.deactivateForForward()
}
/// Emit cleanups up to a given depth into a continuation.
func emitCleanups(
_ GGF: GIRGenFunction, in continuation: Continuation,
_ maxDepth: CleanupStack.Handle? = nil
) {
guard !self.stack.isEmpty else {
return
}
let depth = maxDepth ?? self.stack.count
for cleanup in self.stack.prefix(depth).reversed() {
guard cleanup.state == .alive else {
continue
}
cleanup.emit(GGF, in: continuation)
}
}
}
/// A cleanup represents a known way to reclaim resources for a managed value.
class Cleanup {
/// Enumerates the states that a cleanup can be in.
public enum State {
/// The cleanup is inactive.
case dead
/// The cleanup is active.
case alive
}
let value: Value
required init(value: Value) {
self.value = value
}
private(set) var state: State = .alive
fileprivate func deactivateForForward() {
self.state = .dead
}
/// Emit this cleanup into the provided continuation.
open func emit(_ GGF: GIRGenFunction, in cont: Continuation) {
fatalError("Abstract cleanup cannot be emitted")
}
}
final class DestroyValueCleanup: Cleanup {
override func emit(_ GGF: GIRGenFunction, in cont: Continuation) {
cont.appendCleanupOp(GGF.B.createDestroyValue(self.value))
}
}
final class DestroyAddressCleanup: Cleanup {
override func emit(_ GGF: GIRGenFunction, in cont: Continuation) {
cont.appendCleanupOp(GGF.B.createDestroyAddress(self.value))
}
}
final class DeallocaCleanup: Cleanup {
override func emit(_ GGF: GIRGenFunction, in cont: Continuation) {
cont.appendCleanupOp(GGF.B.createDealloca(self.value))
}
}
| 26.268041 | 79 | 0.6927 |
5b2375e1b0c0d6e89f97c598b9e6ab5e7a02ecd9 | 632 | //
// EnemyEntity.swift
// DatabaseSyncRx
//
// Created by Lobanov Aleksey on 17/10/2017.
// Copyright © 2017 Lobanov Aleksey. All rights reserved.
//
import Foundation
import ObjectMapper
struct EnemyModel: Mappable {
var id: Int = 0
var name: String?
var realName: String?
var heroes: [HeroModel]?
var abilities: [AbilityModel]?
var universe: UniverseModel?
init?(map: Map) {}
// Mappable
mutating func mapping(map: Map) {
id <- map["id"]
name <- map["name"]
realName <- map["real_name"]
heroes <- map["heroes"]
abilities <- map["abilities"]
universe <- map["universe"]
}
}
| 19.75 | 58 | 0.642405 |
8fa9c2f34d5d9428218fe613cf6eb940a0b8bb60 | 561 | //
// NestEgg+Errors.swift
// NestEgg
//
// Created by Ido Mizrachi on 2/6/18.
// Copyright © 2018 Ido Mizrachi. All rights reserved.
//
import Foundation
extension NestEgg {
private static func errorDomain() -> String {
return "com.idomizrachi.nestegg"
}
public static func releasedError() -> NSError {
return NSError(domain: self.errorDomain(), code: 1, userInfo: nil)
}
public static func notImageError() -> NSError {
return NSError(domain: self.errorDomain(), code: 2, userInfo: nil)
}
}
| 22.44 | 74 | 0.636364 |
876da5f2cc7a525496ca59de19cc54d69bec2d3c | 1,388 | import Foundation
//454. 4Sum II
//Given four integer arrays nums1, nums2, nums3, and nums4 all of length n, return the number of tuples (i, j, k, l) such that:
//
//0 <= i, j, k, l < n
//nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0
//
//
//Example 1:
//
//Input: nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2]
//Output: 2
//Explanation:
//The two tuples are:
//1. (0, 0, 0, 1) -> nums1[0] + nums2[0] + nums3[0] + nums4[1] = 1 + (-2) + (-1) + 2 = 0
//2. (1, 1, 0, 0) -> nums1[1] + nums2[1] + nums3[0] + nums4[0] = 2 + (-1) + (-1) + 0 = 0
//Example 2:
//
//Input: nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0]
//Output: 1
class Solution {
func fourSumCount(_ nums1: [Int], _ nums2: [Int], _ nums3: [Int], _ nums4: [Int]) -> Int {
var result: [Int: Int] = [:]
for number1 in nums1 {
for number2 in nums2 {
if let value = result[number1 + number2] {
result[number1 + number2] = value + 1
} else {
result[number1 + number2] = 1
}
}
}
var count = 0 // a + b + c + d = 0 出现次数
for number3 in nums3 {
for number4 in nums4 {
if let value = result[0 - (number3 + number4)] {
count += value
}
}
}
return count
}
}
| 29.531915 | 127 | 0.458213 |
0ac7fbe21baebf2e34cc370eb0c6cded9874c26f | 1,918 | //
// UIBarButtonItem+Combine.swift
// CombineCocoa
//
// Created by Daniel Tartaglia on 5/31/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if os(iOS) || os(tvOS)
import UIKit
import Combine
private var rx_tap_key: UInt8 = 0
@available(iOS 13.0, macOS 10.15, *)
extension Reactive where Base: UIBarButtonItem {
/// Reactive wrapper for target action pattern on `self`.
public var tap: ControlEvent<()> {
let source = lazyInstanceAnyPublisher(&rx_tap_key) { () -> AnyPublisher<(), Error> in
create { [weak control = self.base] observer in
guard let control = control else {
observer.receive(completion: .finished)
return AnyCancellable {}
}
let target = BarButtonItemTarget(barButtonItem: control) {
_ = observer.receive()
}
return target
}
.prefix(untilOutputFrom: self.deallocated)
.share()
.eraseToAnyPublisher()
}
return ControlEvent(events: source)
}
}
@objc
@available(iOS 13.0, macOS 10.15, *)
final class BarButtonItemTarget: CombineTarget {
typealias Callback = () -> Void
weak var barButtonItem: UIBarButtonItem?
var callback: Callback!
init(barButtonItem: UIBarButtonItem, callback: @escaping () -> Void) {
self.barButtonItem = barButtonItem
self.callback = callback
super.init()
barButtonItem.target = self
barButtonItem.action = #selector(BarButtonItemTarget.action(_:))
}
override func cancel() {
super.cancel()
#if DEBUG
DispatchQueue.ensureRunningOnMainThread()
#endif
barButtonItem?.target = nil
barButtonItem?.action = nil
callback = nil
}
@objc func action(_ sender: AnyObject) {
callback()
}
}
#endif
| 25.918919 | 93 | 0.604797 |
1acea4c73dac6fae8ab4fe553d61674a171847b1 | 228 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct B<h{struct A{enum S<T where g:B{}}func a<T where h:A | 45.6 | 87 | 0.754386 |
d65963996c5dbc567a12f8fadd008b0c9323a42f | 1,004 | //
// ChangeTimeCarelinMessageBodyTests.swift
// Naterade
//
// Created by Nathan Racklyeft on 3/17/16.
// Copyright © 2016 Nathan Racklyeft. All rights reserved.
//
import XCTest
@testable import MinimedKit
class ChangeTimeCarelinMessageBodyTests: XCTestCase {
func testChangeTime() {
var components = DateComponents()
components.calendar = Calendar(identifier: Calendar.Identifier.gregorian)
components.year = 2017
components.month = 12
components.day = 29
components.hour = 9
components.minute = 22
components.second = 59
let message = PumpMessage(packetType: .carelink, address: "123456", messageType: .changeTime, messageBody: ChangeTimeCarelinkMessageBody(dateComponents: components)!)
XCTAssertEqual(Data(hexadecimalString: "a7123456400709163B07E10C1D000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), message.txData)
}
}
| 31.375 | 207 | 0.737052 |
8fab4cd8228f0fc7e8e33156813d4eb6b867f958 | 1,412 | //
// PreworkUITests.swift
// PreworkUITests
//
// Created by Olivia Gillam on 2/26/21.
//
import XCTest
class PreworkUITests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// UI tests must launch the application that they test.
let app = XCUIApplication()
app.launch()
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testLaunchPerformance() throws {
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTApplicationLaunchMetric()]) {
XCUIApplication().launch()
}
}
}
}
| 32.837209 | 182 | 0.655099 |
2fb2572aac081818d975d941688705a19688a4b1 | 13,625 | //
// KingfisherOptionsInfo.swift
// Kingfisher
//
// Created by Wei Wang on 15/4/23.
//
// Copyright (c) 2017 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(macOS)
import AppKit
#else
import UIKit
#endif
/**
* KingfisherOptionsInfo is a typealias for [KingfisherOptionsInfoItem]. You can use the enum of option item with value to control some behaviors of Kingfisher.
*/
public typealias KingfisherOptionsInfo = [KingfisherOptionsInfoItem]
let KingfisherEmptyOptionsInfo = [KingfisherOptionsInfoItem]()
/**
Items could be added into KingfisherOptionsInfo.
*/
public enum KingfisherOptionsInfoItem {
/// The associated value of this member should be an ImageCache object. Kingfisher will use the specified
/// cache object when handling related operations, including trying to retrieve the cached images and store
/// the downloaded image to it.
case targetCache(ImageCache)
/// The associated value of this member should be an ImageDownloader object. Kingfisher will use this
/// downloader to download the images.
case downloader(ImageDownloader)
/// Member for animation transition when using UIImageView. Kingfisher will use the `ImageTransition` of
/// this enum to animate the image in if it is downloaded from web. The transition will not happen when the
/// image is retrieved from either memory or disk cache by default. If you need to do the transition even when
/// the image being retrieved from cache, set `ForceTransition` as well.
case transition(ImageTransition)
/// Associated `Float` value will be set as the priority of image download task. The value for it should be
/// between 0.0~1.0. If this option not set, the default value (`NSURLSessionTaskPriorityDefault`) will be used.
case downloadPriority(Float)
/// If set, `Kingfisher` will ignore the cache and try to fire a download task for the resource.
case forceRefresh
/// If set, setting the image to an image view will happen with transition even when retrieved from cache.
/// See `Transition` option for more.
case forceTransition
/// If set, `Kingfisher` will only cache the value in memory but not in disk.
case cacheMemoryOnly
/// If set, `Kingfisher` will only try to retrieve the image from cache not from network.
case onlyFromCache
/// Decode the image in background thread before using.
case backgroundDecode
/// The associated value of this member will be used as the target queue of dispatch callbacks when
/// retrieving images from cache. If not set, `Kingfisher` will use main quese for callbacks.
case callbackDispatchQueue(DispatchQueue?)
/// The associated value of this member will be used as the scale factor when converting retrieved data to an image.
/// It is the image scale, instead of your screen scale. You may need to specify the correct scale when you dealing
/// with 2x or 3x retina images.
case scaleFactor(CGFloat)
/// Whether all the animated image data should be preloaded. Default it false, which means following frames will be
/// loaded on need. If true, all the animated image data will be loaded and decoded into memory. This option is mainly
/// used for back compatibility internally. You should not set it directly. `AnimatedImageView` will not preload
/// all data, while a normal image view (`UIImageView` or `NSImageView`) will load all data. Choose to use
/// corresponding image view type instead of setting this option.
case preloadAllAnimationData
/// The `ImageDownloadRequestModifier` contained will be used to change the request before it being sent.
/// This is the last chance you can modify the request. You can modify the request for some customizing purpose,
/// such as adding auth token to the header, do basic HTTP auth or something like url mapping. The original request
/// will be sent without any modification by default.
case requestModifier(ImageDownloadRequestModifier)
/// Processor for processing when the downloading finishes, a processor will convert the downloaded data to an image
/// and/or apply some filter on it. If a cache is connected to the downloader (it happenes when you are using
/// KingfisherManager or the image extension methods), the converted image will also be sent to cache as well as the
/// image view. `DefaultImageProcessor.default` will be used by default.
case processor(ImageProcessor)
/// Supply an `CacheSerializer` to convert some data to an image object for
/// retrieving from disk cache or vice versa for storing to disk cache.
/// `DefaultCacheSerializer.default` will be used by default.
case cacheSerializer(CacheSerializer)
/// Keep the existing image while setting another image to an image view.
/// By setting this option, the placeholder image parameter of imageview extension method
/// will be ignored and the current image will be kept while loading or downloading the new image.
case keepCurrentImageWhileLoading
/// If set, Kingfisher will only load the first frame from a animated image data file as a single image.
/// Loading a lot of animated images may take too much memory. It will be useful when you want to display a
/// static preview of the first frame from a animated image.
/// This option will be ignored if the target image is not animated image data.
case onlyLoadFirstFrame
/// If set and an `ImageProcessor` is used, Kingfisher will try to cache both
/// the final result and original image. Kingfisher will have a chance to use
/// the original image when another processor is applied to the same resouce,
/// instead of downloading it again.
case cacheOriginalImage
}
precedencegroup ItemComparisonPrecedence {
associativity: none
higherThan: LogicalConjunctionPrecedence
}
infix operator <== : ItemComparisonPrecedence
// This operator returns true if two `KingfisherOptionsInfoItem` enum is the same, without considering the associated values.
func <== (lhs: KingfisherOptionsInfoItem, rhs: KingfisherOptionsInfoItem) -> Bool {
switch (lhs, rhs) {
case (.targetCache(_), .targetCache(_)): return true
case (.downloader(_), .downloader(_)): return true
case (.transition(_), .transition(_)): return true
case (.downloadPriority(_), .downloadPriority(_)): return true
case (.forceRefresh, .forceRefresh): return true
case (.forceTransition, .forceTransition): return true
case (.cacheMemoryOnly, .cacheMemoryOnly): return true
case (.onlyFromCache, .onlyFromCache): return true
case (.backgroundDecode, .backgroundDecode): return true
case (.callbackDispatchQueue(_), .callbackDispatchQueue(_)): return true
case (.scaleFactor(_), .scaleFactor(_)): return true
case (.preloadAllAnimationData, .preloadAllAnimationData): return true
case (.requestModifier(_), .requestModifier(_)): return true
case (.processor(_), .processor(_)): return true
case (.cacheSerializer(_), .cacheSerializer(_)): return true
case (.keepCurrentImageWhileLoading, .keepCurrentImageWhileLoading): return true
case (.onlyLoadFirstFrame, .onlyLoadFirstFrame): return true
case (.cacheOriginalImage, .cacheOriginalImage): return true
default: return false
}
}
extension Collection where Iterator.Element == KingfisherOptionsInfoItem {
func lastMatchIgnoringAssociatedValue(_ target: Iterator.Element) -> Iterator.Element? {
return reversed().first { $0 <== target }
}
func removeAllMatchesIgnoringAssociatedValue(_ target: Iterator.Element) -> [Iterator.Element] {
return filter { !($0 <== target) }
}
}
public extension Collection where Iterator.Element == KingfisherOptionsInfoItem {
/// The target `ImageCache` which is used.
public var targetCache: ImageCache {
if let item = lastMatchIgnoringAssociatedValue(.targetCache(.default)),
case .targetCache(let cache) = item
{
return cache
}
return ImageCache.default
}
/// The `ImageDownloader` which is specified.
public var downloader: ImageDownloader {
if let item = lastMatchIgnoringAssociatedValue(.downloader(.default)),
case .downloader(let downloader) = item
{
return downloader
}
return ImageDownloader.default
}
/// Member for animation transition when using UIImageView.
public var transition: ImageTransition {
if let item = lastMatchIgnoringAssociatedValue(.transition(.none)),
case .transition(let transition) = item
{
return transition
}
return ImageTransition.none
}
/// A `Float` value set as the priority of image download task. The value for it should be
/// between 0.0~1.0.
public var downloadPriority: Float {
if let item = lastMatchIgnoringAssociatedValue(.downloadPriority(0)),
case .downloadPriority(let priority) = item
{
return priority
}
return URLSessionTask.defaultPriority
}
/// Whether an image will be always downloaded again or not.
public var forceRefresh: Bool {
return contains{ $0 <== .forceRefresh }
}
/// Whether the transition should always happen or not.
public var forceTransition: Bool {
return contains{ $0 <== .forceTransition }
}
/// Whether cache the image only in memory or not.
public var cacheMemoryOnly: Bool {
return contains{ $0 <== .cacheMemoryOnly }
}
/// Whether only load the images from cache or not.
public var onlyFromCache: Bool {
return contains{ $0 <== .onlyFromCache }
}
/// Whether the image should be decoded in background or not.
public var backgroundDecode: Bool {
return contains{ $0 <== .backgroundDecode }
}
/// Whether the image data should be all loaded at once if it is an animated image.
public var preloadAllAnimationData: Bool {
return contains { $0 <== .preloadAllAnimationData }
}
/// The queue of callbacks should happen from Kingfisher.
public var callbackDispatchQueue: DispatchQueue {
if let item = lastMatchIgnoringAssociatedValue(.callbackDispatchQueue(nil)),
case .callbackDispatchQueue(let queue) = item
{
return queue ?? DispatchQueue.main
}
return DispatchQueue.main
}
/// The scale factor which should be used for the image.
public var scaleFactor: CGFloat {
if let item = lastMatchIgnoringAssociatedValue(.scaleFactor(0)),
case .scaleFactor(let scale) = item
{
return scale
}
return 1.0
}
/// The `ImageDownloadRequestModifier` will be used before sending a download request.
public var modifier: ImageDownloadRequestModifier {
if let item = lastMatchIgnoringAssociatedValue(.requestModifier(NoModifier.default)),
case .requestModifier(let modifier) = item
{
return modifier
}
return NoModifier.default
}
/// `ImageProcessor` for processing when the downloading finishes.
public var processor: ImageProcessor {
if let item = lastMatchIgnoringAssociatedValue(.processor(DefaultImageProcessor.default)),
case .processor(let processor) = item
{
return processor
}
return DefaultImageProcessor.default
}
/// `CacheSerializer` to convert image to data for storing in cache.
public var cacheSerializer: CacheSerializer {
if let item = lastMatchIgnoringAssociatedValue(.cacheSerializer(DefaultCacheSerializer.default)),
case .cacheSerializer(let cacheSerializer) = item
{
return cacheSerializer
}
return DefaultCacheSerializer.default
}
/// Keep the existing image while setting another image to an image view.
/// Or the placeholder will be used while downloading.
public var keepCurrentImageWhileLoading: Bool {
return contains { $0 <== .keepCurrentImageWhileLoading }
}
public var onlyLoadFirstFrame: Bool {
return contains { $0 <== .onlyLoadFirstFrame }
}
public var cacheOriginalImage: Bool {
return contains { $0 <== .cacheOriginalImage }
}
}
| 44.093851 | 159 | 0.701578 |
e04273e556ce3042796466160baa81e686c6a68c | 423 | //
// CSText.swift
// ComponentStudio
//
// Created by devin_abbott on 8/3/17.
// Copyright © 2017 Devin Abbott. All rights reserved.
//
import Foundation
import AppKit
class CSTextView: NSTextView, CSRendering {
override func hitTest(_ point: NSPoint) -> NSView? {
return nil
}
override var alphaValue: CGFloat {
get {
return multipliedAlpha
}
set {}
}
}
| 17.625 | 56 | 0.614657 |
5686a58fc5cc64376b48f847baa7d15a5c09c412 | 7,175 | //
// PickerViewSetupTests.swift
// PickerViewKit_Tests
//
// Created by crelies on 18.03.18.
// Copyright © 2018 Christian Elies. All rights reserved.
//
@testable import PickerViewKit
import Foundation
import Nimble
import Quick
final class PickerViewSetupTests: QuickSpec {
override func spec() {
describe("PickerViewSetup") {
context("when initializing with picker view and type") {
let pickerView = UIPickerView()
let row = PickerViewRow(type: .plain(title: "Mock"))
let column = PickerViewColumn(rows: [row])
var setup: PickerViewSetup?
do {
setup = try PickerViewSetup(pickerView: pickerView, type: .single(column: column))
} catch {
fail("Could not create PickerViewSetup")
}
it("should have picker view") {
expect(setup?.pickerView) == pickerView
}
it("should have picker view type") {
expect(setup?.pickerViewType) == .singleColumn
}
it("should have columns") {
expect(setup?.columns.count) == 1
}
it("should have no callback") {
expect(setup?.callback).to(beNil())
}
it("should have default column width") {
expect(setup?.defaultColumnWidth) == 48
}
it("should have default row height") {
expect(setup?.defaultRowHeight) == 48
}
}
context("when initializing with picker view, type and callback") {
let pickerView = UIPickerView()
let row = PickerViewRow(type: .plain(title: "Mock"))
let column = PickerViewColumn(rows: [row])
var setup: PickerViewSetup?
do {
setup = try PickerViewSetup(pickerView: pickerView, type: .single(column: column))
} catch {
fail("Could not create PickerViewSetup")
}
it("should have picker view") {
expect(setup?.pickerView) == pickerView
}
it("should have picker view type") {
expect(setup?.pickerViewType) == .singleColumn
}
it("should have columns") {
expect(setup?.columns.count) == 1
}
it("should have callback") {
let callback = MockPickerViewDelegateCallback()
setup?.callback = callback
expect(setup?.callback).toNot(beNil())
}
it("should have default column width") {
expect(setup?.defaultColumnWidth) == 48
}
it("should have default row height") {
expect(setup?.defaultRowHeight) == 48
}
}
context("when initializing with picker view, type, callback and defaultColumnWidth") {
let pickerView = UIPickerView()
let row = PickerViewRow(type: .plain(title: "Mock"))
let column = PickerViewColumn(rows: [row])
var setup: PickerViewSetup?
do {
setup = try PickerViewSetup(pickerView: pickerView, type: .single(column: column), defaultColumnWidth: 96)
} catch {
fail("Could not create PickerViewSetup")
}
it("should have picker view") {
expect(setup?.pickerView) == pickerView
}
it("should have picker view type") {
expect(setup?.pickerViewType) == .singleColumn
}
it("should have columns") {
expect(setup?.columns.count) == 1
}
it("should have callback") {
let callback = MockPickerViewDelegateCallback()
setup?.callback = callback
expect(setup?.callback).toNot(beNil())
}
it("should have custom default column width") {
expect(setup?.defaultColumnWidth) == 96
}
it("should have default row height") {
expect(setup?.defaultRowHeight) == 48
}
}
context("when initializing with picker view, type, callback, defaultColumnWidth and defaultRowHeight") {
let pickerView = UIPickerView()
let row = PickerViewRow(type: .plain(title: "Mock"))
let column = PickerViewColumn(rows: [row])
var setup: PickerViewSetup?
do {
setup = try PickerViewSetup(pickerView: pickerView, type: .single(column: column), defaultColumnWidth: 128, defaultRowHeight: 56)
} catch {
fail("Could not create PickerViewSetup")
}
it("should have picker view") {
expect(setup?.pickerView) == pickerView
}
it("should have picker view type") {
expect(setup?.pickerViewType) == .singleColumn
}
it("should have columns") {
expect(setup?.columns.count) == 1
}
it("should have callback") {
let callback = MockPickerViewDelegateCallback()
setup?.callback = callback
expect(setup?.callback).toNot(beNil())
}
it("should have custom default column width") {
expect(setup?.defaultColumnWidth) == 128
}
it("should have custom default row height") {
expect(setup?.defaultRowHeight) == 56
}
}
context("when initializing with key value type and 3 columns") {
it("should throw wrong number of columns error") {
let pickerView = UIPickerView()
let row = PickerViewRow(type: .plain(title: "Mock"))
let column1 = PickerViewColumn(rows: [row])
let column2 = PickerViewColumn(rows: [row])
let column3 = PickerViewColumn(rows: [row])
do {
let _ = try PickerViewSetup(pickerView: pickerView, type: .keyValue(columns: [column1, column2, column3]))
fail("No error thrown")
} catch {
let err = error as? PickerViewSetupError
expect(err).toNot(beNil())
}
}
}
}
}
}
| 38.368984 | 149 | 0.469686 |
01bf7ffd96196ad63a5c39d6ec4bf60a640e708d | 1,322 | //
// AddressMaskView.swift
// TianMaUser
//
// Created by Healson on 2018/8/6.
// Copyright © 2018 YH. All rights reserved.
//
import UIKit
class AddressMaskView: UIView {
var sureDelete: (() -> Void)?
override func awakeFromNib() {
super.awakeFromNib()
self.backgroundColor = UIColor.black.withAlphaComponent(0.4)
UIApplication.shared.keyWindow?.rootViewController?.view.addSubview(self)
self.alpha = 0
}
// MARK: - XIB View
public class func maskView() -> Any? {
return bundle(self).loadNibNamed(String(describing: self), owner: nil, options: nil)?.last
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
diss()
}
public func show() {
maskViewAnimail(isShow: true)
}
public func diss() {
maskViewAnimail(isShow: false)
}
private func maskViewAnimail(isShow: Bool) {
let alpha: CGFloat = isShow ? 1 : 0
UIView.animate(withDuration: 0.3, animations: {
self.alpha = alpha
})
}
@IBAction func action_sure() {
if let click = sureDelete {
click()
diss()
}
}
@IBAction func action_cancel() {
diss()
}
}
| 21.322581 | 98 | 0.56354 |
f9e8f13432ecf6d4a1fcd9e4948d3037b4a448b3 | 8,318 | // Copyright 2019 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import CTensorFlow
import XCTest
@testable import TensorFlow
final class LazyTensorTFFunctionBuilderTests: LazyTensorTestCase {
func testSingletonInputs() {
let a = materializedLazyTensor(Tensor<Float>(10.0))
let w = _Raw.identity(a)
XCTAssertEqual(
tfFunction(w, "testSingletonInputs")!.description,
"""
testSingletonInputs(placeholder_0:float) -> (identity_1:float) {
Identity_1 = Identity[T=float](placeholder_0)
return identity_1 = Identity_1:output:0
}
""")
}
func testListInputs() {
let a = materializedLazyTensor(Tensor<Float>(10.0))
let b = materializedLazyTensor(Tensor<Float>(2.0))
let w = _Raw.addN(inputs: [a, b])
XCTAssertEqual(
tfFunction(w, "testListInputs")!.description,
"""
testListInputs(placeholder_0:float, placeholder_1:float) -> (addn_2:float) {
AddN_2 = AddN[N=2, T=float](placeholder_0, placeholder_1)
return addn_2 = AddN_2:sum:0
}
""")
}
func testSequence() {
let a = materializedLazyTensor(Tensor<Float>(10.0))
let b = materializedLazyTensor(Tensor<Float>(2.0))
let c = materializedLazyTensor(Tensor<Float>(3.0))
let w = a + b * c
XCTAssertEqual(
tfFunction(w, "sequence")!.description,
"""
sequence(placeholder_0:float, placeholder_1:float, placeholder_2:float) -> (addv2_4:float) {
Mul_3 = Mul[T=float](placeholder_1, placeholder_2)
AddV2_4 = AddV2[T=float](placeholder_0, Mul_3:z:0)
return addv2_4 = AddV2_4:z:0
}
""")
}
func testAttributes() {
// If tests ops such as "AttrBool" are available, testing the handing of
// attributes would be very simple. However, tests ops are not
// registered into the runtime by default (which is reasonable). If it
// is possible to get a test-only libtensorflow.so, we should simplify
// this test usinge the test ops.
let a = materializedLazyTensor(Tensor<Float>(10.0))
let b = materializedLazyTensor(Tensor<Float>(20.0))
// Bool attribute
let boolAttr = LazyTensorOperation("MatrixInverse", 1)
boolAttr.updateAttribute("adjoint", true)
boolAttr.addInput(a)
XCTAssertEqual(
tfFunction(boolAttr, "boolAttr").description,
"""
boolAttr(placeholder_0:float) -> () {
MatrixInverse_1 = MatrixInverse[T=float, adjoint=true](placeholder_0)
}
""")
// Int attribute
let intAttr = LazyTensorOperation("Unpack", 1)
intAttr.updateAttribute("axis", 0)
intAttr.updateAttribute("num", 1)
intAttr.updateAttribute("T", Float.tensorFlowDataType)
intAttr.addInput(a)
XCTAssertEqual(
tfFunction(intAttr, "intAttr").description,
"""
intAttr(placeholder_0:float) -> () {
Unpack_1 = Unpack[T=float, axis=0, num=1](placeholder_0)
}
""")
// Float attribute
let floatAttr = LazyTensorOperation("ApproximateEqual", 1)
floatAttr.updateAttribute("T", Float.tensorFlowDataType)
floatAttr.updateAttribute("tolerance", 0.01)
floatAttr.addInput(a)
floatAttr.addInput(b)
XCTAssertEqual(
tfFunction(floatAttr, "floatAttr").description,
"""
floatAttr(placeholder_0:float, placeholder_1:float) -> () {
ApproximateEqual_2 = ApproximateEqual[T=float, tolerance=0.01](placeholder_0, placeholder_1)
}
""")
// String attribute
let stringAttr = LazyTensorOperation("PrintV2", 0)
let tag = StringTensor("Hello!")
stringAttr.updateAttribute("output_stream", "stream")
stringAttr.addInput(tag)
XCTAssertEqual(
tfFunction(stringAttr, "stringAttr").description,
"""
stringAttr() -> () {
Const_0 = Const[dtype=string, value=Tensor<type: string shape: [] values: Hello!>]()
PrintV2_1 = PrintV2[end=\"\\n\", output_stream=\"stream\"](Const_0:output:0)
}
""")
// TensorShape attr
let shapeAttr = LazyTensorOperation("EnsureShape", 1)
shapeAttr.updateAttribute("shape", TensorShape([5, 6]))
shapeAttr.updateAttribute("T", Float.tensorFlowDataType)
shapeAttr.addInput(a)
XCTAssertEqual(
tfFunction(shapeAttr, "shapeAttr").description,
"""
shapeAttr(placeholder_0:float) -> () {
EnsureShape_1 = EnsureShape[T=float, shape=[5,6]](placeholder_0)
}
""")
// [Int], [TensorShape?] & [TensorDataType] attribute.
let arrayAttr1 = LazyTensorOperation("PrelinearizeTuple", 0)
arrayAttr1.updateAttribute(
"dtypes",
[Float.tensorFlowDataType, Float.tensorFlowDataType]) // [TensorDataType]
arrayAttr1.updateAttribute("shapes", [[1, 2], nil]) // [TensorShape?]
arrayAttr1.updateAttribute("layouts", [3, 4]) // [Int]
arrayAttr1.addInputList([a, b])
XCTAssertEqual(
tfFunction(arrayAttr1, "arrayAttr1").description,
"""
arrayAttr1(placeholder_0:float, placeholder_1:float) -> () {
PrelinearizeTuple_2 = PrelinearizeTuple[dtypes={float, float}, layouts=[3, 4], shapes=[[1,2], <unknown>]](placeholder_0, placeholder_1)
}
""")
// Const Tensor attribute.
let constTensorAttr = LazyTensorOperation("Const", 0)
let x = Tensor<Float>(5.5)
constTensorAttr.updateAttribute("dtype", Float.tensorFlowDataType)
constTensorAttr.updateAttribute("value", x.handle.handle._tfeTensorHandle)
XCTAssertEqual(
tfFunction(constTensorAttr, "constTensorAttr").description,
"""
constTensorAttr() -> () {
Const_0 = Const[dtype=float, value=Tensor<type: float shape: [] values: 5.5>]()
}
""")
// TensorFunctionPointer attribute.
let statelessWhile = LazyTensorOperation("StatelessWhile", 1)
statelessWhile.updateAttribute("T", [Float.tensorFlowDataType])
statelessWhile.updateAttribute("cond", _TensorFunctionPointer(name: "cond"))
statelessWhile.updateAttribute("body", _TensorFunctionPointer(name: "body"))
statelessWhile.addInputList([a])
XCTAssertEqual(
tfFunction(statelessWhile, "statelessWhile").description,
"""
statelessWhile(placeholder_0:float) -> () {
StatelessWhile_1 = StatelessWhile[T={float}, body=body, cond=cond, output_shapes=[], parallel_iterations=10](placeholder_0)
}
""")
}
private func tfFunction(
_ lazyOp: LazyTensorOperation,
_ name: String? = nil
) -> TFFunction {
return TFFunction(trace: lazyTensorTrace(lazyOp), name: name)
}
private func materializedLazyTensor<T: TensorFlowScalar>(
_ input: Tensor<T>
) -> Tensor<T> {
let concreteHandle = input.handle.handle._tfeTensorHandle
let materializedHandle = LazyTensorHandle(_materialized: concreteHandle)
return Tensor(handle: TensorHandle<T>(handle: materializedHandle))
}
private func tfFunction<T: TensorFlowScalar>(
_ input: Tensor<T>,
_ name: String? = nil
) -> TFFunction? {
let tensor = input.handle.handle
guard let lazyTensor = tensor as? LazyTensorHandle else {
XCTFail("Trying to get TFFunction for a non-lazy tensor.")
return nil
}
guard case let .symbolic(lazyOp, _, _) = lazyTensor.handle else {
XCTFail("Cannot get TFFunction for a concrete tensor.")
return nil
}
return TFFunction(trace: lazyTensorTrace(lazyOp), name: name)
}
private func lazyTensorTrace(_ lazyOp: LazyTensorOperation) -> LazyTensorTrace {
let traceInfo = LazyTensorTraceBuilder.materializationTraceInfo(lazyOp)
return traceInfo.trace
}
static var allTests = [
("testSingletonInputs", testSingletonInputs),
("testListInputs", testListInputs),
("testSequence", testSequence),
("testAttributes", testAttributes),
]
}
| 33.007937 | 143 | 0.676244 |
14429a005d9a8aa973976ae9a4a0847c28d05718 | 449 | //
// LaunchTimePlugin.swift
// DoraemonKit-Swift
//
// Created by objc on 2020/5/29.
//
import Foundation
import UIKit
struct LaunchTimePlugin: Plugin {
var module: PluginModule { .performance }
var title: String { LocalizedString("启动耗时") }
var icon: UIImage? { DKImage(named: "doraemon_app_start_time") }
func onSelected() {
let vc = LaunchTimeViewController()
HomeWindow.shared.openPlugin(vc: vc)
}
}
| 18.708333 | 68 | 0.670379 |
23c1b1380fcf3738496507297c2dd8de343ea756 | 53,650 | //
// Attribute.swift
// Asset Catalog Viewer
//
// Copyright © 2021 Joey. All rights reserved.
//
/// Rendition Attributes.
enum Attribute {
/// ThemeSize
enum Size: UInt16 {
/// kCoreThemeSizeRegular
case Regular = 0
/// kCoreThemeSizeSmall
case Small = 1
/// kCoreThemeSizeMini
case Mini = 2
/// kCoreThemeSizeLarge
case Large = 3
}
/// ThemeDirection
enum Direction: UInt16 {
/// kCoreThemeDirectionHorizontal
case Horizontal = 0
/// kCoreThemeDirectionVertical
case Vertical = 1
/// kCoreThemeDirectionPointingUp
case PointingUp = 2
/// kCoreThemeDirectionPointingDown
case PointingDown = 3
/// kCoreThemeDirectionPointingLeft
case PointingLeft = 4
/// kCoreThemeDirectionPointingRight
case PointingRight = 5
}
/// ThemeValue
enum Value: UInt16 {
/// kCoreThemeValueOff
case Off = 0
/// kCoreThemeValueOn
case On = 1
/// kCoreThemeValueMixed
case Mixed = 2
}
/// ThemeState
enum State: UInt16 {
/// kCoreThemeStateNormal
case Normal = 0
/// kCoreThemeStateRollover
case Rollover = 1
/// kCoreThemeStatePressed
case Pressed = 2
/// obsolete_kCoreThemeStateInactive
case Inactive = 3
/// kCoreThemeStateDisabled
case Disabled = 4
/// kCoreThemeStateDeeplyPressed
case DeeplyPressed = 5
}
/// ThemePresentationState
enum PresentationState: UInt16 {
/// kCoreThemePresentationStateActive
case Active = 0
/// kCoreThemePresentationStateInactive
case Inactive = 1
/// kCoreThemePresentationStateActiveMain
case Main = 2
}
/// ThemeDrawingLayer
enum Layer: UInt16 {
/// kCoreThemeLayerBase
case Base = 0
/// kCoreThemeLayerHighlight
case Highlight = 1
/// kCoreThemeLayerMask
case Mask = 2
/// kCoreThemeLayerPulse
case Pulse = 3
/// kCoreThemeLayerHitMask
case HitMask = 4
/// kCoreThemeLayerPatternOverlay
case PatternOverlay = 5
/// kCoreThemeLayerOutline
case Outline = 6
/// kCoreThemeLayerInterior
case Interior = 7
}
/// ThemeScale
enum Scale: UInt16 {
/// Universal scale factor.
case Universal = 0
/// @1x scale factor.
case x1 = 1
/// @2x scale factor.
case x2 = 2
/// @3x scale factor.
case x3 = 3
/// Returns the name of the scale factor enum case.
var string: String {
switch self {
case .Universal: return "Universal"
case .x1: return "1x"
case .x2: return "2x"
case .x3: return "3x"
}
}
}
/// ThemeIdiom
enum Idiom: UInt16 {
/// kCoreThemeIdiomUniversal
case Universal = 0
/// kCoreThemeIdiomPhone
case iPhone = 1
/// kCoreThemeIdiomPad
case iPad = 2
/// kCoreThemeIdiomTV
case AppleTV = 3
/// kCoreThemeIdiomCar
case CarPlay = 4
/// kCoreThemeIdiomWatch
case AppleWatch = 5
/// kCoreThemeIdiomMarketing
case Marketing = 6
/// kCoreThemeIdiomMac
case Mac = 7
}
/// ThemeUISizeClass
enum SizeClass: UInt16 {
/// kCoreThemeUISizeClassUnspecified
case Universal = 0
/// kCoreThemeUISizeClassCompact
case Compact = 1
/// kCoreThemeUISizeClassRegular
case Regular = 2
}
/// ThemeMemoryClass
enum Memory: UInt16 {
/// kCoreThemeMemoryClassLow
case `Any` = 0
/// kCoreThemeMemoryClass1GB
case Class1GB = 1
/// kCoreThemeMemoryClass2GB
case Class2GB = 2
/// kCoreThemeMemoryClass4GB
case Class4GB = 3
/// kCoreThemeMemoryClass3GB
case Class3GB = 4
/// kCoreThemeMemoryClass6GB
case Class6GB = 6
/// kCoreThemeMemoryClass8GB
case Class8GB = 8
/// kCoreThemeMemoryClass16GB
case Class16GB = 16
/// Returns the name of the memory class enum case.
var string: String {
switch self {
case .Any: return "Any Memory"
case .Class1GB: return "1 GB"
case .Class2GB: return "2 GB"
case .Class4GB: return "4 GB"
case .Class3GB: return "3 GB"
case .Class6GB: return "6 GB"
case .Class8GB: return "8 GB"
case .Class16GB: return "16 GB"
}
}
}
/// ThemeGraphicsFeatureSetClass
enum Graphics: UInt16 {
/// kCoreThemeFeatureSetOpenGLES2 / GLES2,0
case OpenGLES2 = 0
/// kCoreThemeFeatureSetMetalGPUFamily1 / APPLE1
case MetalGPUFamily1 = 1
/// kCoreThemeFeatureSetMetalGPUFamily2 / APPLE2
case MetalGPUFamily2 = 2
/// kCoreThemeFeatureSetMetalGPUFamily3_Deprecated / APPLE3v1
case MetalGPUFamily3_Deprecated = 3
/// kCoreThemeFeatureSetMetalGPUFamily3 / APPLE3
case MetalGPUFamily3 = 4
/// kCoreThemeFeatureSetMetalGPUFamily4 / APPLE4
case MetalGPUFamily4 = 5
/// kCoreThemeFeatureSetMetalGPUFamily5 / APPLE5
case MetalGPUFamily5 = 6
/// kCoreThemeFeatureSetMetalGPUFamily6 / APPLE6
case MetalGPUFamily6 = 7
/// kCoreThemeFeatureSetMetalGPUFamily7 / APPLE7
case MetalGPUFamily7 = 8
}
/// ThemeDisplayGamut
enum Gamut: UInt16 {
/// kCoreThemeDisplayGamutSRGB
case sRGB = 0
/// kCoreThemeDisplayGamutP3
case P3 = 1
}
/// ThemeDeploymentTarget
enum Target: UInt16 {
/// kCoreThemeDeploymentTargetAny
case TargetAny = 0
/// kCoreThemeDeploymentTarget2016
case Target2016 = 1
/// kCoreThemeDeploymentTarget2017
case Target2017 = 2
/// kCoreThemeDeploymentTarget2018
case Target2018 = 3
/// kCoreThemeDeploymentTarget2018Plus
case Target2018Plus = 4
/// kCoreThemeDeploymentTarget2019
case Target2019 = 5
/// kCoreThemeDeploymentTarget2020
case Target2020 = 6
}
/// ThemeGlyphWeight
enum GlyphWeight: UInt16 {
/// kCoreThemeVectorGlyphWeightNone
case None = 0
/// kCoreThemeVectorGlyphWeightUltralight
case Ultralight = 1
/// kCoreThemeVectorGlyphWeightThin
case Thin = 2
/// kCoreThemeVectorGlyphWeightLight
case Light = 3
/// kCoreThemeVectorGlyphWeightRegular
case Regular = 4
/// kCoreThemeVectorGlyphWeightMedium
case Medium = 5
/// kCoreThemeVectorGlyphWeightSemibold
case Semibold = 6
/// kCoreThemeVectorGlyphWeightBold
case Bold = 7
/// kCoreThemeVectorGlyphWeightHeavy
case Heavy = 8
/// kCoreThemeVectorGlyphWeightBlack
case Black = 9
}
/// ThemeGlyphSize
enum GlyphSize: UInt16 {
/// kCoreThemeVectorGlyphSizeNone
case None = 0
/// kCoreThemeVectorGlyphSizeSmall
case Small = 1
/// kCoreThemeVectorGlyphSizeMedium
case Medium = 2
/// kCoreThemeVectorGlyphSSizeLarge
case Large = 3
}
/// ThemeElement
enum Element: UInt16 {
/// kCoreThemeCheckBoxID - CheckBox
case CheckBox = 1
/// kCoreThemeRadioButtonID - Radio Button
case RadioButton = 2
/// kCoreThemePushButtonID - Push Button
case PushButton = 3
/// kCoreThemeBevelButtonGradientID - Bevel Button Gradient
case BevelButtonGradient = 4
/// kCoreThemeBevelButtonRoundID - Bevel Button Round
case BevelButtonRound = 5
/// kCoreThemeDisclosureButtonID - Disclosure Button
case DisclosureButton = 6
/// kCoreThemeComboBoxButtonID - Combo Box Button
case ComboBoxButton = 7
/// kCoreThemeTabButtonID - Tab Button
case TabButton = 8
/// kCoreThemeGroupedImagesID - Grouped/Packed Images
case GroupedImages = 9
/// kCoreThemeGlassButtonID - Glass Push Button
case GlassPushButton = 10
/// kCoreThemeBasicButtonID - Basic Button
case BasicButton = 11
/// kCoreThemePopUpButtonTexturedID - Pop-Up Button Textured
case TexturedPopUpButton = 12
/// kCoreThemeSquarePopUpButtonID - Square Pop-Up Button
case SquarePopUpButton = 13
/// kCoreThemePullDownButtonTexturedID - Pull-Down Button Rounded
case RoundedPullDownButton = 14
/// kCoreThemeSquarePullDownButtonID - Pull-Down Button Square
case SquarePullDownButton = 15
/// kCoreThemeBoxID - Box
case Box = 16
/// kCoreThemeMenuID - Menu
case Menu = 17
/// kCoreThemeScrollerID - Scroller
case Scroller = 18
/// kCoreThemeSplitViewID - SplitView
case SplitView = 19
/// kCoreThemeStepperElementID - Stepper
case Stepper = 20
/// kCoreThemeTabViewElementID - Tab View
case TabView = 21
/// kCoreThemeTableViewElementID - Table View
case TableView = 22
/// kCoreThemeTextFieldElementID - Text Field
case TextField = 23
/// kCoreThemeWindowID - Window
case Window = 24
/// kCoreThemePatternsElementID - Patterns
case Patterns = 25
/// kCoreThemeButtonGlyphsID - Button Glyphs
case ButtonGlyphs = 26
/// kCoreThemeBezelElementID - Bezel
case Bezel = 27
/// kCoreThemeProgressBarID - Progress Bar
case ProgressBar = 28
/// kCoreThemeImageWellID - Image Well
case ImageWell = 29
/// kCoreThemeSliderID - Slider
case Slider = 30
/// kCoreThemeDialID - Dial
case Dial = 31
/// kCoreThemeDrawerID - Drawer
case Drawer = 32
/// kCoreThemeToolbarID - Toolbar
case Toolbar = 33
/// kCoreThemeCursorsID - Cursors
case Cursors = 34
/// kCoreThemeTimelineID - Timeline
case Timeline = 35
/// kCoreThemeZoomBarID - Zoom Bar
case ZoomBar = 36
/// kCoreThemeZoomSliderID - Zoom Slider
case ZoomSlider = 37
/// kCoreThemeIconsID - Icons
case Icons = 38
/// kCoreThemeListColorPickerScrollerID - List Color Picker Scroller
case ListColorPickerScroller = 39
/// kCoreThemeColorPanelID - Color Panel
case ColorPanel = 40
/// kCoreThemeTextureID - Texture Group
case TextureGroup = 41
/// kCoreThemeBrowserID - Browser
case Browser = 42
/// kCoreThemeNavID - Nav Panel
case NavPanel = 43
/// kCoreThemeSearchFieldID - Search Field
case SearchField = 44
/// kCoreThemeFontPanelID - Font Panel
case FontPanel = 45
/// kCoreThemeScrubberID - Scrubber
case Scrubber = 46
/// kCoreThemeTexturedWindowID - Textured Window
case TexturedWindow = 47
/// kCoreThemeUtilityWindowID - Utility Window
case UtilityWindow = 48
/// kCoreThemeTransientColorPickerID - Transient Color Picker
case TransientColorPicker = 49
/// kCoreThemeSegmentedScrubberID - Segmented Scrubber
case SegmentedScrubber = 50
/// kCoreThemeCommandsID - Commands
case Commands = 51
/// kCoreThemePathControlID - Path Control
case PathControl = 52
/// kCoreThemeCustomButtonID - Custom Button for Zero Code
case CustomButton = 53
/// kCoreThemeZeroCodePlaceHolderID - Zero Code Place Holder
case ZeroCodePlaceHolder = 54
/// kCoreThemeRuleEditorID - Rule Editor
case RuleEditor = 55
/// kCoreThemeTokenFieldID - Token Field
case TokenField = 56
/// kCoreThemePopUpTableViewArrowsID - PopUp Arrows for TableViews
case PopUpTableViewArrows = 57
/// kCoreThemePullDownTableViewArrowsID - PullDown Arrow for TableViews
case PullDownTableViewArrows = 58
/// kCoreThemeComboBoxTableArrowID - Combo Box Arrow for TableViews
case ComboBoxTableViewArrow = 59
/// kCoreThemeRuleEditorPopUpID - Rule Editor - PopUp Button
case RuleEditorPopUp = 60
/// kCoreThemeRuleEditorStepperID - Rule Editor - Stepper
case RuleEditorStepper = 61
/// kCoreThemeRuleEditorComboBoxID - Rule Editor - ComboBox
case RuleEditorComboBox = 62
/// kCoreThemeRuleEditorActionButtonsID - Rule Editor - Action Buttons
case RuleEditorActionButtons = 63
/// kCoreThemeColorSliderID - Color Slider
case ColorSlider = 64
/// kCoreThemeGradientControlGradientID - Control Gradient
case GradientControl = 65
/// kCoreThemeGradientControlBezelID - Gradient Bezel
case GradientControlBezel = 66
/// kCoreThemeMegaTrackballID - MegaTrackball
case MegaTrackball = 67
// 68-73: Not Found
/// kCoreThemeLevelIndicatorRelevancyID - LevelIndicatorRelevancy
case LevelIndicatorRelevancy = 74
// 75-78: Not Found
/// kCoreThemeToolbarRaisedEffectID - Toolbar Raised Effect
case ToolbarRaisedEffect = 79
/// kCoreThemeSidebarRaisedEffectID - Sidebar Raised Effect
case SidebarRaisedEffect = 80
/// kCoreThemeLoweredEmbossedEffectID - Lowered Embossed Effect
case LoweredEmbossedEffect = 81
/// kCoreThemeTitlebarRaisedEffectID - Fullscreen/TAL Window Controls Effect
case TitlebarRaisedEffect = 82
/// kCoreThemeSegmentedControlRoundedID - Segmented Control Rounded
case SegmentedControlRounded = 83
/// kCoreThemeSegmentedControlTexturedID - Segmented Control Textured
case SegmentedControlTextured = 84
/// kCoreThemeNamedElementID - Named Element
case NamedElement = 85
/// kCoreThemeLetterpressEffectID - Letterpress Emboss Effect
case LetterpressEmbossEffect = 86
/// kCoreThemeRoundRectButtonID - Round Rect Button
case RoundRectButton = 87
/// kCoreThemeButtonRoundID - Round Button
case RoundButton = 88
/// kCoreThemeButtonRoundTexturedID - Textured Round Button
case TexturedRoundButton = 89
/// kCoreThemeButtonRoundHelpID - Round Help Button
case RoundHelpButton = 90
/// kCoreThemeScrollerOverlayID - Scroll Bar Overlay
case ScrollBarOverlay = 91
/// kCoreThemeScrollViewFrameID - Scroll View Frame
case ScrollViewFrame = 92
/// kCoreThemePopoverID - Popover
case Popover = 93
/// kCoreThemeLightContentEffectID - Light Content Effect
case LightContentEffect = 94
/// kCoreThemeDisclosureTriangleElementID - Disclosure Triangle
case DisclosureTriangle = 95
/// kCoreThemeSourceListElementID - Source List
case SourceList = 96
/// kCoreThemePopUpButtonID - Pop-Up Button
case PopUpButton = 97
/// kCoreThemePullDownButtonID - Pull-Down Button
case PullDownButton = 98
/// kCoreThemeTextFieldTexturedElementID - Textured Text Field
case TexturedTextField = 99
/// kCoreThemeComboBoxButtonTexturedID - Textured Combo Box
case TexturedComboBox = 100
/// kCoreThemeStructuredImageElementID - Structured Image
case StructuredImage = 101
/// kCoreThemePopUpButtonInsetID - Pop-Up Button Inset
case PopUpButtonInset = 102
/// kCoreThemePullDownButtonInsetID - Pull Down Button Inset
case PullDownButtonInset = 103
/// kCoreThemeSheetID - Sheet
case Sheet = 104
/// kCoreThemeBevelButtonSquareID - Bevel Button Square
case BevelButtonSquare = 105
/// kCoreThemeBevelButtonPopUpArrowID - Bevel Button Pop Up Arrow
case BevelButtonPopUpArrow = 106
/// kCoreThemeRecessedButtonID - Recessed Button
case RecessedButton = 107
/// kCoreThemeSegmentedControlSeparatedToolbarID - Segmented Control Separated Toolbar
case SegmentedControlSeparatedToolbar = 108
/// kCoreThemeLightEffectID - Light Effect
case LightEffect = 109
/// kCoreThemeDarkEffectID - Dark Effect
case DarkEffect = 110
/// kCoreThemeButtonRoundInsetID - Round Button Inset
case ButtonRoundInset = 111
/// kCoreThemeSegmentedControlSeparatedID - Segmented Control Separated
case SegmentedControlSeparated = 112
/// kCoreThemeBorderlessEffectID - Borderless Effect
case BorderlessEffect = 113
/// kCoreThemeMenuBarEffectID - MenuBar Effect
case MenuBarEffect = 114
/// kCoreThemeSecondaryBoxID - Secondary Box
case SecondaryBox = 115
/// kCoreThemeDockBadgeID - Dock Badge
case DockBadge = 116
/// kCoreThemeBannerID - Banner
case Banner = 117
/// kCoreThemePushButtonTexturedID - Textured Button
case TexturedPushButton = 118
/// kCoreThemeSegmentedControlInsetID - Inset Segmented Control
case SegmentedControlInset = 119
/// kCoreThemeHUDWindowID - HUD Window
case HUDWindow = 120
/// kCoreThemeFullScreenWindowID - FullScreen Window
case FullScreenWindow = 121
/// kCoreThemeTableViewOpaqueElementID - Table View Opaque
case TableViewOpaque = 122
/// kCoreThemeTableViewTranslucentElementID - Table View Translucent
case TableViewTranslucent = 123
/// kCoreThemeImageWellOpaqueID - Image Well Opaque
case ImageWellOpaque = 124
/// kCoreThemeStateTransformEffectID - State Transform Effect
case StateTransformEffect = 125
// 126: Not Found
/// kCoreThemeLightMaterialID - Light Material
case LightMaterial = 127
/// kCoreThemeMacLightMaterialID - Mac Light Material
case MacLightMaterial = 128
/// kCoreThemeUltralightMaterialID - Ultralight Material
case UltralightMaterial = 129
/// kCoreThemeMacUltralightMaterialID - Mac Ultralight Material
case MacUltralightMaterial = 130
/// kCoreThemeMacDarkMaterialID - Mac Dark Material
case MacDarkMaterial = 131
/// kCoreThemeMacMediumDarkMaterialID - Mac Medium Dark Material
case MacMediumDarkMaterial = 132
/// kCoreThemeMacUltradarkMaterialID - Mac Ultradark Material
case MacUltradarkMaterial = 133
/// kCoreThemeTitlebarMaterialID - Titlebar Material
case TitlebarMaterial = 134
/// kCoreThemeSelectionMaterialID - Selection Material
case SelectionMaterial = 135
/// kCoreThemeEmphasizedSelectionMaterialID - Emphasized Selection Material
case EmphasizedSelectionMaterial = 136
/// kCoreThemeHeaderMaterialID - Header Material
case HeaderMaterial = 137
/// kCoreThemeComboBoxButtonToolbarID - Toolbar Combo Box
case ComboBoxButtonToolbar = 138
/// kCoreThemePopUpButtonToolbarID - Pop-Up Button Toolbar
case PopUpButtonToolbar = 139
/// kCoreThemePullDownButtonToolbarID - Pull-Down Button Rounded Toolbar
case PullDownButtonToolbar = 140
/// kCoreThemeButtonRoundToolbarID - Toolbar Round Button
case ButtonRoundToolbar = 141
/// kCoreThemeSegmentedControlSeparatedTexturedID - Segmented Control Separated Textured
case SegmentedControlSeparatedTextured = 142
/// kCoreThemeSegmentedControlToolbarID - Segmented Control Toolbar
case SegmentedControlToolbar = 143
/// kCoreThemePushButtonToolbarID - Toolbar Button
case PushButtonToolbar = 144
/// kCoreThemeLightOpaqueMaterialID - Opaque Light Material
case LightOpaqueMaterial = 145
/// kCoreThemeMacLightOpaqueMaterialID - Opaque Mac Light Material
case MacLightOpaqueMaterial = 146
/// kCoreThemeUltralightOpaqueMaterialID - Opaque Ultralight Material
case UltralightOpaqueMaterial = 147
/// kCoreThemeMacUltralightOpaqueMaterialID - Opaque Mac Ultralight Material
case MacUltralightOpaqueMaterial = 148
/// kCoreThemeMacDarkOpaqueMaterialID - Opaque Mac Dark Material
case MacDarkOpaqueMaterial = 149
/// kCoreThemeMacMediumDarkOpaqueMaterialID - Opaque Mac Medium Dark Material
case MacMediumDarkOpaqueMaterial = 150
/// kCoreThemeMacUltradarkOpaqueMaterialID - Opaque Mac Ultradark Material
case MacUltradarkOpaqueMaterial = 151
/// kCoreThemeTitlebarOpaqueMaterialID - Opaque Titlebar Material
case TitlebarOpaqueMaterial = 152
/// kCoreThemeSelectionOpaqueMaterialID - Opaque Selection Material
case SelectionOpaqueMaterial = 153
/// kCoreThemeEmphasizedSelectionOpaqueMaterialID - Opaque Emphasized Selection Material
case EmphasizedSelectionOpaqueMaterial = 154
/// kCoreThemeHeaderOpaqueMaterialID - Opaque Header Material
case HeaderOpaqueMaterial = 155
/// kCoreThemeRecessedPullDownButtonID - Recessed Pull Down Button
case RecessedPullDownButton = 156
/// kCoreThemeBezelTintEffectID - Bezel Tint Effect
case BezelTintEffect = 157
/// kCoreThemeDefaultBezelTintEffectID - Default Bezel Tint Effect
case DefaultBezelTintEffect = 158
/// kCoreThemeOnOffBezelTintEffectID - On-Off Bezel Tint Effect
case OnOffBezelTintEffect = 159
/// kCoreThemeMacMediumLightMaterialID - Mac Medium Light Material
case MacMediumLightMaterial = 160
/// kCoreThemeMacMediumLightOpaqueMaterialID - Opaque Mac Medium Light Material
case MacMediumLightOpaqueMaterial = 161
/// kCoreThemeSelectionOverlayID - Selection Overlay
case SelectionOverlay = 162
/// kCoreThemeRangeSelectorID - Range Selector
case RangeSelector = 163
/// kCoreThemeModelAssetID - Model Asset
case ModelAsset = 164
// 165: Not Found
/// kCoreThemeSegmentedControlSmallSquareID - Segmented Control Small Square
case SegmentedControlSmallSquare = 166
/// kCoreThemeLevelIndicatorID - LevelIndicator
case LevelIndicator = 167
/// kCoreThemeMenuMaterialID - Menu Material
case MenuMaterial = 168
/// kCoreThemeMenuBarMaterialID - Menu Bar Material
case MenuBarMaterial = 169
/// kCoreThemePopoverMaterialID - Popover Material
case PopoverMaterial = 170
/// kCoreThemePopoverLabelMaterialID - Popover Label Material
case PopoverLabelMaterial = 171
/// kCoreThemeToolTipMaterialID - ToolTip Material
case ToolTipMaterial = 172
/// kCoreThemeSidebarMaterialID - Sidebar Material
case SidebarMaterial = 173
/// kCoreThemeWindowBackgroundMaterialID - Window Background Material
case WindowBackgroundMaterial = 174
/// kCoreThemeUnderWindowBackgroundMaterialID - Under Window Background Material
case UnderWindowBackgroundMaterial = 175
/// kCoreThemeContentBackgroundMaterialID - Content Background Material
case ContentBackgroundMaterial = 176
/// kCoreThemeSpotlightBackgroundMaterialID - Spotlight Background Material
case SpotlightBackgroundMaterial = 177
/// kCoreThemeNotificationCenterBackgroundMaterialID - Notification Center Background Material
case NotificationCenterBackgroundMaterial = 178
/// kCoreThemeSheetMaterialID - Sheet Material
case SheetMaterial = 179
/// kCoreThemeHUDWindowMaterialID - HUD Window Material
case HUDWindowMaterial = 180
/// kCoreThemeFullScreenUIMaterialID - Full Screen UI Material
case FullScreenUIMaterial = 181
/// kCoreThemeMenuOpaqueMaterialID - Opaque Menu Material
case MenuOpaqueMaterial = 182
/// kCoreThemeMenuBarOpaqueMaterialID - Opaque Menu Bar Material
case MenuBarOpaqueMaterial = 183
/// kCoreThemePopoverOpaqueMaterialID - Opaque Popover Material
case PopoverOpaqueMaterial = 184
/// kCoreThemePopoverLabelOpaqueMaterialID - Opaque Popover Label Material
case PopoverLabelOpaqueMaterial = 185
/// kCoreThemeToolTipOpaqueMaterialID - Opaque ToolTip Material
case ToolTipOpaqueMaterial = 186
/// kCoreThemeSidebarOpaqueMaterialID - Opaque Sidebar Material
case SidebarOpaqueMaterial = 187
/// kCoreThemeWindowBackgroundOpaqueMaterialID - Opaque Window Background Material
case WindowBackgroundOpaqueMaterial = 188
/// kCoreThemeUnderWindowBackgroundOpaqueMaterialID - Opaque Under Window Background Material
case UnderWindowBackgroundOpaqueMaterial = 189
/// kCoreThemeContentBackgroundOpaqueMaterialID - Opaque Content Background Material
case ContentBackgroundOpaqueMaterial = 190
/// kCoreThemeSpotlightBackgroundOpaqueMaterialID - Opaque Spotlight Background Material
case SpotlightBackgroundOpaqueMaterial = 191
/// kCoreThemeNotificationCenterBackgroundOpaqueMaterialID - Opaque Notification Center Background Material
case NotificationCenterBackgroundOpaqueMaterial = 192
/// kCoreThemeSheetOpaqueMaterialID - Opaque Sheet Material
case SheetOpaqueMaterial = 193
/// kCoreThemeHUDWindowOpaqueMaterialID - Opaque HUD Window Material
case HUDWindowOpaqueMaterial = 194
/// kCoreThemeFullScreenUIOpaqueMaterialID - Opaque Full Screen UI Material
case FullScreenUIOpaqueMaterial = 195
/// kCoreThemeTextHighlightEffectID - Color Effect for Text Highlights
case TextHighlightEffect = 196
/// kCoreThemeRowSelectionEffectID - Color Effect for Selected Rows
case RowSelectionEffect = 197
/// kCoreThemeFocusRingEffectID - Color Effect for Focus Rings
case FocusRingEffect = 198
/// kCoreThemeBoxSquareID - Square Box
case BoxSquare = 199
/// kCoreThemeSelectionEffectID - Color Effect for Selection
case SelectionEffect = 200
/// kCoreThemeUnderPageBackgroundMaterialID - UnderPage Background Material
case UnderPageBackgroundMaterial = 201
/// kCoreThemeUnderPageBackgroundOpaqueMaterialID - UnderPage Background Opaque Material
case UnderPageBackgroundOpaqueMaterial = 202
/// kCoreThemeInlineSidebarMaterialID - Inline Sidebar Material
case InlineSidebarMaterial = 203
/// kCoreThemeInlineSidebarOpaqueMaterialID - Inline Sidebar Opaque Material
case InlineSidebarOpaqueMaterial = 204
/// kCoreThemeMenuBarMenuMaterialID - MenuBar Menu Material
case MenuBarMenuMaterial = 205
/// kCoreThemeMenuBarMenuOpaqueMaterialID - MenuBar Menu Opaque Material
case MenuBarMenuOpaqueMaterial = 206
/// kCoreThemeHUDControlsBackgroundMaterialID - HUD Controls Background Material
case HUDControlsBackgroundMaterial = 207
/// kCoreThemeHUDControlsBackgroundOpaqueMaterialID - HUD Controls Background Opaque Material
case HUDControlsBackgroundOpaqueMaterial = 208
/// kCoreThemeSystemBezelMaterialID - System Bezel Material
case SystemBezelMaterial = 209
/// kCoreThemeSystemBezelOpaqueMaterialID - System Bezel Opaque Material
case SystemBezelOpaqueMaterial = 210
/// kCoreThemeLoginWindowControlMaterialID - Login Window Control Material
case LoginWindowControlMaterial = 211
/// kCoreThemeLoginWindowControlOpaqueMaterialID - Login Window Control Opaque Material
case LoginWindowControlOpaqueMaterial = 212
/// kCoreThemeDesktopStackMaterialID - Desktop Stack Material
case kCoreThsemeDesktopStackMaterial = 213
/// kCoreThemeDesktopStackOpaqueMaterialID - Desktop Stack Opaque Material
case DesktopStackOpaqueMaterial = 214
/// kCoreThemeDetailAccentEffectID - Color Effect for Detail Accent Colors
case DetailAccentEffect = 215
/// kCoreThemeToolbarStateTransformEffectID - Toolbar State Transform Effect
case ToolbarStateTransformEffect = 216
/// kCoreThemeStatefulColorsSystemEffectID - Stateful Colors System Effect
case StatefulColorsSystemEffect = 217
/// kCoreThemeSwitchElementID - Switch
case SwitchElement = 218
/// kCoreThemeInlineTitlebarMaterialID - Inline Titlebar Material
case InlineTitlebarMaterial = 219
/// kCoreThemeInlineTitlebarOpaqueMaterialID - Inline Titlebar Opaque Material
case InlineTitlebarOpaqueMaterial = 220
/// kCoreThemeSliderModernID - Slider Modern
case SliderModern = 221
/// kCoreThemeSegmentedControlSliderID - Segmented Control Slider
case SegmentedControlSlider = 222
/// kCoreThemeSegmentedControlSliderToolbarID - Segmented Control Slider Toolbar
case SegmentedControlSliderToolbar = 223
/// kCoreThemeSheetUnderlayMaterialID - Sheet Underlay Material
case SheetUnderlayMaterial = 224
/// kCoreThemeSheetUnderlayOpaqueMaterialID - Opaque Sheet Underlay Material
case OpaqueSheetUnderlayMaterial = 225
/// kCoreThemeAlertMaterialID - Alert Material
case AlertMaterial = 226
/// kCoreThemeAlertOpaqueMaterialID - Opaque Alert Material
case OpaqueAlertMaterial = 227
/// kCoreThemeMenuBarSelectionMaterialID - Menu Bar Selection Material
case MenuBarSelectionMaterial = 228
/// kCoreThemeMenuBarSelectionOpaqueMaterialID - Opaque Menu Bar Selection Material
case OpaqueMenuBarSelectionMaterial = 229
/// kCoreThemeOverlayBackingMaterialID - Overlay Backing Material
case OverlayBackingMaterial = 230
/// kCoreThemeOverlayBackingOpaqueMaterialID - Overlay Backing Opaque Material
case OverlayBackingOpaqueMaterial = 231
/// kCoreThemeSliderModernToolbarID - Slider Modern Toolbar
case SliderModernToolbar = 232
/// kCoreThemeDiscreteSelectionEffectID - Color Effect for Discrete Selection
case DiscreteSelectionColorEffect = 233
/// kCoreThemeAlertSheetMaterialID - Alert Sheet Material
case AlertSheetMaterial = 234
/// kCoreThemeAlertSheetOpaqueMaterialID - Opaque Alert Sheet Material
case OpaqueAlertSheetMaterial = 235
}
/// ThemePart
enum Part: UInt16 {
/// kCoreThemeBasicPartID - Basic - Basic Part
case BasicPart = 0
/// kCoreThemeTitlebarControlsID - Basic Button - Titlebar Controls
case TitlebarControls = 1
/// kCoreThemeShowHideButtonID - Basic Button - Show Hide Button
case ShowHideButton = 2
/// kCoreThemeBoxPrimaryID - Box - Primary Box
case BoxPrimary = 3
/// kCoreThemeBoxSecondaryID - Box - Secondary Box
case BoxSecondary = 4
/// kCoreThemeBoxMetalID - Box - Metal Box
case BoxMetal = 5
/// kCoreThemeBoxWellID - Box - Well Box
case BoxWell = 6
/// kCoreThemeMenuGlyphsID - Menu - Menu Glyphs
case MenuGlyphs = 7
/// kCoreThemeCornerID - Scroller - Corner
case Corner = 8
/// kCoreThemeSlotID - Scroller - Slot
case Slot = 9
/// kCoreThemeThumbID - Scroller / Zoom / SplitView - Thumb
case Thumb = 10
/// kCoreThemeNoArrowID - Scroller - No Arrow
case NoArrow = 11
/// kCoreThemeSingleArrowID - Scroller / Toolbar - Single Arrow
case SingleArrow = 12
/// kCoreThemeDoubleArrowMinEndID - Scroller - Double Arrow Min End
case DoubleArrowMinEnd = 13
/// kCoreThemeDoubleArrowMaxEndID - Scroller - Double Arrow Max End
case DoubleArrowMaxEnd = 14
/// kCoreThemeDividerID - SplitView - Divider
case Divider = 15
/// kCoreThemeTabViewPrimaryTabID - Tab View - Primary Tab
case TabViewPrimaryTab = 16
/// kCoreThemeTabViewSecondaryTabID - Tab View - Secondary Tab
case TabViewSecondaryTab = 17
/// kCoreThemeTabViewRodID - Tab View - Tab View Rod
case TabViewRod = 18
/// kCoreThemeTabViewLargeRodID - Tab View - Large Rod
case TabViewLargeRod = 19
/// kCoreThemeTabViewSmallRodID - Tab View - Small Rod
case TabViewSmallRod = 20
/// kCoreThemeTabViewMiniRodID - Tab View - Mini Rod
case TabViewMiniRod = 21
/// kCoreThemeTabViewPaneID - Tab View - Tab Pane
case TabViewPane = 22
/// kCoreThemePrimaryListHeaderID - Table View - Primary ListHeader
case PrimaryListHeader = 23
/// kCoreThemeSecondaryListHeaderID - Table View - Secondary ListHeader
case SecondaryListHeader = 24
/// kCoreThemeListHeaderGlyphsID - Table View - ListHeader Glyphs
case ListHeaderGlyphs = 25
/// kCoreThemeTitlebarID - Window - Title Bar
case Titlebar = 26
/// kCoreThemeWindowButtonsID - Window - Buttons
case WindowButtons = 27
/// kCoreThemeResizeControlID - Window - Resize Control
case ResizeControl = 28
/// kCoreThemeDoubleArrowID - Toolbar - Double Arrow
case DoubleArrow = 29
/// kCoreThemeToolbarIconsID - Toolbar - Toolbar Icons
case ToolbarIcons = 30
/// kCoreThemeToolbarSpacerIconsID - Toolbar - Spacer Icons
case ToolbarSpacerIcons = 31
/// kCoreThemeProgressBackgroundID - Progress Bar - Background
case ProgressBackground = 32
/// kCoreThemeProgressBarDeterminateID - Progress Bar - Determinate
case ProgressBarDeterminate = 33
/// kCoreThemeProgressBarIndeterminateID - Progress Bar - Indeterminate
case ProgressBarIndeterminate = 34
/// kCoreThemeSliderTrackID - Slider - Track
case SliderTrack = 35
/// kCoreThemeSliderKnobID - Slider - Knob
case SliderKnob = 36
/// kCoreThemeSliderTickID - Slider - Tick
case SliderTick = 37
/// kCoreThemeThumbnailBezelID - Bezel - Thumbnail
case ThumbnailBezel = 38
/// kCoreThemeColorSwatchBezelID - Bezel - Color Swatch
case ColorSwatchBezel = 39
/// kCoreThemeRoundBezelID - Text Field - Round Text Field
case RoundBezel = 40
/// kCoreThemeSquareBezelID - Text Field - Square Text Field
case SquareBezel = 41
/// kCoreThemeVectorArtworkImageID - Vector Artwork Image
case VectorArtworkImage = 42
/// kCoreThemeStandardCursorsID - Cursors - Standard Cursors
case StandardCursors = 43
/// kCoreThemeTimelineStreamID - Timeline - Stream
case TimelineStream = 44
/// kCoreThemeTimelineClipID - Timeline - Clip
case TimelineClip = 45
/// kCoreThemeTimelineSelectedClipID - Timeline - Selected Clip
case TimelineSelectedClip = 46
/// kCoreThemeTimelineLockOverlayID - Timeline - Lock Overlay
case TimelineLockOverlay = 47
// 48: Not Found
/// kCoreThemeTimelineLockedGlyphID - Timeline - Locked Glyph
case TimelineLockedGlyph = 49
/// kCoreThemePlayHeadID - Timeline / Zoom Bar - Play Head
case PlayHead = 50
/// kCoreThemeTimelineTrackSizeButtonID - Timeline - Track Size Button
case TimelineTrackSizeButton = 51
/// kCoreThemeTimeCodeIconID - Timeline - Time Code Icon
case TimeCodeIcon = 52
/// kCoreThemeGlassRoundButtonID - Glass Button / Button Glyphs - Round Button
case GlassRoundButton = 53
/// kCoreThemeGlassVisibilityButtonID - Glass Button / Button Glyphs - Visibility Button
case GlassVisibilityButton = 54
/// kCoreThemeTabButtonSingletonID - Tab Button - Singleton
case TabButtonSingleton = 55
/// kCoreThemeTabButtonMatrixID - Tab Button - Matrix
case TabButtonMatrix = 56
/// kCoreThemeSampleGlyphsTabButtonsID - Button Glyphs - Sample Glyphs for Tab Matrix Buttons
case SampleGlyphsTabButtons = 57
/// kCoreThemeSampleGlyphsSingleTabButtonID - Button Glyphs - Sample Glyphs for Singleton Tab Buttons
case SampleGlyphsSingleTabButton = 58
/// kCoreThemeVectorGlyphID - Glyph Vector Data
case VectorGlyph = 59
/// kCoreThemeModelPartID
case ModelPart = 60
/// kCoreThemeLargeTextBezelID - Bezel - Large Text Bezel
case LargeTextBezel = 61
/// kCoreThemeDisplayTextBezelID - Text Field - Display Text Bezel
case DisplayTextBezel = 62
/// kCoreThemeSlideOutBezelID - Drawer - Slideout Bezel
case SlideOutBezel = 63
// 64: Not Found
/// kCoreThemeDrawerAffordanceID - Drawer - Affordance
case DrawerAffordance = 65
/// kCoreThemeDimpleID - Dial - Dimple
case Dimple = 66
/// kCoreThemeDisclosureTriangleID - Disclosure - Triangle
case DisclosureTriangle = 67
/// kCoreThemeDisclosureKnobID - Disclosure - Knob
case DisclosureKnob = 68
/// kCoreThemeDisclosureGlyphID - Disclosure - Glyph
case DisclosureGlyph = 69
/// kCoreThemeTypeAlignGlyphID - Button Glyphs - Type Alignment Glyph
case TypeAlignGlyph = 70
/// kCoreThemeTypeLeadingGlyphID - Button Glyphs - Type Leading Glyph
case TypeLeadingGlyph = 71
/// kCoreThemeFontPanelGlyphsID - Button Glyphs - Font Panel Glyphs
case FontPanelGlyphs = 72
/// kCoreThemePreferencesID - Icons - Preferences
case Preferences = 73
/// kCoreThemeNoteGlyphID - Icons - Note Glyph
case NoteGlyph = 74
/// kCoreThemePreviewBezelID - Bezel - Preview Bezel
case PreviewBezel = 75
/// kCoreThemeGlassHelpButtonID - Glass Button / Button Glyphs - Help Button
case GlassHelpButton = 76
/// kCoreThemeColumnResizerID - Browser - Column Resize
case ColumnResizer = 77
/// kCoreThemeSearchButtonID - Search Field - Search Button
case SearchButton = 78
/// kCoreThemeCancelButtonID - Search Field - Cancel Button
case CancelButton = 79
/// kCoreThemeSnapBackButtonID - Search Field - SnapBack Button
case SnapBackButton = 80
/// kCoreThemeArrowsID - Scrubber / Segmented Scrubber - Arrows
case Arrows = 81
/// kCoreThemeScopeButtonID - Nav Panel - Scope Button
case ScopeButton = 82
/// kCoreThemePreviewButtonID - Nav Panel - Preview Button
case PreviewButton = 83
/// kCoreThemeWindowTextureID - Textured Window - Scratches
case TexturedWindowScratches = 84
/// kCoreThemeWindowTextureGradientID - Textured Window - Gradient
case TexturedWindowGradient = 85
/// kCoreThemeWindowRoundCornerID - Window - Round Corner
case WindowRoundCorner = 86
/// kCoreThemeUnifiedWindowFillID - Unified Toolbar - Gradient
case UnifiedWindowFill = 87
/// kCoreThemeMenuBarID - Menu - Menu Bar
case MenuBar = 88
/// kCoreThemeAppleMenuID - Menu - Apple Menu
case AppleMenu = 89
/// kCoreThemeBoxMatteWellID - Box - Matte Well Box
case BoxMatteWell = 90
/// kCoreThemeTransientColorPickerImageID - Transient Color Picker - Image
case TransientColorPickerImage = 91
/// kCoreThemeTransientColorPickerImageGrayscaleID - Transient Color Picker - Grayscale Image
case TransientColorPickerImageGrayscale = 92
/// kCoreThemeTransientColorWellButtonLeftPartID - Transient Color Picker - Color Well Left Part
case TransientColorWellButtonLeft = 93
/// kCoreThemeTransientColorWellButtonSeparatorID - Transient Color Picker - Color Well Separator
case TransientColorWellSeparator = 94
/// kCoreThemeTransientColorWellButtonRightPartID - Transient Color Picker - Color Well Right Part
case TransientColorWellButtonRight = 95
/// kCoreThemeTransientColorWellButtonLeftPartLgID - Transient Color Picker - Color Well (Large) Left Part
case TransientColorWellButtonLeftLarge = 96
/// kCoreThemeTransientColorWellButtonSeparatorLgID - Transient Color Picker - Color Well (Large) Separator
case TransientColorWellSeparatorLarge = 97
/// kCoreThemeTransientColorWellButtonRightPartLgID - Transient Color Picker - Color Well (Large) Right Part
case TransientColorWellButtonRightLarge = 98
/// kCoreThemeCaretID - Segmented Scrubber - Caret
case Caret = 99
/// kCoreThemeScrubbingArrowsID - Segmented Scrubber - Scrubbing Arrows
case ScrubbingArrows = 100
/// kCoreThemeCommandIconsID - Commands - Icons
case CommandIcons = 101
/// kCoreThemeCommandKeyCapID - Commands - Key Cap
case CommandKeyCap = 102
/// kCoreThemeCommandInfoID - Commands - Extra KeyPad Glyphs
case CommandInfo = 103
/// kCoreThemePathControlDividerID - Path Control - Divider
case PathControlDivider = 104
/// kCoreThemePathControlNavBarID - Path Control - Navigation Bar
case PathControlNavBar = 105
/// kCoreThemeBoxRaisedID - Box - Raised Box
case BoxRaised = 106
/// kCoreThemeBoxInsetID - Box - Inset Box
case BoxInset = 107
/// kCoreThemeCommandsSearchFocus - Commands - Searching Focus
case CommandsSearchFocus = 108
/// kCoreThemeCommandsSearchOverlay - Commands - Searching Overlay
case CommandsSearchOverlay = 109
// 110-111: Not Found
/// kCoreThemeTableViewChevronID - TableView - Chevron
case TableViewChevron = 112
/// kCoreThemeZoomSmallGlyphID - Zero Code - Small Glyph
case ZoomSmallGlyph = 113
/// kCoreThemeZoomLargeGlyphID - Zero Code - Large Glyph
case ZoomLargeGlyph = 114
/// kCoreThemeCommandKeyCapPatchID - Commands - Key Cap Patch
case CommandKeyCapPatch = 115
/// kCoreThemeNavigateBackwardID - Button Glyphs - Navigate Backward
case NavigateBackward = 116
/// kCoreThemeNavigateForwardID - Button Glyphs - Navigate Forward
case NavigateForward = 117
// 118: Not Found
/// kCoreThemeGroupWellID - Box - Group Well Box
case GroupWellBox = 119
/// kCoreThemeTableViewScrubbingArrowsID - Segmented Scrubber - TableView Scrubbing Arrows
case TableViewScrubbingArrows = 120
/// kCoreThemeProgressSpinningID - Progress Indicator - Spinning
case ProgressSpinning = 121
/// kCoreThemeLabelBulletRoundID - Rule Editor - Label Bullets Round (Tiger)
case LabelBulletRound = 122
/// kCoreThemeLabelSelectorRoundID - Rule Editor - Label Selectors Round (Tiger)
case LabelSelectorRound = 123
/// kCoreThemeLabelBulletSquareID - Rule Editor - Label Bullets Square (Leopard)
case LabelBulletSquare = 124
/// kCoreThemeLabelSelectorSquareID - Rule Editor - Label Selectors Square (Leopard)
case LabelSelectorSquare = 125
/// kCoreThemeDisclosureTriangleSidebarID - Disclosure - Nav Sidebar Highlighted Triangle
case DisclosureTriangleSidebar = 126
/// kCoreThemePackedContentsNamesID - Packed Contents Names
case PackedContentsNames = 127
/// kCoreThemeTransientColorPickerSwatchBackgroundID - Transient Color Picker - Swatch Background
case TransientColorPickerSwatchBackground = 128
/// kCoreThemeSegmentedControlSeparatorID - Segmented Control Separator
case SegmentedControlSeparator = 129
/// kCoreThemeColorLabelPatternsID - Color Label Patterns
case ColorLabelPatterns = 130
/// kCoreThemeMegaTrackballPuckID - MegaTrackball - Puck
case MegaTrackballPuck = 131
/// kCoreThemeMegaTrackballGlyphsID - MegaTrackball - Glyphs
case MegaTrackballGlyphs = 132
/// kCoreThemeMegaTrackballBaseGradientID - MegaTrackball - Base Gradient
case MegaTrackballBaseGradient = 133
/// kCoreThemeMegaTrackballHueRingID - MegaTrackball - Hue Ring
case MegaTrackballHueRing = 134
/// kCoreThemeMegaTrackballBaseShadowMaskID - MegaTrackball - Base Shadow Mask
case MegaTrackballBaseShadowMask = 135
/// kCoreThemeMegaTrackballCenterID - MegaTrackball - Center
case MegaTrackballCenter = 136
/// kCoreThemeZoomUnifiedGlyphID - Icons - Unified Zoom
case ZoomUnifiedGlyph = 137
/// kCoreThemeSegmentedControlBezelID - Segmented Control Bezel
case SegmentedControlBezel = 138
/// kCoreThemeBrowserBranchID - Browser - Branch Image
case BrowserBranch = 139
/// kCoreThemePaneCapLoweredMenuIndicatorPartID - Pane Cap - Lowered Menu Indicator
case PaneCapLoweredMenuIndicator = 140
/// kCoreThemePaneCapCenteredMenuIndicatorPartID - Pane Cap - Centered Menu Indicator
case PaneCapCenteredMenuIndicator = 141
/// kCoreThemePaneCapPopUpMenuIndicatorPartID - Pane Cap - Pop Up Menu Indicator
case PaneCapPopUpMenuIndicator = 142
/// kCoreThemeCloseButtonGlyphID - Content Tab View -Close Button Glyph
case CloseButtonGlyph = 143
/// kCoreThemeContentTabViewTabID - Content Tab View - Tab
case ContentTabViewTab = 144
/// kCoreThemeContentTabViewMenuChevronID - Content Tab View - Menu Chevron
case ContentTabViewMenuChevron = 145
/// kCoreThemeContentViewMenuGrabberID - Content Tab View - Menu Grabber
case ContentViewMenuGrabber = 146
/// kCoreThemeContentViewMenuButtonGlyphID - Content Tab View - Menu Button Glyph
case ContentViewMenuButtonGlyph = 147
/// kCoreThemeContentViewMenuThumbnailHighlightID - Content Tab View - Menu Thumbnail Highlight
case ContentViewMenuThumbnailHighlight = 148
/// kCoreThemeNavPushButtonPartID - Nav Panel - Scope Bar Push (Save) Button
case NavPanelPushButton = 149
// 150-152: Not Found
/// kCoreThemeToolbarSelectionIndicatorID - Toolbar Item Selection Indicator
case ToolbarSelectionIndicator = 153
// 154-159: Not Found
/// kCoreThemeSplitViewGrabberID - SplitView - Grabber
case SplitViewGrabber = 160
// 161-170: Not Found
/// kCoreThemePaneCapHeaderID - Pane Cap Header
case PaneCapHeader = 171
/// kCoreThemePaneCapFooterID - Pane Cap Footer
case PaneCapFooter = 172
// 173-174: Not Found
/// kCoreThemeWindowOverlayPatternID - Window - Overlay Pattern
case WindowOverlayPattern = 175
/// kCoreThemeWindowBackgroundImageID - Window - Background Image
case WindowBackgroundImage = 176
/// kCoreThemeWindowBottomGradientID - Window - Bottom Gradient
case WindowBottomGradient = 177
/// kCoreThemeImageEffectID - Image Effect Definition
case ImageEffect = 178
/// kCoreThemeTextEffectID - Text Effect Definition
case TextEffect = 179
/// kCoreThemeMenuSeparatorID - Menu Separator
case MenuSeparator = 180
/// kCoreThemeArtworkImageID - Artwork Image
case ArtworkImage = 181
/// kCoreThemeWindowTitlebarSeparatorID - Window Titlebar Separator
case WindowTitlebarSeparator = 182
/// kCoreThemeMenuPartID - Menu Background
case MenuPart = 183
/// kCoreThemeMenuItemPartID - Menu Item
case MenuItemPart = 184
/// kCoreThemeNamedEffectID - Named Effect
case NamedEffect = 185
/// kCoreThemeExpandedThumbID - Scroller - Expanded Thumb
case ExpandedThumb = 186
/// kCoreThemeTokenFieldTokenBackgroundID - Token Field - Token Background
case TokenFieldTokenBackground = 187
/// kCoreThemeProgressBarDeterminateCompleteID - Progress Bar Complete - Determinate
case ProgressBarDeterminateComplete = 188
/// kCoreThemeProgressBarDeterminateShadowID - Progress Bar Shadow - Determinate
case ProgressBarDeterminateShadow = 189
/// kCoreThemeProgressSpinningDeterminateID - Progress Spinner - Determinate
case ProgressSpinningDeterminate = 190
/// kCoreThemePopoverBackgroundID - Popover - Popover Background
case PopoverBackground = 191
/// kCoreThemePopoverAreaOfInterestID - Popover - Popover Area of Interest
case PopoverAreaOfInterest = 192
/// kCoreThemeSourceListBackgroundID - Source List - Source List Background
case SourceListBackground = 193
/// kCoreThemeSourceListSelectionID - Source List - Selected Item
case SourceListSelection = 194
/// kCoreThemeSourceListMenuHighlightID - Source List - Menu Highlight
case SourceListMenuHighlight = 195
/// kCoreThemeWindowBottomBarSeparatorID - Window BottomBar Separator
case WindowBottomBarSeparator = 196
/// kCoreThemePopUpArrowButton - PopUp Arrow Button
case PopUpArrowButton = 197
/// kCoreThemePopUpArrowsOnly - PopUp Arrows Only
case PopUpArrowsOnly = 198
/// kCoreThemeListHeaderGlyphsPlusBackgroundID - List Header Arrow Plus Background
case ListHeaderGlyphsPlusBackground = 199
/// kCoreThemeAnimationPartID - Animation
case AnimationPart = 200
/// kCoreThemePopUpArrowsSubpartID - PopUp Arrows Subpart
case PopUpArrowsSubpart = 201
/// kCoreThemePopUpEndcapSubpartID - PopUp Endcap Subpart
case PopUpEndcapSubpart = 202
/// kCoreThemeDockBadgeBackgroundID - Dock Badge Background
case DockBadgeBackground = 203
/// kCoreThemeGroupHeaderID - Table View Group Header
case GroupHeader = 204
/// kCoreThemeSliderBackgroundID - Slider Background
case SliderBackground = 205
/// kCoreThemeRecognitionGroupID - Recognition Group
case RecognitionGroup = 206
/// kCoreThemeRecognitionObjectID - Recognition Object
case RecognitionObject = 207
/// kCoreThemeFlattenedImageID - Flattened Image
case FlattenedImage = 208
/// kCoreThemeRadiosityImageID - Radiosity Image
case RadiosityImage = 209
/// kCoreThemeFillID - Fill
case Fill = 210
/// kCoreThemeOuterStrokeID - Outer Stroke
case OuterStroke = 211
/// kCoreThemeInnerStrokeID - Inner Stroke
case InnerStroke = 212
/// kCoreThemeRangeSelectorNoHandleID - Range Selector No Handle
case RangeSelectorNoHandle = 213
/// kCoreThemeRangeSelectorSingleHandleID - Range Selector Single Handle
case RangeSelectorSingleHandle = 214
/// kCoreThemeRangeSelectorDualHandleID - Range Selector Dual Handle
case RangeSelectorDualHandle = 215
/// kCoreThemeRangeSelectorMonoHandleID - Range Selector Mono Handle
case RangeSelectorMonoHandle = 216
/// kCoreThemeColorPartID - Color Part
case ColorPart = 217
/// kCoreThemeMultisizeImageSetPartID - Multi-size Image Set Part
case MultisizeImageSetPart = 218
/// kCoreThemeModelAssetPartID - Top Level Model Asset
case ModelAssetPart = 219
/// kCoreThemeMultisizeImagePartID - Multi-size Image Part
case MultisizeImagePart = 220
/// kCoreThemeLevelIndicatorFillID - Level Indicator Fill
case LevelIndicatorFill = 221
/// kCoreThemeLevelIndicatorMaskID - Level Indicator Mask
case LevelIndicatorMask = 222
/// kCoreThemeLevelIndicatorOutlineID - Level Indicator Border
case LevelIndicatorBorder = 223
/// kCoreThemeLevelIndicatorRelevancyBackgroundID - Level Indicator Relevancy Background
case LevelIndicatorRelevancyBackground = 224
/// kCoreThemeLevelIndicatorTickMarkMajorID - Level Indicator Tick Mark Major
case LevelIndicatorTickMarkMajor = 225
/// kCoreThemeLevelIndicatorTickMarkMinorID - Level Indicator Tick Mark Minor
case LevelIndicatorTickMarkMinor = 226
/// kCoreThemeMaskID - Mask Part
case MaskPart = 227
/// kCoreThemeBorderPartID - Border Part
case BorderPart = 228
/// kCoreThemeRightPartID - Right Part
case RightPart = 229
/// kCoreThemeLeftPartID - Left Part
case LeftPart = 230
/// kCoreThemeTextStylePartID - Text Style Part
case TextStylePart = 231
/// kCoreThemeModelMeshID - Model Mesh Object
case ModelMesh = 232
/// kCoreThemeModelSubMeshID - Model SubMesh Object
case ModelSubMesh = 233
/// kCoreThemeKnobPartID - Knob
case Knob = 234
/// kCoreThemeLabelPartID - Label
case Label = 235
/// kCoreThemeProgressSpinningDeterminateTrackID - Progress Spinner - Determinate Track
case ProgressSpinnerDeterminateTrack = 236
/// kCoreThemeShadowPartID - Shadow Part
case ShadowPart = 237
/// kCoreThemeSidebarPartID - SplitView - Sidebar Divider
case SplitViewSidebarDivider = 238
}
}
| 46.289905 | 116 | 0.674501 |
2614262e0856527a5b00daef7a21ac1db2f4a937 | 5,811 | // RUN: rm -rf %t && mkdir -p %t
// RUN: %target-swift-frontend -emit-module %S/Inputs/PrivateObjC.swift -o %t
// RUN: %target-parse-verify-swift -I %t
// REQUIRES: objc_interop
import Foundation
import PrivateObjC
@objc
class A {
init() {}
}
@objc
class B : A {
override init() { super.init() }
}
@objc
class C {
init() {}
}
class X {
init() {}
@objc func foo(_ i: Int) { }
@objc func bar() { }
@objc func ovl2() -> A { } // expected-note{{found this candidate}}
@objc func ovl4() -> B { }
@objc func ovl5() -> B { } // expected-note{{found this candidate}}
@objc class func staticFoo(_ i : Int) { }
@objc func prop3() -> Int { return 5 }
}
class Y : P {
init() {}
@objc func foo(_ s: String) { }
@objc func wibble() { }
@objc func ovl1() -> A { }
@objc func ovl4() -> B { }
@objc func ovl5() -> C { } // expected-note{{found this candidate}}
@objc var prop1 : Int {
get {
return 5
}
}
var _prop2 : String
@objc var prop2 : String {
get {
return _prop2
}
set(value) {
_prop2 = value
}
}
@objc var prop3 : Int {
get {
return 5
}
}
@objc subscript (idx : Int) -> String {
get {
return "hello"
}
set {}
}
}
class Z : Y {
@objc override func ovl1() -> B { }
@objc func ovl2() -> C { } // expected-note{{found this candidate}}
@objc(ovl3_A) func ovl3() -> A { }
@objc func ovl3() -> B { }
func generic4<T>(_ x : T) { }
}
@objc protocol P {
func wibble()
}
@objc protocol P2 {
func wonka()
var protoProp : Int { get }
static func staticWibble()
subscript (idx : A) -> Int { get set }
}
struct S {
func wobble() { }
}
class D<T> {
func generic1(_ x : T) { }
}
extension Z {
@objc func ext1() -> A { }
}
// Find methods via dynamic method lookup.
typealias Id = AnyObject
var obj : Id = X()
obj.bar!()
obj.foo!(5)
obj.foo!("hello")
obj.wibble!()
obj.wobble!() // expected-error{{value of type 'Id' (aka 'AnyObject') has no member 'wobble'}}
obj.ext1!() // expected-warning {{result of call is unused}}
obj.wonka!()
// Same as above but without the '!'
obj.bar()
obj.foo(5)
obj.foo("hello")
obj.wibble()
obj.wobble() // expected-error{{value of type 'Id' (aka 'AnyObject') has no member 'wobble'}}
obj.ext1() // expected-warning {{result of call is unused}}
obj.wonka()
// Find class methods via dynamic method lookup.
obj.dynamicType.staticFoo!(5)
obj.dynamicType.staticWibble!()
// Same as above but without the '!'
obj.dynamicType.staticFoo(5)
obj.dynamicType.staticWibble()
// Overloading and ambiguity resolution
// When we have overriding, pick the least restrictive declaration.
var ovl1Result = obj.ovl1!()
ovl1Result = A() // verify that we got an A, not a B
// Same as above but without the '!'
obj.ovl1() // expected-warning {{result of call is unused}}
// Don't allow overload resolution between declarations from different
// classes.
var ovl2ResultA = obj.ovl2!() // expected-error{{ambiguous use of 'ovl2()'}}
// ... but it's okay to allow overload resolution between declarations
// from the same class.
var ovl3Result = obj.ovl3!()
ovl3Result = B()
// For [objc] declarations, we can ignore declarations with the same
// selector and type.
var ovl4Result = obj.ovl4!()
// ... but not when the types are different.
var ovl5Result = obj.ovl5!() // expected-error{{ambiguous use of 'ovl5()'}}
// Same as above but without the '!'
obj.ovl4() // expected-warning {{result of call is unused}}
// Generics
// Dynamic lookup cannot find members of a generic class (or a class
// that's a member of anything generic), because we wouldn't be able
// to figure out the generic arguments.
var generic1Result = obj.generic1!(17) // expected-error{{value of type 'Id' (aka 'AnyObject') has no member 'generic1'}}
obj.generic2!() // expected-error{{value of type 'Id' (aka 'AnyObject') has no member 'generic2'}}
obj.generic3!() // expected-error{{value of type 'Id' (aka 'AnyObject') has no member 'generic3'}}
// Dynamic method lookup can't find non-[objc] members
obj.generic4!(5) // expected-error{{value of type 'Id' (aka 'AnyObject') has no member 'generic4'}}
// Find properties via dynamic lookup.
var prop1Result : Int = obj.prop1!
var prop2Result : String = obj.prop2!
obj.prop2 = "hello" // expected-error{{cannot assign to property: 'obj' is immutable}}
var protoPropResult : Int = obj.protoProp!
// Find subscripts via dynamic lookup
var sub1Result : String = obj[5]!
var sub2Result : Int = obj[A()]!
// Subscript then call without the '!'
var sub1ResultNE = obj[5].hasPrefix("foo")
var sub2ResultNE = obj[A()].hashValue
// Property/function ambiguities.
var prop3ResultA : Int? = obj.prop3
var prop3ResultB : (() -> Int)? = obj.prop3
var prop3ResultC = obj.prop3
let prop3ResultCChecked: Int? = prop3ResultC
var obj2 : protocol<AnyObject, P> = Y()
class Z2 : AnyObject { }
class Z3<T : AnyObject> { }
class Z4<T where T : AnyObject> { }
// Don't allow one to call instance methods on the Type via
// dynamic method lookup.
obj.dynamicType.foo!(obj)(5) // expected-error{{instance member 'foo' cannot be used on type 'Id' (aka 'AnyObject')}}
// Checked casts to AnyObject
var p: P = Y()
// expected-warning @+1 {{forced cast from 'P' to 'AnyObject' always succeeds; did you mean to use 'as'?}}
var obj3 : AnyObject = (p as! AnyObject)! // expected-error{{cannot force unwrap value of non-optional type 'AnyObject'}} {{41-42=}}
// Implicit force of an implicitly unwrapped optional
let uopt : AnyObject! = nil
uopt.wibble!()
// Should not be able to see private or internal @objc methods.
uopt.privateFoo!() // expected-error{{'privateFoo' is inaccessible due to 'private' protection level}}
uopt.internalFoo!() // expected-error{{'internalFoo' is inaccessible due to 'internal' protection level}}
| 26.175676 | 132 | 0.656858 |
87c1e7151c65694ee5ddaa85bfbf43bf76b893db | 756 | import Foundation
import ProjectDescription
import TSCBasic
import TuistCore
import TuistSupport
extension TuistCore.DefaultSettings {
/// Maps a ProjectDescription.DefaultSettings instance into a TuistCore.DefaultSettings model.
/// - Parameters:
/// - manifest: Manifest representation of default settings.
/// - generatorPaths: Generator paths.
static func from(manifest: ProjectDescription.DefaultSettings) -> TuistCore.DefaultSettings {
switch manifest {
case let .recommended(excludedKeys):
return .recommended(excluding: excludedKeys)
case let .essential(excludedKeys):
return .essential(excluding: excludedKeys)
case .none:
return .none
}
}
}
| 32.869565 | 98 | 0.698413 |
75c1de8dc892e0a2d955a1532a24ca59aedcc64e | 369 | //
// UIViewController+.swift
// Weather
//
// Created by akashlal on 12/03/22.
//
import Foundation
import UIKit
extension UIViewController {
static func loadFromNib() -> Self {
func instantiateFromNib<T: UIViewController>() -> T {
T(nibName: String(describing: T.self), bundle: nil)
}
return instantiateFromNib()
}
}
| 18.45 | 63 | 0.628726 |
7117e2a5a245e44b6b4fcecd971aa3dea5baf1ac | 1,484 | // swift-tools-version:5.3
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "core-database",
platforms: [
.iOS(.v14),
],
products: [
// Products define the executables and libraries a package produces, and make them visible to other packages.
.library(
name: "CoreDatabase",
targets: ["CoreDatabase"]
),
],
dependencies: [
.package(name: "Overture", url: "https://github.com/pointfreeco/swift-overture.git", from: "0.5.0"),
.package(name: "core", url: "https://github.com/Qase/swift-core.git", .branch("master")),
.package(name: "overture-operators", url: "https://github.com/Qase/swift-overture-operators.git", .branch("master")),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages this package depends on.
.target(
name: "CoreDatabase",
dependencies: [
"Overture",
.product(name: "Core", package: "core"),
.product(name: "OvertureOperators", package: "overture-operators"),
]
),
.testTarget(
name: "CoreDatabaseTests",
dependencies: ["CoreDatabase"]
),
]
)
| 37.1 | 125 | 0.593666 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.