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
|
---|---|---|---|---|---|
e9b8c772d70c7d637be89a5da47d8ebb9f9c93a3 | 13,001 | /*
* Copyright (c) 2016, Nordic Semiconductor
* 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.
*/
// Errors
internal enum DFUStreamZipError : Error {
case noManifest
case invalidManifest
case fileNotFound
case typeNotFound
var description: String {
switch self {
case .noManifest: return NSLocalizedString("No manifest file found", comment: "")
case .invalidManifest: return NSLocalizedString("Invalid manifest.json file", comment: "")
case .fileNotFound: return NSLocalizedString("File specified in manifest.json not found in ZIP", comment: "")
case .typeNotFound: return NSLocalizedString("Specified type not found in manifest.json", comment: "")
}
}
}
internal class DFUStreamZip : DFUStream {
private static let MANIFEST_FILE = "manifest.json"
private(set) var currentPart = 1
private(set) var parts = 1
private(set) var currentPartType: UInt8 = 0
/// The parsed manifest file if such found, nil otherwise.
private var manifest: Manifest?
/// Binaries with softdevice and bootloader.
private var systemBinaries: Data?
/// Binaries with an app.
private var appBinaries: Data?
/// System init packet.
private var systemInitPacket: Data?
/// Application init packet.
private var appInitPacket: Data?
private var currentBinaries: Data?
private var currentInitPacket: Data?
private var softdeviceSize : UInt32 = 0
private var bootloaderSize : UInt32 = 0
private var applicationSize : UInt32 = 0
var size: DFUFirmwareSize {
return DFUFirmwareSize(softdevice: softdeviceSize, bootloader: bootloaderSize, application: applicationSize)
}
var currentPartSize: DFUFirmwareSize {
// If the ZIP file will be transferred in one part, return all sizes. Two of them will be 0.
if parts == 1 {
return DFUFirmwareSize(softdevice: softdeviceSize, bootloader: bootloaderSize, application: applicationSize)
}
// Else, return sizes based on the current part number. First the SD and/or BL are uploaded
if currentPart == 1 {
return DFUFirmwareSize(softdevice: softdeviceSize, bootloader: bootloaderSize, application: 0)
}
// and then the application.
return DFUFirmwareSize(softdevice: 0, bootloader: 0, application: applicationSize)
}
/**
Initializes the stream with given data of a ZIP file.
- parameter zipFile: Content of the ZIP file with firmware files and manifest.json file containing metadata.
- parameter type: The type of the firmware to use
- throws: DFUStreamZipError when manifest file was not found or contained an error
- returns: the stream
*/
convenience init(zipFile: Data, type: DFUFirmwareType) throws {
let url = try ZipArchive.createTemporaryFile(zipFile)
try self.init(urlToZipFile: url, type: type)
}
/**
Initializes the stream with URL to the ZIP file.
- parameter urlToZipFile: URL to the ZIP file with firmware files and manifest.json file containing metadata.
- parameter type: The type of the firmware to use
- throws: DFUStreamZipError when manifest file was not found or contained an error
- returns: the stream
*/
init(urlToZipFile: URL, type: DFUFirmwareType) throws {
// Try to unzip the file. This may throw an exception
let contentUrls = try ZipArchive.unzip(urlToZipFile)
// Look for MANIFEST_FILE
let manifestUrl = ZipArchive.findFile(DFUStreamZip.MANIFEST_FILE, inside: contentUrls)
if let url = manifestUrl {
// Read manifest content
let json = try String(contentsOf: url)
// Deserialize json
manifest = Manifest(withJsonString: json)
if manifest!.valid {
// After validation we are sure that the manifest file contains at most one
// of: softdeviceBootloader, softdevice or bootloader
// Look for and assign files specified in the manifest
let softdeviceBootloaderType = FIRMWARE_TYPE_SOFTDEVICE | FIRMWARE_TYPE_BOOTLOADER
if type.rawValue & softdeviceBootloaderType == softdeviceBootloaderType {
if let softdeviceBootloader = manifest!.softdeviceBootloader {
let (bin, dat) = try getContentOf(softdeviceBootloader, from: contentUrls)
systemBinaries = bin
systemInitPacket = dat
if softdeviceBootloader.sdSize + softdeviceBootloader.blSize > 0 {
softdeviceSize = softdeviceBootloader.sdSize
bootloaderSize = softdeviceBootloader.blSize
} else {
// Secure DFU does not specify SD and BL sizes in the manifest file
// (actually it does, but as an optional read_only value).
// The exact sizes of SD and BL are not known (only the sum is),
// but some applications may rely on size > 0, so let's just say there is a bootloader.
softdeviceSize = UInt32(bin.count) - 1
bootloaderSize = 1
}
currentPartType = softdeviceBootloaderType
}
}
let softdeviceType = FIRMWARE_TYPE_SOFTDEVICE
if type.rawValue & softdeviceType == softdeviceType {
if let softdevice = manifest!.softdevice {
if systemBinaries != nil {
// It is not allowed to put both softdevice and softdeviceBootloader in the manifest
throw DFUStreamZipError.invalidManifest
}
let (bin, dat) = try getContentOf(softdevice, from: contentUrls)
systemBinaries = bin
systemInitPacket = dat
softdeviceSize = UInt32(bin.count)
currentPartType = softdeviceType
}
}
let bootloaderType = FIRMWARE_TYPE_BOOTLOADER
if type.rawValue & bootloaderType == bootloaderType {
if let bootloader = manifest!.bootloader {
if systemBinaries != nil {
// It is not allowed to put both bootloader and softdeviceBootloader in the manifest
throw DFUStreamZipError.invalidManifest
}
let (bin, dat) = try getContentOf(bootloader, from: contentUrls)
systemBinaries = bin
systemInitPacket = dat
bootloaderSize = UInt32(bin.count)
currentPartType = bootloaderType
}
}
let applicationType = FIRMWARE_TYPE_APPLICATION
if type.rawValue & applicationType == applicationType {
if let application = manifest!.application {
let (bin, dat) = try getContentOf(application, from: contentUrls)
appBinaries = bin
appInitPacket = dat
applicationSize = UInt32(bin.count)
if currentPartType == 0 {
currentPartType = applicationType
} else {
// Otherwise the app will be sent as part 2
// It is not possible to send SD+BL+App in a single connection, due to a fact that
// the softdevice_bootloade_application section is not defined for the manifest.json file.
// It would be possible to send both bin (systemBinaries and appBinaries), but there are
// two dat files with two Init Packets and non of them matches two combined binaries.
}
}
}
if systemBinaries == nil && appBinaries == nil {
// The specified type is not included in the manifest.
throw DFUStreamZipError.typeNotFound
}
else if systemBinaries != nil {
currentBinaries = systemBinaries
currentInitPacket = systemInitPacket
} else {
currentBinaries = appBinaries
currentInitPacket = appInitPacket
}
// If the ZIP file contains an app and a softdevice or bootloader,
// the content will be sent in 2 parts.
if systemBinaries != nil && appBinaries != nil {
parts = 2
}
} else {
throw DFUStreamZipError.invalidManifest
}
} else { // no manifest file
// This library does not support the old, deprecated name-based ZIP files
// Please, use the nrf-util app to create a new Distribution packet
throw DFUStreamZipError.noManifest
}
}
/**
This method checks if the FirmwareInfo object is valid (has both bin and dat files specified),
adds those files to binUrls and datUrls arrays and returns the length of the bin file in bytes.
- parameter info: the metadata obtained from the manifest file
- parameter contentUrls: the list of URLs to the unzipped files
- throws: DFUStreamZipError when file specified in the metadata was not found in the ZIP
- returns: content bin and dat files
*/
fileprivate func getContentOf(_ info: ManifestFirmwareInfo, from contentUrls: [URL]) throws -> (Data, Data?) {
if !info.valid {
throw DFUStreamZipError.invalidManifest
}
// Get the URLs to the bin and dat files specified in the FirmwareInfo
let bin = ZipArchive.findFile(info.binFile!, inside: contentUrls)
var dat: URL? = nil
if let datFile = info.datFile {
dat = ZipArchive.findFile(datFile, inside: contentUrls)
}
// Check if the files were found in the ZIP
if bin == nil || (info.datFile != nil && dat == nil) {
throw DFUStreamZipError.fileNotFound
}
// Read content of those files
let binData = try! Data(contentsOf: bin!)
var datData: Data? = nil
if let dat = dat {
datData = try! Data(contentsOf: dat)
}
return (binData, datData)
}
var data: Data {
return currentBinaries!
}
var initPacket: Data? {
return currentInitPacket
}
func hasNextPart() -> Bool {
return currentPart < parts
}
func switchToNextPart() {
if currentPart == 1 && parts == 2 {
currentPart = 2
currentPartType = FIRMWARE_TYPE_APPLICATION
currentBinaries = appBinaries
currentInitPacket = appInitPacket
}
}
}
| 45.939929 | 144 | 0.595262 |
9178dcccee890a1a96d683ac8de56d6b075dd617 | 3,161 | /*
Copyright 2021 The Fuel Rats Mischief
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 Foundation
import JSONAPI
extension Int64: CreatableRawIdType {
public static func unique() -> Int64 {
return Int64.random(in: 0...9999999999999)
}
}
typealias SystemsAPIJSONEntity<Description: ResourceObjectDescription> =
JSONAPI.ResourceObject<Description, NoMetadata, NoLinks, String>
typealias SystemsAPIDocument<PrimaryResourceBody: JSONAPI.CodableResourceBody, IncludeType: JSONAPI.Include> = JSONAPI.Document<
PrimaryResourceBody,
NoMetadata,
JSONAPILinks,
IncludeType,
NoAPIDescription,
BasicJSONAPIError<String>
>
typealias SystemGetDocument = SystemsAPIDocument<SingleResourceBody<SystemsAPI.System>, Include3<SystemsAPI.Star, SystemsAPI.Body, SystemsAPI.Station>>
enum SystemDescription: ResourceObjectDescription {
public static var jsonType: String { return "systems" }
public struct Attributes: JSONAPI.Attributes {
public var name: Attribute<String>
public var coords: Attribute<Vector3>
}
public struct Relationships: JSONAPI.Relationships {
public let stars: ToManyRelationship<SystemsAPI.Star>?
public let planets: ToManyRelationship<SystemsAPI.Body>?
public let stations: ToManyRelationship<SystemsAPI.Station>?
}
}
extension SystemsAPI {
typealias System = SystemsAPIJSONEntity<SystemDescription>
enum CelestialBodyType: String, Codable {
case Planet
case Star
}
struct Belt: Codable, Equatable {
public var mass: Double?
public var name: String?
public var type: String?
public var innerRadius: Double?
public var outerRadius: Double?
}
}
| 40.012658 | 151 | 0.76305 |
4bdbec4817d5ab8a1a17ce0e25034618152be0a9 | 10,968 | import CoreData
import CoreSpotlight
import Foundation
import Intents
import Search
import TBAData
import TBAKit
import TBAUtils
private struct SearchConstants {
static let lastRefreshEventsAllKey = "kLastRefreshAllEvents"
static let lastRefreshTeamsAllKey = "kLastRefreshAllTeams"
}
public class SearchService: NSObject, TeamsRefreshProvider {
let batchSize = 1000
private let application: UIApplication
private let errorRecorder: ErrorRecorder
private let indexDelegate: TBACoreDataCoreSpotlightDelegate
private let persistentContainer: NSPersistentContainer
private let searchIndex: CSSearchableIndex
private let statusService: StatusService
private let tbaKit: TBAKit
private let userDefaults: UserDefaults
private(set) var refreshOperation: Operation?
private var eventsRefreshOperation: Operation?
private var teamsRefreshOperation: Operation?
private(set) var operationQueue = OperationQueue()
public init(application: UIApplication, errorRecorder: ErrorRecorder, indexDelegate: TBACoreDataCoreSpotlightDelegate, persistentContainer: NSPersistentContainer, searchIndex: CSSearchableIndex, statusService: StatusService, tbaKit: TBAKit, userDefaults: UserDefaults) {
self.application = application
self.errorRecorder = errorRecorder
self.indexDelegate = indexDelegate
self.persistentContainer = persistentContainer
self.searchIndex = searchIndex
self.statusService = statusService
self.tbaKit = tbaKit
self.userDefaults = userDefaults
super.init()
searchIndex.indexDelegate = self
}
// MARK: Public Methods
@discardableResult
public func refresh(userInitiated: Bool = false) -> Operation {
if let refreshOperation = refreshOperation {
return refreshOperation
}
var eventsOperation: TBAKitOperation!
if shouldRefreshAllEvents || userInitiated {
eventsOperation = tbaKit.fetchEvents() { [unowned self] (result, notModified) in
guard case .success(let events) = result, !notModified else {
return
}
// TODO: NSBatchInsertRequest/NSBatchDeleteRequest
let managedObjectContext = self.persistentContainer.newBackgroundContext()
managedObjectContext.performChangesAndWait({
// Batch insert/save our events
// Fetch all of our existing events so we can clean up orphans
let oldEvents = Event.fetch(in: managedObjectContext)
var newEvents: [Event] = []
for i in stride(from: events.startIndex, to: events.endIndex, by: self.batchSize) {
let subEvents = Array(events[i..<min(i + self.batchSize, events.count)])
newEvents.append(contentsOf: subEvents.map {
return Event.insert($0, in: managedObjectContext)
})
managedObjectContext.saveOrRollback(errorRecorder: self.errorRecorder)
}
// Delete orphaned Events for this year
let orphanedEvents = Array(Set(oldEvents).subtracting(Set(newEvents)))
for i in stride(from: orphanedEvents.startIndex, to: orphanedEvents.endIndex, by: self.batchSize) {
let subEvents = Array(orphanedEvents[i..<min(i + self.batchSize, orphanedEvents.count)])
subEvents.forEach {
managedObjectContext.delete($0)
}
managedObjectContext.saveOrRollback(errorRecorder: self.errorRecorder)
}
}, saved: {
self.tbaKit.storeCacheHeaders(eventsOperation)
self.userDefaults.set(Date(), forKey: SearchConstants.lastRefreshEventsAllKey)
self.userDefaults.synchronize()
}, errorRecorder: self.errorRecorder)
}
} else {
let year = statusService.currentSeason
eventsOperation = tbaKit.fetchEvents(year: year) { [unowned self] (result, notModified) in
guard case .success(let events) = result, !notModified else {
return
}
let context = self.persistentContainer.newBackgroundContext()
context.performChangesAndWait({
Event.insert(events, year: year, in: context)
}, saved: {
self.tbaKit.storeCacheHeaders(eventsOperation)
}, errorRecorder: self.errorRecorder)
}
}
eventsOperation.completionBlock = {
self.eventsRefreshOperation = nil
}
self.eventsRefreshOperation = eventsOperation
let teamsOperation = refreshTeams(userInitiated: userInitiated)
teamsOperation?.completionBlock = {
self.teamsRefreshOperation = nil
}
self.teamsRefreshOperation = teamsOperation
// If our refresh is system-initiated, setup a background task which will be
// to ensure all tasks finish before the app is killed in the background
var backgroundTaskIdentifier: UIBackgroundTaskIdentifier?
if userInitiated {
backgroundTaskIdentifier = self.application.beginBackgroundTask {
self.operationQueue.cancelAllOperations()
if let backgroundTaskIdentifier = backgroundTaskIdentifier {
self.application.endBackgroundTask(backgroundTaskIdentifier)
}
}
}
let refreshOperation = Operation()
refreshOperation.completionBlock = {
self.refreshOperation = nil
if let backgroundTaskIdentifier = backgroundTaskIdentifier {
self.application.endBackgroundTask(backgroundTaskIdentifier)
}
}
[eventsOperation, teamsOperation].compactMap({ $0 }).forEach { (op: Operation) in
refreshOperation.addDependency(op)
}
operationQueue.addOperations([eventsOperation, teamsOperation, refreshOperation].compactMap({ $0 }), waitUntilFinished: false)
self.refreshOperation = refreshOperation
return refreshOperation
}
public var shouldRefreshAllEvents: Bool {
// Only automatically refresh all Events once - otherwise, fetch only the current season events
let lastRefreshAllEvents = userDefaults.value(forKey: SearchConstants.lastRefreshEventsAllKey) as? Date
return lastRefreshAllEvents == nil
}
public var shouldRefreshTeams: Bool {
// Only automatically refresh all Teams once-per-day
let lastRefreshAllTeams = userDefaults.value(forKey: SearchConstants.lastRefreshTeamsAllKey) as? Date
var diffInDays = 0
if let lastRefreshAllTeams = lastRefreshAllTeams, let days = Calendar.current.dateComponents([.day], from: lastRefreshAllTeams, to: Date()).day {
diffInDays = days
}
return lastRefreshAllTeams == nil || diffInDays >= 1
}
public func refreshTeams(userInitiated: Bool) -> Operation? {
if let teamsRefreshOperation = teamsRefreshOperation {
return teamsRefreshOperation
}
var teamsOperation: TBAKitOperation?
if shouldRefreshTeams || userInitiated {
teamsOperation = tbaKit.fetchTeams() { [unowned self] (result, notModified) in
guard case .success(let teams) = result, !notModified else {
return
}
// TODO: NSBatchInsertRequest/NSBatchDeleteRequest
let managedObjectContext = self.persistentContainer.newBackgroundContext()
managedObjectContext.performChangesAndWait({
// Batch insert/save our teams
// Fetch all of our existing teams so we can clean up orphans
let oldTeams = Team.fetch(in: managedObjectContext)
var newTeams: [Team] = []
for i in stride(from: teams.startIndex, to: teams.endIndex, by: self.batchSize) {
let subTeams = Array(teams[i..<min(i + self.batchSize, teams.count)])
newTeams.append(contentsOf: subTeams.map {
return Team.insert($0, in: managedObjectContext)
})
managedObjectContext.saveOrRollback(errorRecorder: self.errorRecorder)
}
// Delete orphaned Teams for this year
let orphanedTeams = Array(Set(oldTeams).subtracting(Set(newTeams)))
for i in stride(from: orphanedTeams.startIndex, to: orphanedTeams.endIndex, by: self.batchSize) {
let subTeams = Array(orphanedTeams[i..<min(i + self.batchSize, orphanedTeams.count)])
subTeams.forEach {
managedObjectContext.delete($0)
}
managedObjectContext.saveOrRollback(errorRecorder: self.errorRecorder)
}
}, saved: {
self.tbaKit.storeCacheHeaders(teamsOperation!)
self.userDefaults.set(Date(), forKey: SearchConstants.lastRefreshTeamsAllKey)
self.userDefaults.synchronize()
}, errorRecorder: self.errorRecorder)
}
}
return teamsOperation
}
public func deleteSearchIndex(errorRecorder: ErrorRecorder) {
deleteLastRefresh()
searchIndex.deleteAllSearchableItems { [unowned self] (error) in
if let error = error {
print(error)
self.errorRecorder.recordError(error)
}
}
}
// MARK: - Private Methods
private func deleteLastRefresh() {
self.userDefaults.removeObject(forKey: SearchConstants.lastRefreshEventsAllKey)
self.userDefaults.removeObject(forKey: SearchConstants.lastRefreshTeamsAllKey)
self.userDefaults.synchronize()
}
}
extension SearchService: CSSearchableIndexDelegate {
public func searchableIndex(_ searchableIndex: CSSearchableIndex, reindexAllSearchableItemsWithAcknowledgementHandler acknowledgementHandler: @escaping () -> Void) {
indexDelegate.searchableIndex(searchableIndex, reindexAllSearchableItemsWithAcknowledgementHandler: acknowledgementHandler)
}
public func searchableIndex(_ searchableIndex: CSSearchableIndex, reindexSearchableItemsWithIdentifiers identifiers: [String], acknowledgementHandler: @escaping () -> Void) {
indexDelegate.searchableIndex(searchableIndex, reindexSearchableItemsWithIdentifiers: identifiers, acknowledgementHandler: acknowledgementHandler)
}
}
| 44.225806 | 274 | 0.637673 |
fc9fc64506ff73f253ddcb005fd543aee6b67e09 | 4,822 | //
// ListExpansionsViewControllerTests.swift
// DominionDeckBuilder
//
// Created by David on 2/2/17.
// Copyright (c) 2017 damarte. All rights reserved.
//
// This file was generated by the Clean Swift Xcode Templates so you can apply
// clean architecture to your iOS and Mac projects, see http://clean-swift.com
//
import XCTest
@testable import DominionDeckBuilder
class ListExpansionsViewControllerTests: XCTestCase
{
// MARK: - Subject under test
var sut: ListExpansionsViewController!
var window: UIWindow!
// MARK: - Test lifecycle
override func setUp()
{
super.setUp()
window = UIWindow()
setupListExpansionsViewController()
}
override func tearDown()
{
window = nil
super.tearDown()
}
// MARK: - Test setup
func setupListExpansionsViewController()
{
let bundle = Bundle.main
let storyboard = UIStoryboard(name: "Main", bundle: bundle)
sut = storyboard.instantiateViewController(withIdentifier: "ListExpansionsViewController") as! ListExpansionsViewController
}
func loadView()
{
window.addSubview(sut.view)
RunLoop.current.run(until: Date())
}
// MARK: Test doubles
class ListExpansionsViewControllerOutputSpy: ListExpansionsViewControllerOutput
{
var expansions: [Expansion]?
// MARK: Method call expectations
var fetchExpansionsCalled = false
// MARK: Spied methods
func fetchExpansions(request: ListExpansions.FetchExpansions.Request)
{
fetchExpansionsCalled = true
}
}
class TableViewSpy: UITableView
{
// MARK: Method call expectations
var reloadDataCalled = false
// MARK: Spied methods
override func reloadData()
{
reloadDataCalled = true
}
}
// MARK: - Tests
func testShouldFetchExpansionsWhenViewIsLoaded()
{
// Given
let listExpansionsViewControllerOutputSpy = ListExpansionsViewControllerOutputSpy()
sut.output = listExpansionsViewControllerOutputSpy
// When
loadView()
// Then
XCTAssert(listExpansionsViewControllerOutputSpy.fetchExpansionsCalled, "Should fetch expansions when the view is loaded")
}
func testShouldDisplayFetchedExpansions()
{
// Given
let tableViewSpy = TableViewSpy()
sut.tableView = tableViewSpy
let displayedExpansions = [ListExpansions.FetchExpansions.ViewModel.DisplayedExpansion(name: "Dominion", numCards: 0)]
let viewModel = ListExpansions.FetchExpansions.ViewModel(displayedExpansions: displayedExpansions)
// When
sut.displayFetchedExpansions(viewModel: viewModel)
// Then
XCTAssert(tableViewSpy.reloadDataCalled, "Displaying fetched expansions should reload the table view")
}
func testNumberOfSectionsInTableViewShouldAlwaysBeOne()
{
loadView()
// Given
let tableView = sut.tableView
// When
let numberOfSections = sut.numberOfSections(in: tableView!)
// Then
XCTAssertEqual(numberOfSections, 1, "The number of table view sections should always be 1")
}
func testNumberOfRowsInAnySectionShouldEqaulNumberOfOrdersToDisplay()
{
loadView()
// Given
let tableView = sut.tableView
let testDisplayedExpansions = [ListExpansions.FetchExpansions.ViewModel.DisplayedExpansion(name: "Dominion", numCards: 0)]
sut.displayedExpansions = testDisplayedExpansions
// When
let numberOfRows = sut.tableView(tableView!, numberOfRowsInSection: 0)
// Then
XCTAssertEqual(numberOfRows, testDisplayedExpansions.count, "The number of table view rows should equal the number of objects to display")
}
func testShouldConfigureTableViewCellToDisplayOrder()
{
loadView()
// Given
let tableView = sut.tableView
let testDisplayedOrders = [ListExpansions.FetchExpansions.ViewModel.DisplayedExpansion(name: "Dominion", numCards: 0)]
sut.displayedExpansions = testDisplayedOrders
// When
let indexPath = IndexPath(item: 0, section: 0)
let cell = sut.tableView(tableView!, cellForRowAt: indexPath)
// Then
XCTAssertEqual(cell.textLabel?.text, "Dominion", "A properly configured table view cell should display the title")
XCTAssertEqual(cell.detailTextLabel?.text, "0 cards", "A properly configured table view cell should display the subtitle")
}
}
| 30.327044 | 146 | 0.645998 |
fc93b7ba76639b1d7e77b9a370877c806a0d44c4 | 419 | //
// MockSystemAudioPlayer.swift
// KeyboardKit
//
// Created by Daniel Saidi on 2021-04-01.
// Copyright © 2021 Daniel Saidi. All rights reserved.
//
import KeyboardKit
import MockingKit
class MockSystemAudioPlayer: Mock, SystemAudioPlayer {
lazy var playSystemAudioRef = MockReference(playSystemAudio)
func playSystemAudio(_ id: UInt32) {
call(playSystemAudioRef, args: (id))
}
}
| 20.95 | 64 | 0.708831 |
8730f4818d3aec3d41ae43967da5cf7b37a87f62 | 512 | // swift-tools-version:5.3
import PackageDescription
let package = Package(
name: "GildedRose",
products: [
.library(
name: "GildedRose",
targets: ["GildedRose"]),
],
targets: [
.target(
name: "GildedRose",
dependencies: []),
.target(
name: "GildedRoseApp",
dependencies: ["GildedRose"]),
.testTarget(
name: "GildedRoseTests",
dependencies: ["GildedRose"]),
]
)
| 21.333333 | 42 | 0.498047 |
62e098d8d1c2d2d5ebfc8644ad1835bbf255b4f1 | 8,648 | // License Agreement for FDA MyStudies
// Copyright © 2017-2019 Harvard Pilgrim Health Care Institute (HPHCI) and its Contributors. 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.
// Funding Source: Food and Drug Administration (“Funding Agency”) effective 18 September 2014 as
// Contract no. HHSF22320140030I/HHSF22301006T (the “Prime Contract”).
// 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
// OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
import Foundation
import UIKit
protocol PageViewControllerDelegate: class {
//Parameter count: the total number of pages.
func pageViewController(
pageViewController: PageViewController,
didUpdatePageCount count: Int
)
//Parameter index: the index of the currently visible page.
func pageViewController(
pageViewController: PageViewController,
didUpdatePageIndex index: Int
)
}
class PageViewController: UIPageViewController {
weak var pageViewDelegate: PageViewControllerDelegate?
var overview: Overview!
lazy var currentIndex = 0
// MARK: - ViewController Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
dataSource = self
delegate = self
if let initialViewController = orderedViewControllers.first {
scrollToViewController(viewController: initialViewController)
}
pageViewDelegate?.pageViewController(
pageViewController: self,
didUpdatePageCount: orderedViewControllers.count
)
let scrollView = (self.view.subviews.filter { $0 is UIScrollView }.first as? UIScrollView)!
scrollView.delegate = self
}
// MARK: - Scroll Delegates
/// Scrolls to the given 'viewController' page.
private func scrollToViewController(
viewController: UIViewController,
direction: UIPageViewController.NavigationDirection = .forward
) {
setViewControllers(
[viewController],
direction: direction,
animated: true,
completion: { (_) -> Void in
// Setting the view controller programmatically does not fire
// any delegate methods, so we have to manually notify the
// 'tutorialDelegate' of the new index.
self.notifyTutorialDelegateOfNewIndex(prevViewController: nil)
}
)
}
/// Used to Notify that the current page index was updated.
func notifyTutorialDelegateOfNewIndex(prevViewController: UIViewController?) {
var index = 0
if prevViewController != nil {
index = orderedViewControllers.firstIndex(of: prevViewController!)!
} else {
let viewController = self.viewControllers?.last
switch viewController {
case is FirstGatewayOverviewViewController:
index = (viewController as? FirstGatewayOverviewViewController)!.pageIndex
case is SecondGatewayOverviewViewController:
index = (viewController as? SecondGatewayOverviewViewController)!.pageIndex
case is StudyOverviewViewControllerFirst:
index = (viewController as? StudyOverviewViewControllerFirst)!.pageIndex
case is StudyOverviewViewControllerSecond:
index = (viewController as? StudyOverviewViewControllerSecond)!.pageIndex
default:
index = 0
}
}
pageViewDelegate?.pageViewController(pageViewController: self, didUpdatePageIndex: index)
}
private(set) lazy var orderedViewControllers: [UIViewController] = {
return self.getOverviewViewControllers()
}()
/// Used to get the Viewcontrollers from Study or Overview
/// - Returns: Array of OverView controllers instances.
private func getOverviewViewControllers() -> [UIViewController] {
var controllers: [UIViewController] = []
var storyboard = UIStoryboard.init(name: kLoginStoryboardIdentifier, bundle: Bundle.main)
if overview.type == .study {
storyboard = UIStoryboard.init(name: kStudyStoryboard, bundle: Bundle.main)
// get first overview controller
let firstController =
(storyboard.instantiateViewController(withIdentifier: "FirstViewController")
as? StudyOverviewViewControllerFirst)!
firstController.pageIndex = 0
firstController.overViewWebsiteLink = overview.websiteLink
firstController.overviewSectionDetail = overview.sections[0]
controllers.append(firstController)
if overview.sections.count >= 2 {
let sections = overview.sections.count
for section in 1...(sections - 1) {
let restControllers =
(storyboard.instantiateViewController(withIdentifier: "SecondViewController")
as? StudyOverviewViewControllerSecond)!
restControllers.overviewSectionDetail = overview.sections[section]
restControllers.overViewWebsiteLink = overview.websiteLink
restControllers.pageIndex = section
controllers.append(restControllers)
}
}
} else {
// get first overview controller
let firstController =
(storyboard.instantiateViewController(withIdentifier: "FirstViewController")
as? FirstGatewayOverviewViewController)!
firstController.overviewSectionDetail = overview.sections[0]
firstController.pageIndex = 0
controllers.append(firstController)
let sections = overview.sections.count
if sections > 1 {
for section in 1...(sections - 1) {
let restControllers =
(storyboard.instantiateViewController(withIdentifier: "SecondViewController")
as? SecondGatewayOverviewViewController)!
restControllers.overviewSectionDetail = overview.sections[section]
restControllers.pageIndex = section
controllers.append(restControllers)
}
}
}
return controllers
}
}
// MARK: - UIPageViewController DataSource
extension PageViewController: UIPageViewControllerDataSource {
func pageViewController(
_ pageViewController: UIPageViewController,
viewControllerAfter viewController: UIViewController
) -> UIViewController? {
guard let viewControllerIndex = orderedViewControllers.firstIndex(of: viewController) else {
return nil
}
currentIndex = viewControllerIndex
let nextIndex = viewControllerIndex + 1
// Verify if it's already reached to last view controller.
guard orderedViewControllers.count > nextIndex else {
return nil
}
return orderedViewControllers[nextIndex]
}
func pageViewController(
_ pageViewController: UIPageViewController,
viewControllerBefore viewController: UIViewController
) -> UIViewController? {
guard let viewControllerIndex = orderedViewControllers.firstIndex(of: viewController) else {
return nil
}
currentIndex = viewControllerIndex
let previousIndex = viewControllerIndex - 1
guard previousIndex >= 0 else {
return nil
}
return orderedViewControllers[previousIndex]
}
}
// MARK: - UIPageViewControllerDelegate
extension PageViewController: UIPageViewControllerDelegate {
func pageViewController(
_ pageViewController: UIPageViewController,
didFinishAnimating finished: Bool,
previousViewControllers: [UIViewController],
transitionCompleted completed: Bool
) {
if completed {
self.notifyTutorialDelegateOfNewIndex(prevViewController: nil)
} else {
self.notifyTutorialDelegateOfNewIndex(prevViewController: previousViewControllers.last!)
}
}
}
// MARK: - UIScrollview delegates
extension PageViewController: UIScrollViewDelegate {
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
pageViewDelegate?.pageViewController(
pageViewController: self,
didUpdatePageIndex: currentIndex
)
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {}
}
| 35.297959 | 113 | 0.736471 |
2fa760ddfc05106493844d56e617d28fd428cc9e | 235 | final class GreaterThanOperator: BinaryOperator {
override func binary(_ evaluator: Evaluator, _ lhs: JSON, _ rhs: JSON) -> JSON {
if let result = evaluator.compare(lhs, rhs) {
return JSON(result > 0)
}
return JSON.null
}
}
| 26.111111 | 81 | 0.697872 |
4651e32783a5d0f0f80297a3e4573721a607880d | 1,476 | //
// IntentViewController.swift
// XQSiriDemoIntentsUI
//
// Created by WXQ on 2019/9/27.
// Copyright © 2019 WXQ. All rights reserved.
//
import IntentsUI
// As an example, this extension's Info.plist has been configured to handle interactions for INSendMessageIntent.
// You will want to replace this or add other intents as appropriate.
// The intents whose interactions you wish to handle must be declared in the extension's Info.plist.
// You can test this example integration by saying things to Siri like:
// "Send a message using <myApp>"
class IntentViewController: UIViewController, INUIHostedViewControlling {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
print(#function)
}
// MARK: - INUIHostedViewControlling
// Prepare your view controller for the interaction to handle.
func configureView(for parameters: Set<INParameter>, of interaction: INInteraction, interactiveBehavior: INUIInteractiveBehavior, context: INUIHostedViewContext, completion: @escaping (Bool, Set<INParameter>, CGSize) -> Void) {
// Do configuration here, including preparing views and calculating a desired size for presentation.
print(#function)
completion(true, parameters, self.desiredSize)
}
var desiredSize: CGSize {
print(#function)
return self.extensionContext!.hostedViewMaximumAllowedSize
}
}
| 36 | 231 | 0.719512 |
4a7fab1fe6eab234c2d88874a7eca1ac8d4f0d68 | 7,636 | import XCTest
@testable import SwiftKueryORM
import Foundation
import KituraContracts
class TestFind: XCTestCase {
static var allTests: [(String, (TestFind) -> () throws -> Void)] {
return [
("testFind", testFind),
("testFindAll", testFindAll),
("testFindAllMatching", testFindAllMatching),
]
}
struct Person: Model {
static var tableName = "People"
var name: String
var age: Int
}
/**
Testing that the correct SQL Query is created to retrieve a specific model.
Testing that the model can be retrieved
*/
func testFind() {
let connection: TestConnection = createConnection(.returnOneRow)
Database.default = Database(single: connection)
performTest(asyncTasks: { expectation in
Person.find(id: 1) { p, error in
XCTAssertNil(error, "Find Failed: \(String(describing: error))")
XCTAssertNotNil(connection.query, "Find Failed: Query is nil")
if let query = connection.query {
let expectedQuery = "SELECT * FROM \"People\" WHERE \"People\".\"id\" = ?1"
let resultQuery = connection.descriptionOf(query: query)
XCTAssertEqual(resultQuery, expectedQuery, "Find Failed: Invalid query")
}
XCTAssertNotNil(p, "Find Failed: No model returned")
if let p = p {
XCTAssertEqual(p.name, "Joe", "Find Failed: \(String(describing: p.name)) is not equal to Joe")
XCTAssertEqual(p.age, 38, "Find Failed: \(String(describing: p.age)) is not equal to 38")
}
expectation.fulfill()
}
})
}
/**
Testing that the correct SQL Query is created to retrieve a specific model when using a non-default database.
Testing that the model can be retrieved
*/
func testFindUsingDB() {
let connection: TestConnection = createConnection(.returnOneRow)
let db = Database(single: connection)
performTest(asyncTasks: { expectation in
Person.find(id: 1, using: db) { p, error in
XCTAssertNil(error, "Find Failed: \(String(describing: error))")
XCTAssertNotNil(connection.query, "Find Failed: Query is nil")
if let query = connection.query {
let expectedQuery = "SELECT * FROM \"People\" WHERE \"People\".\"id\" = ?1"
let resultQuery = connection.descriptionOf(query: query)
XCTAssertEqual(resultQuery, expectedQuery, "Find Failed: Invalid query")
}
XCTAssertNotNil(p, "Find Failed: No model returned")
if let p = p {
XCTAssertEqual(p.name, "Joe", "Find Failed: \(String(describing: p.name)) is not equal to Joe")
XCTAssertEqual(p.age, 38, "Find Failed: \(String(describing: p.age)) is not equal to 38")
}
expectation.fulfill()
}
})
}
/**
Testing that the correct SQL Query is created to retrieve all the models.
Testing that correct amount of models are retrieved
*/
func testFindAll() {
let connection: TestConnection = createConnection(.returnThreeRows)
Database.default = Database(single: connection)
performTest(asyncTasks: { expectation in
Person.findAll { array, error in
XCTAssertNil(error, "Find Failed: \(String(describing: error))")
XCTAssertNotNil(connection.query, "Find Failed: Query is nil")
if let query = connection.query {
let expectedQuery = "SELECT * FROM \"People\""
let resultQuery = connection.descriptionOf(query: query)
XCTAssertEqual(resultQuery, expectedQuery, "Find Failed: Invalid query")
}
XCTAssertNotNil(array, "Find Failed: No array of models returned")
if let array = array {
XCTAssertEqual(array.count, 3, "Find Failed: \(String(describing: array.count)) is not equal to 3")
}
expectation.fulfill()
}
})
}
struct Filter: QueryParams {
let name: String
let age: Int
}
/**
Testing that the correct SQL Query is created to retrieve all the models.
Testing that correct amount of models are retrieved
*/
func testFindAllMatching() {
let connection: TestConnection = createConnection(.returnOneRow)
Database.default = Database(single: connection)
let filter = Filter(name: "Joe", age: 38)
performTest(asyncTasks: { expectation in
Person.findAll(matching: filter) { array, error in
XCTAssertNil(error, "Find Failed: \(String(describing: error))")
XCTAssertNotNil(connection.query, "Find Failed: Query is nil")
if let query = connection.query {
let expectedPrefix = "SELECT * FROM \"People\" WHERE"
let expectedClauses = [["\"People\".\"name\" = ?1", "\"People\".\"name\" = ?2"], ["\"People\".\"age\" = ?1", "\"People\".\"age\" = ?2"]]
let expectedOperator = "AND"
let resultQuery = connection.descriptionOf(query: query)
XCTAssertTrue(resultQuery.hasPrefix(expectedPrefix))
for whereClauses in expectedClauses {
var success = false
for whereClause in whereClauses where resultQuery.contains(whereClause) {
success = true
}
XCTAssertTrue(success)
}
XCTAssertTrue(resultQuery.contains(expectedOperator))
}
XCTAssertNotNil(array, "Find Failed: No array of models returned")
if let array = array {
XCTAssertEqual(array.count, 1, "Find Failed: \(String(describing: array.count)) is not equal to 1")
let user = array[0]
XCTAssertEqual(user.name, "Joe")
XCTAssertEqual(user.age, 38)
}
expectation.fulfill()
}
})
}
struct Order: Model {
static var tableName = "Orders"
var item: Int
var deliveryAddress: String
}
/**
Testing that a Model can be decoded if it contains camel case property name.
*/
func testCamelCaseProperty() {
let connection: TestConnection = createConnection(.returnOneOrder)
Database.default = Database(single: connection)
performTest(asyncTasks: { expectation in
Order.findAll { array, error in
XCTAssertNil(error, "Find Failed: \(String(describing: error))")
XCTAssertNotNil(connection.query, "Find Failed: Query is nil")
if let query = connection.query {
let expectedQuery = "SELECT * FROM \"Orders\""
let resultQuery = connection.descriptionOf(query: query)
XCTAssertEqual(resultQuery, expectedQuery, "Find Failed: Invalid query")
}
XCTAssertNotNil(array, "Find Failed: No array of models returned")
if let array = array {
XCTAssertEqual(array.count, 1, "Find Failed: \(String(describing: array.count)) is not equal to 3")
}
expectation.fulfill()
}
})
}
}
| 43.885057 | 154 | 0.566265 |
f57d549ded43d2a31445041b58c6f80e24d80f0f | 2,697 | //
// HCCollectionViewFlowLayout.swift
// HCCardView
//
// Created by UltraPower on 2017/5/25.
// Copyright © 2017年 UltraPower. All rights reserved.
//
import UIKit
protocol UICollectionViewFlowLayoutDataSource:class {
func numberOfColumns(in collection:UICollectionView) -> Int
func heightOfItems(in collection:UICollectionView, at indexPath:IndexPath) -> CGFloat
}
/// 自定义流水布局
class HCCollectionViewFlowLayout: UICollectionViewFlowLayout {
weak var flowLayoutDataSource:UICollectionViewFlowLayoutDataSource?
fileprivate lazy var attributes:[UICollectionViewLayoutAttributes] = [UICollectionViewLayoutAttributes]()
fileprivate lazy var layoutMaxY: CGFloat = {
return self.sectionInset.top + self.sectionInset.bottom
}()
fileprivate lazy var columns: Int = {
return self.flowLayoutDataSource?.numberOfColumns(in: self.collectionView!) ?? 3
}()
fileprivate lazy var itemH: [CGFloat] = {
return Array(repeating: self.sectionInset.top + self.minimumLineSpacing, count: self.columns)
}()
}
// MARK: - 准备布局
extension HCCollectionViewFlowLayout {
override func prepare() {
super.prepare()
let numberItems:Int = collectionView!.numberOfItems(inSection: 0)
let itemWidth:CGFloat = (collectionView!.frame.width - sectionInset.left - sectionInset.right - minimumInteritemSpacing * CGFloat(columns + 1)) / CGFloat(columns)
for i in attributes.count ..< numberItems {
let indexP = IndexPath(item: i, section: 0)
let attribute = UICollectionViewLayoutAttributes(forCellWith: indexP)
let randomH = flowLayoutDataSource?.heightOfItems(in: collectionView!, at: indexP) ?? 100
let itemY = itemH.min()!
let itemYIndex = itemH.index(of: itemY)!
let itemX = sectionInset.left + minimumInteritemSpacing + (itemWidth + minimumInteritemSpacing) * CGFloat(itemYIndex)
attribute.frame = CGRect(x: itemX, y: itemY, width: itemWidth, height: randomH)
attributes.append(attribute)
itemH[itemYIndex] = attribute.frame.maxY + minimumLineSpacing
}
layoutMaxY = itemH.max()! + sectionInset.bottom
}
}
// MARK: - 返回布局
extension HCCollectionViewFlowLayout {
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
return attributes
}
}
// MARK: - 布局作用范围
extension HCCollectionViewFlowLayout{
override var collectionViewContentSize: CGSize {
return CGSize(width: 0, height: layoutMaxY)
}
}
| 35.025974 | 170 | 0.674824 |
e9a9ba3bf2f15d0f7002cfa85e0e18347d1a5f77 | 1,062 | //
// AppDelegate.swift
// MachOAnalysis
//
// Created by Family on 2020/9/19.
//
import Cocoa
import SwiftUI
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
var window: NSWindow!
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Create the SwiftUI view that provides the window contents.
let contentView = ContentView()
// Create the window and set the content view.
window = NSWindow(
contentRect: NSRect(x: 0, y: 0, width: 480, height: 300),
styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
backing: .buffered, defer: false)
window.isReleasedWhenClosed = false
window.center()
window.setFrameAutosaveName("Main Window")
window.contentView = NSHostingView(rootView: contentView)
window.makeKeyAndOrderFront(nil)
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
}
| 26.55 | 95 | 0.6742 |
bf6cb6580674123f1fd4acb4e93bf7406b741d2e | 1,438 | //
// BottleRocketUITests.swift
// BottleRocketUITests
//
// Created by Kapil Rathan on 3/9/22.
//
import XCTest
class BottleRocketUITests: 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, watchOS 7.0, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTApplicationLaunchMetric()]) {
XCUIApplication().launch()
}
}
}
}
| 33.44186 | 182 | 0.658554 |
e531bee1227ed9f0fd6bb14c1706b22e53f3cc0c | 1,291 | //
// UncurryTests.swift
//
//
// Created by Volodymyr Andriienko on 07.02.2022.
//
import XCTest
@testable import Swiftional
class UncurryTests: XCTestCase {
func test_uncurryingTwoArgumentsCurriedFunction_sameResults() {
let cf = curry(f2)
let arr = generateTestIntArray(length: 2)
let expected = f2(arr[0], arr[1])
XCTAssertEqual(expected, uncurry(cf)(arr[0], arr[1]))
}
func test_uncurryingThreeArgumentsCurriedFunction_sameResults() {
let cf = curry(f3)
let arr = generateTestIntArray(length: 3)
let expected = f3(arr[0], arr[1], arr[2])
XCTAssertEqual(expected, uncurry(cf)(arr[0], arr[1], arr[2]))
}
func test_uncurryingFourArgumentsCurriedFunction_sameResults() {
let cf = curry(f4)
let arr = generateTestIntArray(length: 4)
let expected = f4(arr[0], arr[1], arr[2], arr[3])
XCTAssertEqual(expected, uncurry(cf)(arr[0], arr[1], arr[2], arr[3]))
}
func test_uncurryingFiveArgumentsCurriedFunction_sameResults() {
let cf = curry(f5)
let arr = generateTestIntArray(length: 5)
let expected = f5(arr[0], arr[1], arr[2], arr[3], arr[4])
XCTAssertEqual(expected, uncurry(cf)(arr[0], arr[1], arr[2], arr[3], arr[4]))
}
}
| 31.487805 | 85 | 0.636716 |
e96e98b37fde2cc30ae736903d7e808277891011 | 2,737 | //
// Copyright (c) 2020 Related Code - http://relatedcode.com
//
// 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 RealmSwift
import CoreLocation
//-------------------------------------------------------------------------------------------------------------------------------------------------
class Message: SyncObject {
@objc dynamic var chatId = ""
@objc dynamic var userId = ""
@objc dynamic var userFullname = ""
@objc dynamic var userInitials = ""
@objc dynamic var userPictureAt: Int64 = 0
@objc dynamic var type = ""
@objc dynamic var text = ""
@objc dynamic var photoWidth: Int = 0
@objc dynamic var photoHeight: Int = 0
@objc dynamic var videoDuration: Int = 0
@objc dynamic var audioDuration: Int = 0
@objc dynamic var latitude: CLLocationDegrees = 0
@objc dynamic var longitude: CLLocationDegrees = 0
@objc dynamic var isMediaQueued = false
@objc dynamic var isMediaFailed = false
@objc dynamic var isDeleted = false
//---------------------------------------------------------------------------------------------------------------------------------------------
class func lastUpdatedAt() -> Int64 {
let realm = try! Realm()
let object = realm.objects(Message.self).sorted(byKeyPath: "updatedAt").last
return object?.updatedAt ?? 0
}
// MARK: -
//---------------------------------------------------------------------------------------------------------------------------------------------
func update(isMediaQueued value: Bool) {
if (isMediaQueued == value) { return }
let realm = try! Realm()
try! realm.safeWrite {
isMediaQueued = value
syncRequired = true
}
}
//---------------------------------------------------------------------------------------------------------------------------------------------
func update(isMediaFailed value: Bool) {
if (isMediaFailed == value) { return }
let realm = try! Realm()
try! realm.safeWrite {
isMediaFailed = value
syncRequired = true
}
}
//---------------------------------------------------------------------------------------------------------------------------------------------
func update(isDeleted value: Bool) {
if (isDeleted == value) { return }
let realm = try! Realm()
try! realm.safeWrite {
isDeleted = value
syncRequired = true
}
}
}
| 31.825581 | 147 | 0.517355 |
3a5680efeb176be8bbe6d35f7aa621c221363906 | 2,855 | //
// TestQRReader.swift
// Tests
//
// Created by Mederic Petit on 12/2/2018.
// Copyright © 2017-2018 Omise Go Pte. Ltd. All rights reserved.
//
@testable import OmiseGO
import XCTest
class TestQRReader: QRReader {
func mockValueFound(value: String) {
self.delegate?.onDecodedData(decodedData: value)
}
}
class TestQRVCDelegate: QRScannerViewControllerDelegate {
var asyncExpectation: XCTestExpectation?
var didCancel: Bool = false
var transactionRequest: TransactionRequest?
var error: OMGError?
init(asyncExpectation: XCTestExpectation? = nil) {
self.asyncExpectation = asyncExpectation
}
func scannerDidCancel(scanner _: QRScannerViewController) {
self.didCancel = true
self.asyncExpectation?.fulfill()
}
func scannerDidDecode(scanner _: QRScannerViewController, transactionRequest: TransactionRequest) {
self.transactionRequest = transactionRequest
self.asyncExpectation?.fulfill()
}
func scannerDidFailToDecode(scanner _: QRScannerViewController, withError error: OMGError) {
self.error = error
self.asyncExpectation?.fulfill()
}
func userDidChoosePermission(granted _: Bool) {}
}
import AVFoundation
class TestQRViewModel: QRScannerViewModelProtocol {
var didStartScanning: Bool = false
var didStopScanning: Bool = false
var didUpdateQRReaderPreviewLayer: Bool = false
var didCallLoadTransactionRequestWithFormattedId: Bool = false
var onLoadingStateChange: LoadingClosure?
var onGetTransactionRequest: OnGetTransactionRequestClosure?
var onUserPermissionChoice: ((Bool) -> Void)?
var onError: OnErrorClosure?
func startScanning(onStart _: (() -> Void)?) {
self.didStartScanning = true
}
func stopScanning(onStop _: (() -> Void)?) {
self.didStopScanning = true
}
func readerPreviewLayer() -> AVCaptureVideoPreviewLayer {
return AVCaptureVideoPreviewLayer()
}
func updateQRReaderPreviewLayer(withFrame _: CGRect) {
self.didUpdateQRReaderPreviewLayer = true
}
func isQRCodeAvailable() -> Bool {
return true // for testing purpose we ignore the availabilty of the video device
}
func loadTransactionRequest(withFormattedId _: String) {
self.didCallLoadTransactionRequestWithFormattedId = true
}
}
class TestQRVerifier: QRVerifier {
let success: Bool
init(success: Bool) {
self.success = success
}
func onData(data _: String, callback: @escaping (Response<TransactionRequest>) -> Void) {
if self.success {
callback(Response.success(data: StubGenerator.transactionRequest()))
} else {
callback(Response.fail(error: OMGError.api(apiError: .init(code: .other("test"), description: "test"))))
}
}
}
| 27.718447 | 116 | 0.697373 |
d5871fb6bafe9f7886e23e72820a148d90cbfc92 | 1,522 | //
// ViewController.swift
// ZImageCropper
//
// Created by ZAID PATHAN on 12/11/15.
// Copyright © 2015 Zaid Pathan. All rights reserved.
//
import UIKit
import Foundation
import CoreGraphics
import ZImageCropper
class ViewController: UIViewController {
@IBOutlet weak var imageView: ZImageCropperView!
var croppedImage: UIImage?
override func viewDidLoad() {
super.viewDidLoad()
self.title = "ZImageCropper"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//
//MARK:- IBAction methods
//
@IBAction func IBActionCropImage(_ sender: UIButton) {
croppedImage = imageView.cropImage()
}
@IBAction func IBActionAI(_ sender: Any) {
croppedImage = ZImageCropper.cropImage(ofImageView: imageView, withinPoints: [
CGPoint(x: 0, y: 0),
CGPoint(x: 100, y: 0),
CGPoint(x: 100, y: 100),
CGPoint(x: 0, y: 100)
])
}
@IBAction func IBActionCancelCrop(_ sender: UIButton) {
imageView.resetCrop()
croppedImage = nil
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destinationVC:NewImageViewController = segue.destination as! NewImageViewController
destinationVC.newImageFile = croppedImage
}
}
| 26.701754 | 95 | 0.574244 |
56d1ecac7565f15b853058a6b4c6555462f7ba37 | 8,599 | // Created by Cihat Gündüz on 24.01.19.
import Foundation
import SwiftSyntax
import HandySwift
class TranslateTransformer: SyntaxRewriter {
let transformer: Transformer
let typeName: String
let translateMethodName: String
let caseToLangCode: [String: String]
var translateEntries: [CodeFileHandler.TranslateEntry] = []
init(transformer: Transformer, typeName: String, translateMethodName: String, caseToLangCode: [String: String]) {
self.transformer = transformer
self.typeName = typeName
self.translateMethodName = translateMethodName
self.caseToLangCode = caseToLangCode
}
override func visit(_ functionCallExpression: FunctionCallExprSyntax) -> ExprSyntax {
guard
let memberAccessExpression = functionCallExpression.child(at: 0) as? MemberAccessExprSyntax,
let memberAccessExpressionBase = memberAccessExpression.base,
memberAccessExpressionBase.description.stripped() == typeName,
memberAccessExpression.name.text == translateMethodName,
let functionCallArgumentList = functionCallExpression.child(at: 2) as? FunctionCallArgumentListSyntax,
let keyFunctionCallArgument = functionCallArgumentList.child(at: 0) as? FunctionCallArgumentSyntax,
keyFunctionCallArgument.label?.text == "key",
let keyStringLiteralExpression = keyFunctionCallArgument.expression as? StringLiteralExprSyntax,
let translationsFunctionCallArgument = functionCallArgumentList.child(at: 1) as? FunctionCallArgumentSyntax,
translationsFunctionCallArgument.label?.text == "translations",
let translationsDictionaryExpression = translationsFunctionCallArgument.child(at: 2) as? DictionaryExprSyntax
else {
return super.visit(functionCallExpression)
}
let leadingWhitespace: String = String(memberAccessExpressionBase.description.prefix(memberAccessExpressionBase.description.count - typeName.count))
let key = keyStringLiteralExpression.text
guard !key.isEmpty else {
print("Found empty key in translate entry '\(functionCallExpression)'.", level: .warning)
return functionCallExpression
}
var translations: [CodeFileHandler.TranslationElement] = []
if let translationsDictionaryElementList = translationsDictionaryExpression.child(at: 1) as? DictionaryElementListSyntax {
for dictionaryElement in translationsDictionaryElementList {
guard let langCase = dictionaryElement.keyExpression.description.components(separatedBy: ".").last?.stripped() else {
print("LangeCase was not an enum case literal: '\(dictionaryElement.keyExpression)'")
return functionCallExpression
}
guard let translationLiteralExpression = dictionaryElement.valueExpression as? StringLiteralExprSyntax else {
print("Translation for langCase '\(langCase)' was not a String literal: '\(dictionaryElement.valueExpression)'")
return functionCallExpression
}
let translation = translationLiteralExpression.text
guard !translation.isEmpty else {
print("Translation for langCase '\(langCase)' was empty.", level: .warning)
continue
}
guard let langCode = caseToLangCode[langCase] else {
print("Could not find a langCode for langCase '\(langCase)' when transforming translation.", level: .warning)
continue
}
translations.append((langCode: langCode, translation: translation))
}
}
var comment: String?
if
let commentFunctionCallArgument = functionCallArgumentList.child(at: 2) as? FunctionCallArgumentSyntax,
commentFunctionCallArgument.label?.text == "comment",
let commentStringLiteralExpression = commentFunctionCallArgument.expression as? StringLiteralExprSyntax
{
comment = commentStringLiteralExpression.text
}
let translateEntry: CodeFileHandler.TranslateEntry = (key: key, translations: translations, comment: comment)
translateEntries.append(translateEntry)
print("Found translate entry with key '\(key)' and \(translations.count) translations.", level: .info)
let transformedExpression: ExprSyntax = {
switch transformer {
case .foundation:
return buildFoundationExpression(key: key, comment: comment, leadingWhitespace: leadingWhitespace)
case .swiftgenStructured:
return buildSwiftgenStructuredExpression(key: key, leadingWhitespace: leadingWhitespace)
}
}()
print("Transformed '\(functionCallExpression)' to '\(transformedExpression)'.", level: .info)
return transformedExpression
}
private func buildSwiftgenStructuredExpression(key: String, leadingWhitespace: String) -> ExprSyntax {
// e.g. the key could be something like 'ONBOARDING.FIRST_PAGE.HEADER_TITLE' or 'onboarding.first-page.header-title'
let keywordSeparators: CharacterSet = CharacterSet(charactersIn: ".")
let casingSeparators: CharacterSet = CharacterSet(charactersIn: "-_")
// e.g. ["ONBOARDING", "FIRST_PAGE", "HEADER_TITLE"]
let keywords: [String] = key.components(separatedBy: keywordSeparators)
// e.g. [["ONBOARDING"], ["FIRST", "PAGE"], ["HEADER", "TITLE"]]
let keywordsCasingComponents: [[String]] = keywords.map { $0.components(separatedBy: casingSeparators) }
// e.g. ["Onboarding", "FirstPage", "HeaderTitle"]
var swiftgenKeyComponents: [String] = keywordsCasingComponents.map { $0.map { $0.capitalized }.joined() }
// e.g. ["Onboarding", "FirstPage", "headerTitle"]
let lastKeyComponentIndex: Int = swiftgenKeyComponents.endIndex - 1
swiftgenKeyComponents[lastKeyComponentIndex] = swiftgenKeyComponents[lastKeyComponentIndex].firstCharacterLowercased()
// e.g. ["L10n", "Onboarding", "FirstPage", "headerTitle"]
swiftgenKeyComponents.insert("\(leadingWhitespace)L10n", at: 0)
return buildMemberAccessExpression(components: swiftgenKeyComponents)
}
private func buildMemberAccessExpression(components: [String]) -> ExprSyntax {
let identifierToken = SyntaxFactory.makeIdentifier(components.last!)
guard components.count > 1 else { return SyntaxFactory.makeIdentifierExpr(identifier: identifierToken, declNameArguments: nil) }
return SyntaxFactory.makeMemberAccessExpr(
base: buildMemberAccessExpression(components: Array(components.dropLast())),
dot: SyntaxFactory.makePeriodToken(),
name: identifierToken,
declNameArguments: nil
)
}
private func buildFoundationExpression(key: String, comment: String?, leadingWhitespace: String) -> ExprSyntax {
let keyArgument = SyntaxFactory.makeFunctionCallArgument(
label: nil,
colon: nil,
expression: SyntaxFactory.makeStringLiteralExpr(key),
trailingComma: SyntaxFactory.makeCommaToken(leadingTrivia: .zero, trailingTrivia: .spaces(1))
)
let commentArgument = SyntaxFactory.makeFunctionCallArgument(
label: SyntaxFactory.makeIdentifier("comment"),
colon: SyntaxFactory.makeColonToken(leadingTrivia: .zero, trailingTrivia: .spaces(1)),
expression: SyntaxFactory.makeStringLiteralExpr(comment ?? ""),
trailingComma: nil
)
return SyntaxFactory.makeFunctionCallExpr(
calledExpression: SyntaxFactory.makeIdentifierExpr(identifier: SyntaxFactory.makeIdentifier("\(leadingWhitespace)NSLocalizedString"), declNameArguments: nil),
leftParen: SyntaxFactory.makeLeftParenToken(),
argumentList: SyntaxFactory.makeFunctionCallArgumentList([keyArgument, commentArgument]),
rightParen: SyntaxFactory.makeRightParenToken(),
trailingClosure: nil
)
}
}
extension StringLiteralExprSyntax {
var text: String {
let description: String = self.description
guard description.count > 2 else { return "" }
let textRange = description.index(description.startIndex, offsetBy: 1) ..< description.index(description.endIndex, offsetBy: -1)
return String(description[textRange])
}
}
| 48.581921 | 170 | 0.68601 |
67d753b02f9bcaf84ea11c356321ca636d2709bd | 873 | //
// FlowType.swift
// iOS
//
// Created by Mariusz Sut on 12/03/2022.
//
import Core
import SwiftUI
enum FlowType {
case export
case `import`
case none
init(value: Double) {
if value > 0 {
self = .import
} else if value < 0 {
self = .export
} else {
self = .none
}
}
var tintColor: Color {
typealias Colors = Assets.Colors.iOS
switch self {
case .export: return Colors.exportTintColor
case .import: return Colors.importTintColor
case .none: return Colors.noneTintColor
}
}
var literal: String {
typealias Literals = Assets.Strings.Core.Common
switch self {
case .export: return Literals.exported
case .import: return Literals.imported
case .none: return ""
}
}
}
| 19.840909 | 55 | 0.553265 |
e2a935185b206dd47ffecaf10ff1ecc79228318a | 921 | /// A poor man's ordered set.
internal struct OrderedSet<T: Hashable> {
fileprivate var values: [T] = []
init<S: Sequence>(_ sequence: S) where S.Element == T {
for e in sequence where !values.contains(e) {
values.append(e)
}
}
@discardableResult
mutating func remove(_ member: T) -> T? {
if let index = values.index(of: member) {
return values.remove(at: index)
} else {
return nil
}
}
}
extension OrderedSet: Equatable {
static func == (_ lhs: OrderedSet, rhs: OrderedSet) -> Bool {
return lhs.values == rhs.values
}
}
extension OrderedSet: Collection {
subscript(position: Int) -> T {
return values[position]
}
var count: Int {
return values.count
}
var isEmpty: Bool {
return values.isEmpty
}
var startIndex: Int {
return values.startIndex
}
var endIndex: Int {
return values.endIndex
}
func index(after i: Int) -> Int {
return values.index(after: i)
}
}
| 17.711538 | 62 | 0.660152 |
627a7bf5810c6987fbcd6698a63080f5cd8c6bdc | 4,663 | //
// HomeViewController.swift
// CombineTest1
//
// Created by Quoc Doan M. on 2/28/21.
//
import UIKit
import Combine
final class HomeViewController: UIViewController {
@IBOutlet private weak var collectionView: UICollectionView!
var viewModel: HomeViewModel = HomeViewModel()
private var cancelables = Set<AnyCancellable>()
override func viewDidLoad() {
super.viewDidLoad()
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(UINib(nibName: Define.cellIdentifier, bundle: nil), forCellWithReuseIdentifier: Define.cellIdentifier)
NotificationCenter.default.addObserver(self, selector: #selector(updateUI(_:)), name: Notification.Name.init(rawValue: "NotificationCenter"), object: nil)
}
@objc private func updateUI(_ notification: NSNotification) {
guard let userInfo = notification.userInfo,
let indexPath = viewModel.indexPath else { return }
let name: String = userInfo["name"] as? String ?? ""
let address: String = userInfo["address"] as? String ?? ""
viewModel.users[indexPath.row] = User(name: name, address: address)
let indexPaths: [IndexPath] = [IndexPath(row: indexPath.row, section: indexPath.section)]
collectionView.reloadItems(at: indexPaths)
}
}
// MARK: - UICollectionViewDataSource
extension HomeViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return viewModel.numberOfItems(in: section)
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell: CustomCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: Define.cellIdentifier, for: indexPath) as? CustomCollectionViewCell else {
return UICollectionViewCell()
}
cell.viewModel = viewModel.cellForItem(at: indexPath)
cell.delegate = self
return cell
}
}
// MARK: - UICollectionViewDelegateFlowLayout
extension HomeViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width: CGFloat = (UIScreen.main.bounds.width - 20) / 2
let height: CGFloat = (UIScreen.main.bounds.height - 8) / 2
return CGSize(width: width, height: height)
}
}
// MARK: - CustomCollectionViewCellDelegate
extension HomeViewController: CustomCollectionViewCellDelegate {
func cell(_ cell: CustomCollectionViewCell, needsPerform action: CustomCollectionViewCell.Action) {
guard let indexPath = collectionView.indexPath(for: cell) else { return }
viewModel.indexPath = indexPath
let vc = EditViewController()
// Combine: Received value from publisher
vc.publisher
.sink(receiveValue: { user in
self.viewModel.users[indexPath.row] = user
let indexPaths: [IndexPath] = [IndexPath(row: indexPath.row, section: indexPath.section)]
self.collectionView.reloadItems(at: indexPaths)
})
.store(in: &cancelables)
vc.viewModel = viewModel.getEditViewModel()
// Closure
vc.closure = { [weak self] (value) in
guard let indexPath = self?.viewModel.indexPath else { return }
self?.viewModel.users[indexPath.row] = value
let indexPaths: [IndexPath] = [IndexPath(row: indexPath.row, section: indexPath.section)]
self?.collectionView.reloadItems(at: indexPaths)
}
// Delegate
vc.delegate = self
// Present edit view controller
vc.modalPresentationStyle = .overFullScreen
present(vc, animated: true, completion: nil)
}
}
// MARK: - EditViewControllerDelegate
extension HomeViewController: EditViewControllerDelegate {
func vc(_ vc: EditViewController, needsPerform action: EditViewController.Action) {
switch action {
case .didSelectedDoneButton(let user):
guard let indexPath = viewModel.indexPath else { return }
viewModel.users[indexPath.row] = user
let indexPaths: [IndexPath] = [IndexPath(row: indexPath.row, section: indexPath.section)]
collectionView.reloadItems(at: indexPaths)
}
}
}
// Define
extension HomeViewController {
private struct Define {
static let cellIdentifier: String = "CustomCollectionViewCell"
}
}
| 40.903509 | 181 | 0.68947 |
892ad6a44b37656b8a361a4e4f9805c07922fa1f | 477 | //
// User.swift
// FoodFood
//
// Created by Rajashree Naik on 4/25/19.
// Copyright © 2019 Rajashree Naik. All rights reserved.
//
import Foundation
import UIKit
struct User {
var name : String
var userimg : String
var email : String
init( name : String, email : String, userimg : String) {
self.name = name
self.email = email
self.userimg = userimg
// "https://cdn.onlinewebfonts.com/svg/img_332705.png"
}
}
| 19.875 | 61 | 0.612159 |
d98625edd434040780bde1e69253497ed2295ea2 | 3,776 | import Foundation
import RxSwift
class EditTimeslotViewModel
{
var timelineItemObservable: Observable<TimelineItem?>
{
return timelineItemVariable.asObservable()
}
let timelineItemsObservable: Observable<[TimelineItem]>
let categoryProvider : CategoryProvider
let timeService: TimeService
var isShowingSubSlot : Bool
private let timeSlotService: TimeSlotService
private let metricsService: MetricsService
private let smartGuessService: SmartGuessService
private let startDate: Date
private let timelineItemVariable = Variable<TimelineItem?>(nil)
private let disposeBag = DisposeBag()
// MARK: - Init
init(startDate: Date,
isShowingSubSlot: Bool = false,
timelineItemsObservable: Observable<[TimelineItem]>,
timeSlotService: TimeSlotService,
metricsService: MetricsService,
smartGuessService: SmartGuessService,
timeService: TimeService)
{
self.startDate = startDate
self.timelineItemsObservable = timelineItemsObservable
self.isShowingSubSlot = isShowingSubSlot
self.timeSlotService = timeSlotService
self.metricsService = metricsService
self.smartGuessService = smartGuessService
self.timeService = timeService
self.categoryProvider = DefaultCategoryProvider(timeSlotService: timeSlotService)
timelineItemsObservable
.map(filterSelectedElement(for: startDate))
.bindTo(timelineItemVariable)
.addDisposableTo(disposeBag)
}
// MARK: - Public methods
func updateTimelineItem(_ timelineItem: TimelineItem, withCategory category: Category)
{
updateTimeSlot(timelineItem.timeSlots, withCategory: category)
}
// MARK: - Private methods
private func updateTimeSlot(_ timeSlots: [TimeSlot], withCategory category: Category)
{
timeSlotService.update(timeSlots: timeSlots, withCategory: category)
timeSlots.forEach { (timeSlot) in
metricsService.log(event: .timeSlotEditing(date: timeService.now, fromCategory: timeSlot.category, toCategory: category, duration: timeSlot.duration))
}
}
private func filterSelectedElement(for date: Date) -> ([TimelineItem]) -> TimelineItem?
{
return { timelineItems in
if self.isShowingSubSlot
{
var timeSlotToShow : TimeSlot!
var isRunning = false
for timeline in timelineItems
{
if let timeSlot = timeline.timeSlots.filter({ $0.startTime == date }).first
{
timeSlotToShow = timeSlot
let index = timeline.timeSlots.index(where: { $0.startTime == date })
if index == timeline.timeSlots.endIndex - 1
{
isRunning = timeline.isRunning
}
break
}
}
guard timeSlotToShow != nil else { return nil }
return TimelineItem(withTimeSlots: [timeSlotToShow],
category: timeSlotToShow.category,
duration: timeSlotToShow.duration != nil ?
timeSlotToShow.duration! :
self.timeService.now.timeIntervalSince(timeSlotToShow.startTime),
isRunning: isRunning)
}
else
{
return timelineItems.filter({ $0.startTime == date }).first
}
}
}
}
| 37.386139 | 162 | 0.591102 |
03dd388b03db4d27149f55b6809a65c9e6e33904 | 1,276 | ///
/// MIT License
///
/// Copyright (c) 2020 Mac Gallagher
///
/// 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
extension CGPoint {
init(_ vector: CGVector) {
self = CGPoint(x: vector.dx, y: vector.dy)
}
}
| 38.666667 | 82 | 0.734326 |
4a789a6a237ed941dd4524d0b9dc825da6a30f33 | 884 | //
// NSDataAsset.swift
// TracksLibrary
//
// Created by Ian Grossberg on 9/27/18.
// Copyright © 2018 Adorkable. All rights reserved.
//
#if os(iOS)
import UIKit
#elseif os(macOS)
import Cocoa
#endif
extension NSDataAsset {
public enum Errors: Error, CustomStringConvertible {
case assetNotFound(name: String, bundle: Bundle)
public var description: String {
switch self {
case .assetNotFound(let name, let bundle):
return "Asset '\(name)' not found in bundle '\(bundle)'"
}
}
}
}
extension NSDataAsset {
public static func create(name: String, bundle: Bundle) throws -> NSDataAsset {
guard let result = NSDataAsset(name: name, bundle: bundle) else {
throw NSDataAsset.Errors.assetNotFound(name: name, bundle: bundle)
}
return result
}
}
| 24.555556 | 83 | 0.621041 |
14243bebf3df95d669233e5d7881c405cbe7d344 | 1,802 | // The MIT License (MIT)
// Copyright © 2022 Ivan Vorobei ([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.
import UIKit
extension SFSymbol {
public static var turkishlirasign: Turkishlirasign { .init(name: "turkishlirasign") }
open class Turkishlirasign: SFSymbol {
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
open var circle: SFSymbol { ext(.start.circle) }
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
open var circleFill: SFSymbol { ext(.start.circle.fill) }
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
open var square: SFSymbol { ext(.start.square) }
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
open var squareFill: SFSymbol { ext(.start.square.fill) }
}
} | 43.95122 | 86 | 0.736959 |
90bf3cd07b481b5f654f64e91999a1f17ce1b520 | 21,294 | //
// SocketIOClient.swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 11/23/14.
//
// 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 Dispatch
import Foundation
/// Represents a socket.io-client.
///
/// Clients are created through a `SocketManager`, which owns the `SocketEngineSpec` that controls the connection to the server.
///
/// For example:
///
/// ```swift
/// // Create a socket for the /swift namespace
/// let socket = manager.socket(forNamespace: "/swift")
///
/// // Add some handlers and connect
/// ```
///
/// **NOTE**: The client is not thread/queue safe, all interaction with the socket should be done on the `manager.handleQueue`
///
@objc(SocketIOClient)
@objcMembers
open class SocketIOClient : NSObject, SocketIOClientSpec {
// MARK: Properties
/// The namespace that this socket is currently connected to.
///
/// **Must** start with a `/`.
public let nsp: String
/// A handler that will be called on any event.
public private(set) var anyHandler: ((SocketAnyEvent) -> ())?
/// The array of handlers for this socket.
public private(set) var handlers = [SocketEventHandler]()
/// The manager for this socket.
public private(set) weak var manager: SocketManagerSpec?
/// A view into this socket where emits do not check for binary data.
///
/// Usage:
///
/// ```swift
/// socket.rawEmitView.emit("myEvent", myObject)
/// ```
///
/// **NOTE**: It is not safe to hold on to this view beyond the life of the socket.
public private(set) lazy var rawEmitView = SocketRawView(socket: self)
/// The status of this client.
public private(set) var status = SocketIOStatus.notConnected {
didSet {
handleClientEvent(.statusChange, data: [status, status.rawValue])
}
}
/// The id of this socket.io connect. This is different from the sid of the engine.io connection.
public private(set) var sid: String?
let ackHandlers = SocketAckManager()
var connectPayload: [String: Any]?
private(set) var currentAck = -1
private lazy var logType = "SocketIOClient{\(nsp)}"
// MARK: Initializers
/// Type safe way to create a new SocketIOClient. `opts` can be omitted.
///
/// - parameter manager: The manager for this socket.
/// - parameter nsp: The namespace of the socket.
public init(manager: SocketManagerSpec, nsp: String) {
self.manager = manager
self.nsp = nsp
super.init()
}
/// :nodoc:
deinit {
DefaultSocketLogger.Logger.log("Client is being released", type: logType)
}
// MARK: Methods
/// Connect to the server. The same as calling `connect(timeoutAfter:withHandler:)` with a timeout of 0.
///
/// Only call after adding your event listeners, unless you know what you're doing.
///
/// - parameter withPayload: An optional payload sent on connect
open func connect(withPayload payload: [String: Any]? = nil) {
connect(withPayload: payload, timeoutAfter: 0, withHandler: nil)
}
/// Connect to the server. If we aren't connected after `timeoutAfter` seconds, then `withHandler` is called.
///
/// Only call after adding your event listeners, unless you know what you're doing.
///
/// - parameter withPayload: An optional payload sent on connect
/// - parameter timeoutAfter: The number of seconds after which if we are not connected we assume the connection
/// has failed. Pass 0 to never timeout.
/// - parameter handler: The handler to call when the client fails to connect.
open func connect(withPayload payload: [String: Any]? = nil, timeoutAfter: Double, withHandler handler: (() -> ())?) {
assert(timeoutAfter >= 0, "Invalid timeout: \(timeoutAfter)")
guard let manager = self.manager, status != .connected else {
DefaultSocketLogger.Logger.log("Tried connecting on an already connected socket", type: logType)
return
}
status = .connecting
joinNamespace(withPayload: payload)
switch manager.version {
case .three:
break
case .two where manager.status == .connected && nsp == "/":
// We might not get a connect event for the default nsp, fire immediately
didConnect(toNamespace: nsp, payload: nil)
return
case _:
break
}
guard timeoutAfter != 0 else { return }
manager.handleQueue.asyncAfter(deadline: DispatchTime.now() + timeoutAfter) {[weak self] in
guard let this = self, this.status == .connecting || this.status == .notConnected else { return }
this.status = .disconnected
this.leaveNamespace()
handler?()
}
}
func createOnAck(_ items: [Any], binary: Bool = true) -> OnAckCallback {
currentAck += 1
return OnAckCallback(ackNumber: currentAck, items: items, socket: self)
}
/// Called when the client connects to a namespace. If the client was created with a namespace upfront,
/// then this is only called when the client connects to that namespace.
///
/// - parameter toNamespace: The namespace that was connected to.
open func didConnect(toNamespace namespace: String, payload: [String: Any]?) {
guard status != .connected else { return }
DefaultSocketLogger.Logger.log("Socket connected", type: logType)
status = .connected
sid = payload?["sid"] as? String
handleClientEvent(.connect, data: payload == nil ? [namespace] : [namespace, payload!])
}
/// Called when the client has disconnected from socket.io.
///
/// - parameter reason: The reason for the disconnection.
open func didDisconnect(reason: String) {
guard status != .disconnected else { return }
DefaultSocketLogger.Logger.log("Disconnected: \(reason)", type: logType)
status = .disconnected
sid = ""
handleClientEvent(.disconnect, data: [reason])
}
/// Disconnects the socket.
///
/// This will cause the socket to leave the namespace it is associated to, as well as remove itself from the
/// `manager`.
open func disconnect() {
DefaultSocketLogger.Logger.log("Closing socket", type: logType)
leaveNamespace()
}
/// Send an event to the server, with optional data items and optional write completion handler.
///
/// If an error occurs trying to transform `items` into their socket representation, a `SocketClientEvent.error`
/// will be emitted. The structure of the error data is `[eventName, items, theError]`
///
/// - parameter event: The event to send.
/// - parameter items: The items to send with this event. May be left out.
/// - parameter completion: Callback called on transport write completion.
open func emit(_ event: String, _ items: SocketData..., completion: (() -> ())? = nil) {
emit(event, with: items, completion: completion)
}
/// Send an event to the server, with optional data items and optional write completion handler.
///
/// If an error occurs trying to transform `items` into their socket representation, a `SocketClientEvent.error`
/// will be emitted. The structure of the error data is `[eventName, items, theError]`
///
/// - parameter event: The event to send.
/// - parameter items: The items to send with this event. May be left out.
/// - parameter completion: Callback called on transport write completion.
open func emit(_ event: String, with items: [SocketData], completion: (() -> ())?) {
do {
emit([event] + (try items.map({ try $0.socketRepresentation() })), completion: completion)
} catch {
DefaultSocketLogger.Logger.error("Error creating socketRepresentation for emit: \(event), \(items)",
type: logType)
handleClientEvent(.error, data: [event, items, error])
}
}
/// Sends a message to the server, requesting an ack.
///
/// **NOTE**: It is up to the server send an ack back, just calling this method does not mean the server will ack.
/// Check that your server's api will ack the event being sent.
///
/// If an error occurs trying to transform `items` into their socket representation, a `SocketClientEvent.error`
/// will be emitted. The structure of the error data is `[eventName, items, theError]`
///
/// Example:
///
/// ```swift
/// socket.emitWithAck("myEvent", 1).timingOut(after: 1) {data in
/// ...
/// }
/// ```
///
/// - parameter event: The event to send.
/// - parameter items: The items to send with this event. May be left out.
/// - returns: An `OnAckCallback`. You must call the `timingOut(after:)` method before the event will be sent.
open func emitWithAck(_ event: String, _ items: SocketData...) -> OnAckCallback {
emitWithAck(event, with: items)
}
/// Sends a message to the server, requesting an ack.
///
/// **NOTE**: It is up to the server send an ack back, just calling this method does not mean the server will ack.
/// Check that your server's api will ack the event being sent.
///
/// If an error occurs trying to transform `items` into their socket representation, a `SocketClientEvent.error`
/// will be emitted. The structure of the error data is `[eventName, items, theError]`
///
/// Example:
///
/// ```swift
/// socket.emitWithAck("myEvent", 1).timingOut(after: 1) {data in
/// ...
/// }
/// ```
///
/// - parameter event: The event to send.
/// - parameter items: The items to send with this event. May be left out.
/// - returns: An `OnAckCallback`. You must call the `timingOut(after:)` method before the event will be sent.
open func emitWithAck(_ event: String, with items: [SocketData]) -> OnAckCallback {
do {
return createOnAck([event] + (try items.map({ try $0.socketRepresentation() })))
} catch {
DefaultSocketLogger.Logger.error("Error creating socketRepresentation for emit: \(event), \(items)",
type: logType)
handleClientEvent(.error, data: [event, items, error])
return OnAckCallback(ackNumber: -1, items: [], socket: self)
}
}
func emit(_ data: [Any],
ack: Int? = nil,
binary: Bool = true,
isAck: Bool = false,
completion: (() -> ())? = nil
) {
// wrap the completion handler so it always runs async via handlerQueue
let wrappedCompletion: (() -> ())? = (completion == nil) ? nil : {[weak self] in
guard let this = self else { return }
this.manager?.handleQueue.async {
completion!()
}
}
guard status == .connected else {
wrappedCompletion?()
handleClientEvent(.error, data: ["Tried emitting when not connected"])
return
}
let packet = SocketPacket.packetFromEmit(data, id: ack ?? -1, nsp: nsp, ack: isAck, checkForBinary: binary)
let str = packet.packetString
DefaultSocketLogger.Logger.log("Emitting: \(str), Ack: \(isAck)", type: logType)
manager?.engine?.send(str, withData: packet.binary, completion: wrappedCompletion)
}
/// Call when you wish to tell the server that you've received the event for `ack`.
///
/// **You shouldn't need to call this directly.** Instead use an `SocketAckEmitter` that comes in an event callback.
///
/// - parameter ack: The ack number.
/// - parameter with: The data for this ack.
open func emitAck(_ ack: Int, with items: [Any]) {
emit(items, ack: ack, binary: true, isAck: true)
}
/// Called when socket.io has acked one of our emits. Causes the corresponding ack callback to be called.
///
/// - parameter ack: The number for this ack.
/// - parameter data: The data sent back with this ack.
open func handleAck(_ ack: Int, data: [Any]) {
guard status == .connected else { return }
DefaultSocketLogger.Logger.log("Handling ack: \(ack) with data: \(data)", type: logType)
ackHandlers.executeAck(ack, with: data)
}
/// Called on socket.io specific events.
///
/// - parameter event: The `SocketClientEvent`.
/// - parameter data: The data for this event.
open func handleClientEvent(_ event: SocketClientEvent, data: [Any]) {
handleEvent(event.rawValue, data: data, isInternalMessage: true)
}
/// Called when we get an event from socket.io.
///
/// - parameter event: The name of the event.
/// - parameter data: The data that was sent with this event.
/// - parameter isInternalMessage: Whether this event was sent internally. If `true` it is always sent to handlers.
/// - parameter ack: If > 0 then this event expects to get an ack back from the client.
open func handleEvent(_ event: String, data: [Any], isInternalMessage: Bool, withAck ack: Int = -1) {
guard status == .connected || isInternalMessage else { return }
DefaultSocketLogger.Logger.log("Handling event: \(event) with data: \(data)", type: logType)
anyHandler?(SocketAnyEvent(event: event, items: data))
for handler in handlers where handler.event == event {
handler.executeCallback(with: data, withAck: ack, withSocket: self)
}
}
/// Causes a client to handle a socket.io packet. The namespace for the packet must match the namespace of the
/// socket.
///
/// - parameter packet: The packet to handle.
open func handlePacket(_ packet: SocketPacket) {
guard packet.nsp == nsp else { return }
switch packet.type {
case .event, .binaryEvent:
handleEvent(packet.event, data: packet.args, isInternalMessage: false, withAck: packet.id)
case .ack, .binaryAck:
handleAck(packet.id, data: packet.data)
case .connect:
didConnect(toNamespace: nsp, payload: packet.data.isEmpty ? nil : packet.data[0] as? [String: Any])
case .disconnect:
didDisconnect(reason: "Got Disconnect")
case .error:
handleEvent("error", data: packet.data, isInternalMessage: true, withAck: packet.id)
}
}
/// Call when you wish to leave a namespace and disconnect this socket.
open func leaveNamespace() {
manager?.disconnectSocket(self)
}
/// Joins `nsp`. You shouldn't need to call this directly, instead call `connect`.
///
/// - parameter withPayload: An optional payload sent on connect
open func joinNamespace(withPayload payload: [String: Any]? = nil) {
DefaultSocketLogger.Logger.log("Joining namespace \(nsp)", type: logType)
connectPayload = payload
manager?.connectSocket(self, withPayload: connectPayload)
}
/// Removes handler(s) for a client event.
///
/// If you wish to remove a client event handler, call the `off(id:)` with the UUID received from its `on` call.
///
/// - parameter clientEvent: The event to remove handlers for.
open func off(clientEvent event: SocketClientEvent) {
off(event.rawValue)
}
/// Removes handler(s) based on an event name.
///
/// If you wish to remove a specific event, call the `off(id:)` with the UUID received from its `on` call.
///
/// - parameter event: The event to remove handlers for.
open func off(_ event: String) {
DefaultSocketLogger.Logger.log("Removing handler for event: \(event)", type: logType)
handlers = handlers.filter({ $0.event != event })
}
/// Removes a handler with the specified UUID gotten from an `on` or `once`
///
/// If you want to remove all events for an event, call the off `off(_:)` method with the event name.
///
/// - parameter id: The UUID of the handler you wish to remove.
open func off(id: UUID) {
DefaultSocketLogger.Logger.log("Removing handler with id: \(id)", type: logType)
handlers = handlers.filter({ $0.id != id })
}
/// Adds a handler for an event.
///
/// - parameter event: The event name for this handler.
/// - parameter callback: The callback that will execute when this event is received.
/// - returns: A unique id for the handler that can be used to remove it.
@discardableResult
open func on(_ event: String, callback: @escaping NormalCallback) -> UUID {
DefaultSocketLogger.Logger.log("Adding handler for event: \(event)", type: logType)
let handler = SocketEventHandler(event: event, id: UUID(), callback: callback)
handlers.append(handler)
return handler.id
}
/// Adds a handler for a client event.
///
/// Example:
///
/// ```swift
/// socket.on(clientEvent: .connect) {data, ack in
/// ...
/// }
/// ```
///
/// - parameter event: The event for this handler.
/// - parameter callback: The callback that will execute when this event is received.
/// - returns: A unique id for the handler that can be used to remove it.
@discardableResult
open func on(clientEvent event: SocketClientEvent, callback: @escaping NormalCallback) -> UUID {
return on(event.rawValue, callback: callback)
}
/// Adds a single-use handler for a client event.
///
/// - parameter clientEvent: The event for this handler.
/// - parameter callback: The callback that will execute when this event is received.
/// - returns: A unique id for the handler that can be used to remove it.
@discardableResult
open func once(clientEvent event: SocketClientEvent, callback: @escaping NormalCallback) -> UUID {
return once(event.rawValue, callback: callback)
}
/// Adds a single-use handler for an event.
///
/// - parameter event: The event name for this handler.
/// - parameter callback: The callback that will execute when this event is received.
/// - returns: A unique id for the handler that can be used to remove it.
@discardableResult
open func once(_ event: String, callback: @escaping NormalCallback) -> UUID {
DefaultSocketLogger.Logger.log("Adding once handler for event: \(event)", type: logType)
let id = UUID()
let handler = SocketEventHandler(event: event, id: id) {[weak self] data, ack in
guard let this = self else { return }
this.off(id: id)
callback(data, ack)
}
handlers.append(handler)
return handler.id
}
/// Adds a handler that will be called on every event.
///
/// - parameter handler: The callback that will execute whenever an event is received.
open func onAny(_ handler: @escaping (SocketAnyEvent) -> ()) {
anyHandler = handler
}
/// Tries to reconnect to the server.
@available(*, unavailable, message: "Call the manager's reconnect method")
open func reconnect() { }
/// Removes all handlers.
///
/// Can be used after disconnecting to break any potential remaining retain cycles.
open func removeAllHandlers() {
handlers.removeAll(keepingCapacity: false)
}
/// Puts the socket back into the connecting state.
/// Called when the manager detects a broken connection, or when a manual reconnect is triggered.
///
/// - parameter reason: The reason this socket is reconnecting.
open func setReconnecting(reason: String) {
status = .connecting
handleClientEvent(.reconnect, data: [reason])
}
// Test properties
var testHandlers: [SocketEventHandler] {
return handlers
}
func setTestable() {
status = .connected
}
func setTestStatus(_ status: SocketIOStatus) {
self.status = status
}
func emitTest(event: String, _ data: Any...) {
emit([event] + data)
}
}
| 38.646098 | 128 | 0.635672 |
1dc4022a71cb2d77209a3db060c9303b1c52b9ad | 1,170 | //
// DetailViewController.swift
// Demo App
//
// Created by Iñigo Flores Rabasa on 13/03/20.
// Copyright © 2020 Iñigo Flores Rabasa. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController, StoryboardInstanciable {
@IBOutlet private weak var appImageView: UIImageView!
@IBOutlet private weak var appTitleLabel: UILabel!
@IBOutlet private weak var appDescriptionLabel: UILabel!
@IBOutlet private weak var appLinkLabel: UILabel!
@IBOutlet private weak var copyRigthsLabel: UILabel!
private var viewModel: DetailViewModel!
override func viewDidLoad() {
super.viewDidLoad()
configure()
}
func configure(with viewModel: DetailViewModel) {
self.viewModel = viewModel
}
func configure() {
viewModel.appTitle.bind(to: appTitleLabel.reactive.text)
viewModel.appDescription.bind(to: appDescriptionLabel.reactive.text)
viewModel.appLink.bind(to: appLinkLabel.reactive.text)
viewModel.appCopyRigths.bind(to: copyRigthsLabel.reactive.text)
viewModel.appImage.bind(to: appImageView.reactive.image)
}
}
| 29.25 | 76 | 0.702564 |
382ac691fd40900fde04596a103008fd28ddf84c | 8,874 | //
// TabPageViewController.swift
// TabPageViewController
//
// Created by EndouMari on 2016/02/24.
// Copyright © 2016年 EndouMari. All rights reserved.
//
import UIKit
public class TabPageViewController: UIPageViewController {
public var isInfinity: Bool = false // 是否无穷多
public var option: TabPageOption = TabPageOption()
public var tabItems: [(viewController: UIViewController, title: String)] = [] { // 放入元组的数组
didSet {
tabItemsCount = tabItems.count
}
}
var currentIndex: Int? { // 当前索引
guard let viewController = viewControllers?.first else { // 判断是否存在控制器,,不存在则返回索引值为空
return nil
}
return tabItems.map{ $0.viewController }.indexOf(viewController) // 返回当前控制器的索引
}
private var beforeIndex: Int = 0 // 上一个索引
private var tabItemsCount = 0 // items数量(即控制器数量)
private var defaultContentOffsetX: CGFloat { // 默认的 x 轴方向的偏移值
return self.view.bounds.width
}
private var shouldScrollCurrentBar: Bool = true // 是否需要滚动当前的 bar
lazy private var tabView: TabView = self.configuredTabView()
public static func create() -> TabPageViewController { // 创建 TabPageViewController
let sb = UIStoryboard(name: "TabPageViewController", bundle: NSBundle(forClass: TabPageViewController.self))
return sb.instantiateInitialViewController() as! TabPageViewController
}
override public func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "hjkhsjkhkfjshjk"
setupPageViewController()
setupScrollView()
updateNavigationBar()
}
override public func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if tabView.superview == nil {
tabView = configuredTabView()
}
if let currentIndex = currentIndex where isInfinity {
tabView.updateCurrentIndex(currentIndex, shouldScroll: true)
}
}
override public func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
updateNavigationBar()
}
override public func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
navigationController?.navigationBar.shadowImage = nil
navigationController?.navigationBar.setBackgroundImage(nil, forBarMetrics: .Default)
}
}
// MARK: - Public Interface
public extension TabPageViewController {
public func displayControllerWithIndex(index: Int, direction: UIPageViewControllerNavigationDirection, animated: Bool) {
beforeIndex = index
shouldScrollCurrentBar = false
let nextViewControllers: [UIViewController] = [tabItems[index].viewController]
let completion: (Bool -> Void) = { [weak self] _ in
self?.shouldScrollCurrentBar = true
self?.beforeIndex = index
}
setViewControllers(
nextViewControllers,
direction: direction,
animated: animated,
completion: completion)
}
}
// MARK: - View
extension TabPageViewController {
// 创建 TabPageViewController
private func setupPageViewController() {
dataSource = self
delegate = self
automaticallyAdjustsScrollViewInsets = false
setViewControllers([tabItems[beforeIndex].viewController],
direction: .Forward,
animated: false,
completion: nil)
}
private func setupScrollView() {
// Disable PageViewController's ScrollView bounce
let scrollView = view.subviews.flatMap { $0 as? UIScrollView }.first
scrollView?.scrollsToTop = false
scrollView?.delegate = self
scrollView?.backgroundColor = option.pageBackgoundColor
}
/**
Update NavigationBar
*/
private func updateNavigationBar() {
if let navigationBar = navigationController?.navigationBar {
navigationBar.shadowImage = UIImage()
navigationBar.setBackgroundImage(option.tabBackgroundImage, forBarMetrics: .Default)
}
}
private func configuredTabView() -> TabView {
let tabView = TabView(isInfinity: isInfinity, option: option)
tabView.translatesAutoresizingMaskIntoConstraints = false
let height = NSLayoutConstraint(item: tabView,
attribute: .Height,
relatedBy: .Equal,
toItem: nil,
attribute: .Height,
multiplier: 1.0,
constant: option.tabHeight)
tabView.addConstraint(height)
view.addSubview(tabView)
let top = NSLayoutConstraint(item: tabView,
attribute: .Top,
relatedBy: .Equal,
toItem: topLayoutGuide,
attribute: .Bottom,
multiplier:1.0,
constant: 0.0)
let left = NSLayoutConstraint(item: tabView,
attribute: .Leading,
relatedBy: .Equal,
toItem: view,
attribute: .Leading,
multiplier: 1.0,
constant: 0.0)
let right = NSLayoutConstraint(item: view,
attribute: .Trailing,
relatedBy: .Equal,
toItem: tabView,
attribute: .Trailing,
multiplier: 1.0,
constant: 0.0)
view.addConstraints([top, left, right])
tabView.pageTabItems = tabItems.map({ $0.title})
tabView.updateCurrentIndex(beforeIndex, shouldScroll: true)
tabView.pageItemPressedBlock = { [weak self] (index: Int, direction: UIPageViewControllerNavigationDirection) in
self?.displayControllerWithIndex(index, direction: direction, animated: true)
}
return tabView
}
}
// MARK: - UIPageViewControllerDataSource
extension TabPageViewController: UIPageViewControllerDataSource {
private func nextViewController(viewController: UIViewController, isAfter: Bool) -> UIViewController? {
guard var index = tabItems.map({$0.viewController}).indexOf(viewController) else {
return nil
}
if isAfter {
index += 1
} else {
index -= 1
}
if isInfinity {
if index < 0 {
index = tabItems.count - 1
} else if index == tabItems.count {
index = 0
}
}
if index >= 0 && index < tabItems.count {
return tabItems[index].viewController
}
return nil
}
public func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
return nextViewController(viewController, isAfter: true)
}
public func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
return nextViewController(viewController, isAfter: false)
}
}
// MARK: - UIPageViewControllerDelegate
extension TabPageViewController: UIPageViewControllerDelegate {
public func pageViewController(pageViewController: UIPageViewController, willTransitionToViewControllers pendingViewControllers: [UIViewController]) {
shouldScrollCurrentBar = true
tabView.scrollToHorizontalCenter()
// Order to prevent the the hit repeatedly during animation
tabView.updateCollectionViewUserInteractionEnabled(false)
}
public func pageViewController(pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
if let currentIndex = currentIndex where currentIndex < tabItemsCount {
tabView.updateCurrentIndex(currentIndex, shouldScroll: false)
beforeIndex = currentIndex
}
tabView.updateCollectionViewUserInteractionEnabled(true)
}
}
// MARK: - UIScrollViewDelegate
extension TabPageViewController: UIScrollViewDelegate {
public func scrollViewDidScroll(scrollView: UIScrollView) {
if scrollView.contentOffset.x == defaultContentOffsetX || !shouldScrollCurrentBar {
return
}
// (0..<tabItemsCount)
var index: Int
if scrollView.contentOffset.x > defaultContentOffsetX {
index = beforeIndex + 1
} else {
index = beforeIndex - 1
}
if index == tabItemsCount {
index = 0
} else if index < 0 {
index = tabItemsCount - 1
}
let scrollOffsetX = scrollView.contentOffset.x - view.frame.width
tabView.scrollCurrentBarView(index, contentOffsetX: scrollOffsetX)
}
public func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
tabView.updateCurrentIndex(beforeIndex, shouldScroll: true)
}
}
| 31.580071 | 195 | 0.654496 |
75e7720d3ceffa5ff1aa6cdbc37eef828bff7843 | 2,129 | //
// User.swift
// TwitterDemo
//
// Created by Andrew Rivera on 2/27/16.
// Copyright © 2016 Andrew Rivera. All rights reserved.
//
import UIKit
class User: NSObject {
var name: NSString?
var screenname: NSString?
var profileUrl: NSURL?
var tagline: NSString?
var username: String?
var dictionary: NSDictionary?
init(dictionary: NSDictionary) {
self.dictionary = dictionary
name = dictionary["name"] as? String
screenname = dictionary["screen_name"] as? String
let profileUrlString = dictionary["profile_image_url_https"] as? String
if let profileUrlString = profileUrlString{
profileUrl = NSURL(string: profileUrlString)
}
tagline = dictionary["description"] as? String
}
static let userDidLogoutNotification = "UserDidLogout"
static var _currentUser: User?
class var currentUser: User?{
get{
if _currentUser == nil{
let defaults = NSUserDefaults.standardUserDefaults()
let userData = defaults.objectForKey("currentUserData") as? NSData
if let userData = userData{
let dictionary = try! NSJSONSerialization.JSONObjectWithData(userData, options: []) as! NSDictionary
_currentUser = User(dictionary: dictionary)
}
else{
_currentUser = nil
}
}
return _currentUser
}
set(user) {
_currentUser = user
let defaults = NSUserDefaults.standardUserDefaults()
if let user = user{
let data = try!
NSJSONSerialization.dataWithJSONObject(user.dictionary!, options: [])
defaults.setObject(data, forKey: "currentUserData")
}else{
defaults.setObject(nil, forKey: "currentUserData")
}
defaults.synchronize()
}
}
}
| 25.047059 | 116 | 0.545796 |
fcf1d6baf203ee3c0129510f2346b619e8d6ee86 | 3,692 | //
// HashtagViewController.swift
// SimpleTwitterClient
//
// Created by Alexander Baquiax on 4/8/16.
// Copyright © 2016 Alexander Baquiax. All rights reserved.
//
import Foundation
import UIKit
class HashtagViewController : LastTweetsViewController , UISearchBarDelegate {
@IBOutlet weak var searchBar: UISearchBar!
var textToSearch = ""
var timer : NSTimer?
override func viewDidLoad() {
super.viewDidLoad()
self.searchBar.delegate = self
}
override func loadData() {
self.loader.hidden = false
self.loader.startAnimating()
if let _ = NSUserDefaults.standardUserDefaults().objectForKey("user") {
if (self.textToSearch.isEqual("")) {
self.data = NSArray()
self.tableView.reloadData()
self.loader.stopAnimating()
return
}
TwitterClient.getTwitterClient().client.get("https://api.twitter.com/1.1/search/tweets.json", parameters: ["count" : 100, "q" : self.textToSearch], headers: nil, success: { data, response in
do {
let result = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as! NSDictionary
self.data = result.objectForKey("statuses") as! NSArray
} catch {
self.data = NSArray()
}
self.tableView.reloadData()
self.tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), atScrollPosition: UITableViewScrollPosition.Top, animated: true)
self.loader.stopAnimating()
}, failure: { (error) -> Void in
})
} else {
self.loader.stopAnimating()
}
}
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
self.textToSearch = searchText
print(searchText)
if (self.timer != nil) {
self.timer?.invalidate()
}
self.timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "loadData", userInfo: nil, repeats: false)
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("TwitterPostHashtag", forIndexPath: indexPath) as! TwitterPostCell
let item = self.data.objectAtIndex(indexPath.row) as! NSDictionary
if let user = item.objectForKey("user") as? NSDictionary {
if let name = user.objectForKey("name") as? String {
cell.name.text = name
}
if let screenName = user.objectForKey("screen_name") as? String {
cell.username.text = screenName
}
if let imageStringURL = user.objectForKey("profile_image_url") as? String {
let imageURL = NSURL(string: imageStringURL)
let request = NSURLRequest(URL: imageURL!)
cell.dataTask = self.urlSession.dataTaskWithRequest(request) { (data, response, error) -> Void in
NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
if error == nil && data != nil {
let image = UIImage(data: data!)
cell.profileImage.image = image
}
})
}
cell.dataTask?.resume()
}
}
if let text = item.objectForKey("text") as? String {
cell.tweet.text = text
}
return cell
}
} | 40.571429 | 202 | 0.576381 |
ccee48ee0b286c60a3131fbd6546a3c1c3a19d2a | 10,127 | // DO NOT EDIT.
//
// Generated by the Swift generator plugin for the protocol buffer compiler.
// Source: unittest_swift_enum.proto
//
// For information on using the generated types, please see the documenation:
// https://github.com/apple/swift-protobuf/
// Protocol Buffers - Google's data interchange format
// Copyright 2015 Apple, Inc. All Rights Reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * 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.
// * Neither the name of Google Inc. 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
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import Foundation
import SwiftProtobuf
// If the compiler emits an error on this type, it is because this file
// was generated by a version of the `protoc` Swift plug-in that is
// incompatible with the version of SwiftProtobuf to which you are linking.
// Please ensure that your are building against the same version of the API
// that was used to generate this file.
fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck {
struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {}
typealias Version = _2
}
struct ProtobufUnittest_SwiftEnumTest {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var values1: [ProtobufUnittest_SwiftEnumTest.EnumTest1] = []
var values2: [ProtobufUnittest_SwiftEnumTest.EnumTest2] = []
var values3: [ProtobufUnittest_SwiftEnumTest.EnumTestNoStem] = []
var values4: [ProtobufUnittest_SwiftEnumTest.EnumTestReservedWord] = []
var unknownFields = SwiftProtobuf.UnknownStorage()
enum EnumTest1: SwiftProtobuf.Enum {
typealias RawValue = Int
case firstValue // = 1
case secondValue // = 2
init() {
self = .firstValue
}
init?(rawValue: Int) {
switch rawValue {
case 1: self = .firstValue
case 2: self = .secondValue
default: return nil
}
}
var rawValue: Int {
switch self {
case .firstValue: return 1
case .secondValue: return 2
}
}
}
enum EnumTest2: SwiftProtobuf.Enum {
typealias RawValue = Int
case firstValue // = 1
case secondValue // = 2
init() {
self = .firstValue
}
init?(rawValue: Int) {
switch rawValue {
case 1: self = .firstValue
case 2: self = .secondValue
default: return nil
}
}
var rawValue: Int {
switch self {
case .firstValue: return 1
case .secondValue: return 2
}
}
}
enum EnumTestNoStem: SwiftProtobuf.Enum {
typealias RawValue = Int
case enumTestNoStem1 // = 1
case enumTestNoStem2 // = 2
init() {
self = .enumTestNoStem1
}
init?(rawValue: Int) {
switch rawValue {
case 1: self = .enumTestNoStem1
case 2: self = .enumTestNoStem2
default: return nil
}
}
var rawValue: Int {
switch self {
case .enumTestNoStem1: return 1
case .enumTestNoStem2: return 2
}
}
}
enum EnumTestReservedWord: SwiftProtobuf.Enum {
typealias RawValue = Int
case `var` // = 1
case notReserved // = 2
init() {
self = .var
}
init?(rawValue: Int) {
switch rawValue {
case 1: self = .var
case 2: self = .notReserved
default: return nil
}
}
var rawValue: Int {
switch self {
case .var: return 1
case .notReserved: return 2
}
}
}
init() {}
}
struct ProtobufUnittest_SwiftEnumWithAliasTest {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var values: [ProtobufUnittest_SwiftEnumWithAliasTest.EnumWithAlias] = []
var unknownFields = SwiftProtobuf.UnknownStorage()
enum EnumWithAlias: SwiftProtobuf.Enum {
typealias RawValue = Int
case foo1 // = 1
static let foo2 = foo1
case bar1 // = 2
static let bar2 = bar1
init() {
self = .foo1
}
init?(rawValue: Int) {
switch rawValue {
case 1: self = .foo1
case 2: self = .bar1
default: return nil
}
}
var rawValue: Int {
switch self {
case .foo1: return 1
case .bar1: return 2
}
}
}
init() {}
}
// MARK: - Code below here is support for the SwiftProtobuf runtime.
fileprivate let _protobuf_package = "protobuf_unittest"
extension ProtobufUnittest_SwiftEnumTest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".SwiftEnumTest"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "values1"),
2: .same(proto: "values2"),
3: .same(proto: "values3"),
4: .same(proto: "values4"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeRepeatedEnumField(value: &self.values1)
case 2: try decoder.decodeRepeatedEnumField(value: &self.values2)
case 3: try decoder.decodeRepeatedEnumField(value: &self.values3)
case 4: try decoder.decodeRepeatedEnumField(value: &self.values4)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.values1.isEmpty {
try visitor.visitRepeatedEnumField(value: self.values1, fieldNumber: 1)
}
if !self.values2.isEmpty {
try visitor.visitRepeatedEnumField(value: self.values2, fieldNumber: 2)
}
if !self.values3.isEmpty {
try visitor.visitRepeatedEnumField(value: self.values3, fieldNumber: 3)
}
if !self.values4.isEmpty {
try visitor.visitRepeatedEnumField(value: self.values4, fieldNumber: 4)
}
try unknownFields.traverse(visitor: &visitor)
}
func _protobuf_generated_isEqualTo(other: ProtobufUnittest_SwiftEnumTest) -> Bool {
if self.values1 != other.values1 {return false}
if self.values2 != other.values2 {return false}
if self.values3 != other.values3 {return false}
if self.values4 != other.values4 {return false}
if unknownFields != other.unknownFields {return false}
return true
}
}
extension ProtobufUnittest_SwiftEnumTest.EnumTest1: SwiftProtobuf._ProtoNameProviding {
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "ENUM_TEST_1_FIRST_VALUE"),
2: .same(proto: "ENUM_TEST_1_SECOND_VALUE"),
]
}
extension ProtobufUnittest_SwiftEnumTest.EnumTest2: SwiftProtobuf._ProtoNameProviding {
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "ENUM_TEST_2_FIRST_VALUE"),
2: .same(proto: "SECOND_VALUE"),
]
}
extension ProtobufUnittest_SwiftEnumTest.EnumTestNoStem: SwiftProtobuf._ProtoNameProviding {
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "ENUM_TEST_NO_STEM_1"),
2: .same(proto: "ENUM_TEST_NO_STEM_2"),
]
}
extension ProtobufUnittest_SwiftEnumTest.EnumTestReservedWord: SwiftProtobuf._ProtoNameProviding {
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "ENUM_TEST_RESERVED_WORD_VAR"),
2: .same(proto: "ENUM_TEST_RESERVED_WORD_NOT_RESERVED"),
]
}
extension ProtobufUnittest_SwiftEnumWithAliasTest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".SwiftEnumWithAliasTest"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "values"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeRepeatedEnumField(value: &self.values)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.values.isEmpty {
try visitor.visitPackedEnumField(value: self.values, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
func _protobuf_generated_isEqualTo(other: ProtobufUnittest_SwiftEnumWithAliasTest) -> Bool {
if self.values != other.values {return false}
if unknownFields != other.unknownFields {return false}
return true
}
}
extension ProtobufUnittest_SwiftEnumWithAliasTest.EnumWithAlias: SwiftProtobuf._ProtoNameProviding {
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .aliased(proto: "FOO1", aliases: ["FOO2"]),
2: .aliased(proto: "BAR1", aliases: ["BAR2"]),
]
}
| 30.875 | 151 | 0.705046 |
6a1c76eaa151a85625ad3aeec31c641ecf52cdc1 | 17,807 | //
// ZLPhotoManager.swift
// ZLPhotoBrowser
//
// Created by long on 2020/8/11.
//
// Copyright (c) 2020 Long Zhang <[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.
import UIKit
import Photos
public class ZLPhotoManager: NSObject {
/// 保存图片到相册
@objc public class func saveImageToAlbum(image: UIImage, completion: ( (Bool, PHAsset?) -> Void )? ) {
let status = PHPhotoLibrary.authorizationStatus()
if status == .denied || status == .restricted {
completion?(false, nil)
return
}
var placeholderAsset: PHObjectPlaceholder? = nil
PHPhotoLibrary.shared().performChanges({
let newAssetRequest = PHAssetChangeRequest.creationRequestForAsset(from: image)
placeholderAsset = newAssetRequest.placeholderForCreatedAsset
}) { (suc, error) in
DispatchQueue.main.async {
if suc {
let asset = self.getAsset(from: placeholderAsset?.localIdentifier)
completion?(suc, asset)
} else {
completion?(false, nil)
}
}
}
}
/// 保存视频到相册
@objc public class func saveVideoToAblum(url: URL, completion: ( (Bool, PHAsset?) -> Void )? ) {
let status = PHPhotoLibrary.authorizationStatus()
if status == .denied || status == .restricted {
completion?(false, nil)
return
}
var placeholderAsset: PHObjectPlaceholder? = nil
PHPhotoLibrary.shared().performChanges({
let newAssetRequest = PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: url)
placeholderAsset = newAssetRequest?.placeholderForCreatedAsset
}) { (suc, error) in
DispatchQueue.main.async {
if suc {
let asset = self.getAsset(from: placeholderAsset?.localIdentifier)
completion?(suc, asset)
} else {
completion?(false, nil)
}
}
}
}
private class func getAsset(from localIdentifier: String?) -> PHAsset? {
guard let id = localIdentifier else {
return nil
}
let result = PHAsset.fetchAssets(withLocalIdentifiers: [id], options: nil)
if result.count > 0{
return result[0]
}
return nil
}
/// 从相册中获取照片
class func fetchPhoto(in result: PHFetchResult<PHAsset>, ascending: Bool, allowSelectImage: Bool, allowSelectVideo: Bool, limitCount: Int = .max) -> [ZLPhotoModel] {
var models: [ZLPhotoModel] = []
let option: NSEnumerationOptions = ascending ? .init(rawValue: 0) : .reverse
var count = 1
result.enumerateObjects(options: option) { (asset, index, stop) in
let m = ZLPhotoModel(asset: asset)
if m.type == .image, !allowSelectImage {
return
}
if m.type == .video, !allowSelectVideo {
return
}
if count == limitCount {
stop.pointee = true
}
models.append(m)
count += 1
}
return models
}
/// 获取相册列表
class func getPhotoAlbumList(ascending: Bool, allowSelectImage: Bool, allowSelectVideo: Bool, completion: ( ([ZLAlbumListModel]) -> Void )) {
let option = PHFetchOptions()
if !allowSelectImage {
option.predicate = NSPredicate(format: "mediaType == %ld", PHAssetMediaType.video.rawValue)
}
if !allowSelectVideo {
option.predicate = NSPredicate(format: "mediaType == %ld", PHAssetMediaType.image.rawValue)
}
let smartAlbums = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .albumRegular, options: nil) as! PHFetchResult<PHCollection>
let streamAlbums = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .albumMyPhotoStream, options: nil) as! PHFetchResult<PHCollection>
let userAlbums = PHCollectionList.fetchTopLevelUserCollections(with: nil)
let syncedAlbums = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .albumSyncedAlbum, options: nil) as! PHFetchResult<PHCollection>
let sharedAlbums = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .albumCloudShared, options: nil) as! PHFetchResult<PHCollection>
let arr = [smartAlbums, streamAlbums, userAlbums, syncedAlbums, sharedAlbums]
var albumList: [ZLAlbumListModel] = []
arr.forEach { (album) in
album.enumerateObjects { (collection, _, _) in
guard let collection = collection as? PHAssetCollection else { return }
if collection.assetCollectionSubtype == .smartAlbumAllHidden {
return
}
if #available(iOS 11.0, *), collection.assetCollectionSubtype.rawValue > PHAssetCollectionSubtype.smartAlbumLongExposures.rawValue {
return
}
let result = PHAsset.fetchAssets(in: collection, options: option)
if result.count == 0 {
return
}
let title = self.getCollectionTitle(collection)
if collection.assetCollectionSubtype == .smartAlbumUserLibrary {
// 所有照片
let m = ZLAlbumListModel(title: title, result: result, collection: collection, option: option, isCameraRoll: true)
albumList.insert(m, at: 0)
} else {
let m = ZLAlbumListModel(title: title, result: result, collection: collection, option: option, isCameraRoll: false)
albumList.append(m)
}
}
}
completion(albumList)
}
/// 获取相机胶卷album
class func getCameraRollAlbum(allowSelectImage: Bool, allowSelectVideo: Bool, completion: @escaping ( (ZLAlbumListModel) -> Void )) {
let option = PHFetchOptions()
if !allowSelectImage {
option.predicate = NSPredicate(format: "mediaType == %ld", PHAssetMediaType.video.rawValue)
}
if !allowSelectVideo {
option.predicate = NSPredicate(format: "mediaType == %ld", PHAssetMediaType.image.rawValue)
}
let smartAlbums = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .albumRegular, options: nil)
smartAlbums.enumerateObjects { (collection, _, stop) in
if collection.assetCollectionSubtype == .smartAlbumUserLibrary {
let result = PHAsset.fetchAssets(in: collection, options: option)
let albumModel = ZLAlbumListModel(title: self.getCollectionTitle(collection), result: result, collection: collection, option: option, isCameraRoll: true)
completion(albumModel)
stop.pointee = true
}
}
}
/// 转换相册title
private class func getCollectionTitle(_ collection: PHAssetCollection) -> String {
if collection.assetCollectionType == .album {
// 用户创建的相册
var title: String? = nil
if ZLCustomLanguageDeploy.language == .system {
title = collection.localizedTitle
} else {
switch collection.assetCollectionSubtype {
case .albumMyPhotoStream:
title = localLanguageTextValue(.myPhotoStream)
default:
title = collection.localizedTitle
}
}
return title ?? localLanguageTextValue(.noTitleAlbumListPlaceholder)
}
var title: String? = nil
if ZLCustomLanguageDeploy.language == .system {
title = collection.localizedTitle
} else {
switch collection.assetCollectionSubtype {
case .smartAlbumUserLibrary:
title = localLanguageTextValue(.cameraRoll)
case .smartAlbumPanoramas:
title = localLanguageTextValue(.panoramas)
case .smartAlbumVideos:
title = localLanguageTextValue(.videos)
case .smartAlbumFavorites:
title = localLanguageTextValue(.favorites)
case .smartAlbumTimelapses:
title = localLanguageTextValue(.timelapses)
case .smartAlbumRecentlyAdded:
title = localLanguageTextValue(.recentlyAdded)
case .smartAlbumBursts:
title = localLanguageTextValue(.bursts)
case .smartAlbumSlomoVideos:
title = localLanguageTextValue(.slomoVideos)
case .smartAlbumSelfPortraits:
title = localLanguageTextValue(.selfPortraits)
case .smartAlbumScreenshots:
title = localLanguageTextValue(.screenshots)
case .smartAlbumDepthEffect:
title = localLanguageTextValue(.depthEffect)
case .smartAlbumLivePhotos:
title = localLanguageTextValue(.livePhotos)
default:
title = collection.localizedTitle
}
if #available(iOS 11.0, *) {
if collection.assetCollectionSubtype == PHAssetCollectionSubtype.smartAlbumAnimated {
title = localLanguageTextValue(.animated)
}
}
}
return title ?? localLanguageTextValue(.noTitleAlbumListPlaceholder)
}
@discardableResult
class func fetchImage(for asset: PHAsset, size: CGSize, progress: ( (CGFloat, Error?, UnsafeMutablePointer<ObjCBool>, [AnyHashable : Any]?) -> Void )? = nil, completion: @escaping ( (UIImage?, Bool) -> Void )) -> PHImageRequestID {
return self.fetchImage(for: asset, size: size, resizeMode: .fast, progress: progress, completion: completion)
}
@discardableResult
class func fetchOriginalImage(for asset: PHAsset, progress: ( (CGFloat, Error?, UnsafeMutablePointer<ObjCBool>, [AnyHashable : Any]?) -> Void )? = nil, completion: @escaping ( (UIImage?, Bool) -> Void)) -> PHImageRequestID {
return self.fetchImage(for: asset, size: PHImageManagerMaximumSize, resizeMode: .fast, progress: progress, completion: completion)
}
/// 获取asset data
@discardableResult
class func fetchOriginalImageData(for asset: PHAsset, progress: ( (CGFloat, Error?, UnsafeMutablePointer<ObjCBool>, [AnyHashable : Any]?) -> Void )? = nil, completion: @escaping ( (Data, [AnyHashable: Any]?, Bool) -> Void)) -> PHImageRequestID {
let option = PHImageRequestOptions()
if (asset.value(forKey: "filename") as? String)?.hasSuffix("GIF") == true {
option.version = .original
}
option.isNetworkAccessAllowed = true
option.resizeMode = .fast
option.deliveryMode = .highQualityFormat
option.progressHandler = { (pro, error, stop, info) in
DispatchQueue.main.async {
progress?(CGFloat(pro), error, stop, info)
}
}
return PHImageManager.default().requestImageData(for: asset, options: option) { (data, _, _, info) in
let cancel = info?[PHImageCancelledKey] as? Bool ?? false
let isDegraded = (info?[PHImageResultIsDegradedKey] as? Bool ?? false)
if !cancel, let data = data {
completion(data, info, isDegraded)
}
}
}
/// 获取asset对应图片
private class func fetchImage(for asset: PHAsset, size: CGSize, resizeMode: PHImageRequestOptionsResizeMode, progress: ( (CGFloat, Error?, UnsafeMutablePointer<ObjCBool>, [AnyHashable : Any]?) -> Void )? = nil, completion: @escaping ( (UIImage?, Bool) -> Void )) -> PHImageRequestID {
let option = PHImageRequestOptions()
/**
resizeMode:对请求的图像怎样缩放。有三种选择:None,默认加载方式;Fast,尽快地提供接近或稍微大于要求的尺寸;Exact,精准提供要求的尺寸。
deliveryMode:图像质量。有三种值:Opportunistic,在速度与质量中均衡;HighQualityFormat,不管花费多长时间,提供高质量图像;FastFormat,以最快速度提供好的质量。
这个属性只有在 synchronous 为 true 时有效。
*/
option.resizeMode = resizeMode
option.isNetworkAccessAllowed = true
option.progressHandler = { (pro, error, stop, info) in
DispatchQueue.main.async {
progress?(CGFloat(pro), error, stop, info)
}
}
return PHImageManager.default().requestImage(for: asset, targetSize: size, contentMode: .aspectFill, options: option) { (image, info) in
var downloadFinished = false
if let info = info {
downloadFinished = !(info[PHImageCancelledKey] as? Bool ?? false) && (info[PHImageErrorKey] == nil)
}
let isDegraded = (info?[PHImageResultIsDegradedKey] as? Bool ?? false)
if downloadFinished {
completion(image, isDegraded)
}
}
}
class func fetchLivePhoto(for asset: PHAsset, completion: @escaping ( (PHLivePhoto?, [AnyHashable: Any]?, Bool) -> Void )) -> PHImageRequestID {
let option = PHLivePhotoRequestOptions()
option.version = .current
option.deliveryMode = .opportunistic
option.isNetworkAccessAllowed = true
return PHImageManager.default().requestLivePhoto(for: asset, targetSize: PHImageManagerMaximumSize, contentMode: .aspectFit, options: option) { (livePhoto, info) in
let isDegraded = (info?[PHImageResultIsDegradedKey] as? Bool ?? false)
completion(livePhoto, info, isDegraded)
}
}
class func fetchVideo(for asset: PHAsset, progress: ( (CGFloat, Error?, UnsafeMutablePointer<ObjCBool>, [AnyHashable : Any]?) -> Void )? = nil, completion: @escaping ( (AVPlayerItem?, [AnyHashable: Any]?, Bool) -> Void )) -> PHImageRequestID {
let option = PHVideoRequestOptions()
option.isNetworkAccessAllowed = true
option.progressHandler = { (pro, error, stop, info) in
DispatchQueue.main.async {
progress?(CGFloat(pro), error, stop, info)
}
}
return PHImageManager.default().requestPlayerItem(forVideo: asset, options: option) { (item, info) in
// iOS11 系统这个回调没有在主线程
DispatchQueue.main.async {
let isDegraded = (info?[PHImageResultIsDegradedKey] as? Bool ?? false)
completion(item, info, isDegraded)
}
}
}
class func isFetchImageError(_ error: Error?) -> Bool {
guard let e = error as NSError? else {
return false
}
if e.domain == "CKErrorDomain" || e.domain == "CloudPhotoLibraryErrorDomain" {
return true
}
return false
}
@objc public class func fetchAVAsset(forVideo asset: PHAsset, completion: @escaping ( (AVAsset?, [AnyHashable: Any]?) -> Void )) -> PHImageRequestID {
let options = PHVideoRequestOptions()
options.version = .original
options.deliveryMode = .automatic
options.isNetworkAccessAllowed = true
return PHImageManager.default().requestAVAsset(forVideo: asset, options: options) { (avAsset, _, info) in
DispatchQueue.main.async {
completion(avAsset, info)
}
}
}
/// 获取 asset 本地路径
@objc public class func fetchAssetFilePath(asset: PHAsset, completion: @escaping (String?) -> Void ) {
asset.requestContentEditingInput(with: nil) { (input, info) in
var path = input?.fullSizeImageURL?.absoluteString
if path == nil, let dir = asset.value(forKey: "directory") as? String, let name = asset.value(forKey: "filename") as? String {
path = String(format: "file:///var/mobile/Media/%@/%@", dir, name)
}
completion(path)
}
}
}
/// 权限相关
extension ZLPhotoManager {
public class func havePhotoLibratyAuthority() -> Bool {
return PHPhotoLibrary.authorizationStatus() == .authorized
}
public class func haveCameraAuthority() -> Bool {
let status = AVCaptureDevice.authorizationStatus(for: .video)
if status == .restricted || status == .denied {
return false
}
return true
}
public class func haveMicrophoneAuthority() -> Bool {
let status = AVCaptureDevice.authorizationStatus(for: .audio)
if status == .restricted || status == .denied {
return false
}
return true
}
}
| 44.406484 | 288 | 0.609142 |
1cc490656d0590ff3b62e74e13659c6d04c8c6c2 | 526 | //
// RCPdfUrlEntity.swift
// Infra
//
// Created by 山田隼也 on 2020/02/10.
// Copyright © 2020 Shunya Yamada. All rights reserved.
//
import Foundation
public struct RCPdfUrlEntity: RemoteConfigType {
public let calendar: String
public let timeTable: String
private enum CodingKeys: String, CodingKey {
case calendar
case timeTable = "time_table"
}
public init(calendar: String, timeTable: String) {
self.calendar = calendar
self.timeTable = timeTable
}
}
| 21.04 | 56 | 0.657795 |
bf70f5b241164cff74c142ae60df3bd7cb9c1b63 | 2,153 | //
// AppDelegate.swift
// SwiftBoxiOSDemo
//
// Created by James Tang on 12/7/15.
// Copyright (c) 2015 Josh Abernathy. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 45.808511 | 285 | 0.754296 |
e8ca7b3d4d6468dc81cc739afa90dc7580c844c5 | 185 | //
// main.swift
// Demo
//
// Created by Stephan Zehrer on 09.06.14.
// Copyright (c) 2014 Stephan Zehrer. All rights reserved.
//
import Cocoa
NSApplicationMain(C_ARGC, C_ARGV)
| 15.416667 | 59 | 0.686486 |
503166e77445a4a7deb8f3b71dfe4be23641afa3 | 3,919 | ///// Copyright (c) 2020 Razeware LLC
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
/// distribute, sublicense, create a derivative work, and/or sell copies of the
/// Software in any work that is designed, intended, or marketed for pedagogical or
/// instructional purposes related to programming, coding, application development,
/// or information technology. Permission for such use, copying, modification,
/// merger, publication, distribution, sublicensing, creation of derivative works,
/// or sale is expressly withheld.
///
/// This project and source code may use libraries or frameworks that are
/// released under various Open-Source licenses. Use of those libraries and
/// frameworks are governed by their own individual licenses.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
import CoreData
import SwiftUI
extension Reminder {
@NSManaged var title: String
@NSManaged var isCompleted: Bool
@NSManaged var notes: String?
@NSManaged var dueDate: Date?
@NSManaged var priority: Int16
static func createWith(title: String,
notes: String?,
date: Date?,
priority: ReminderPriority,
using viewContext: NSManagedObjectContext) {
let reminder = Reminder(context: viewContext)
reminder.title = title
reminder.notes = notes
reminder.dueDate = date
reminder.priority = priority.rawValue
do {
try viewContext.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
static func basicFetchRequest() -> FetchRequest<Reminder> {
FetchRequest(entity: Reminder.entity(), sortDescriptors: [])
}
static func sortedFetchRequest() -> FetchRequest<Reminder> {
let dateSortDescriptor = NSSortDescriptor(key: "dueDate", ascending: false)
return FetchRequest(entity: Reminder.entity(), sortDescriptors: [dateSortDescriptor])
}
static func fetchRequestSortedByTitleAndPriority() -> FetchRequest<Reminder> {
let titleSortDescriptor = NSSortDescriptor(key: "title", ascending: true)
let prioritySortDescriptor = NSSortDescriptor(key: "priority", ascending: false)
return FetchRequest(entity: Reminder.entity(), sortDescriptors: [titleSortDescriptor, prioritySortDescriptor])
}
static func completedRemindersFetchRequest() -> FetchRequest<Reminder> {
let titleSortDescriptor = NSSortDescriptor(key: "title", ascending: true)
let prioritySortDescriptor = NSSortDescriptor(key: "priority", ascending: false)
let isCompletedPredicate = NSPredicate(format: "%K == %@", "isCompleted", NSNumber(value: false))
return FetchRequest(entity: Reminder.entity(), sortDescriptors: [titleSortDescriptor, prioritySortDescriptor], predicate: isCompletedPredicate)
}
}
| 44.534091 | 147 | 0.730033 |
1caaed9d2de12343dc18e0cdb8f182dabcc68329 | 1,210 | //
// Copyright © 2019 An Tran. All rights reserved.
//
import CommandRegistry
import SPMUtility
import ColorizeSwift
import Foundation
class VideosValidationCommand: Command {
// MARK: Properties
// Static
let command = "validate"
let overview = "Validate the list of videos"
// Private
let subparser: ArgumentParser
var subcommands: [Command] = []
private var path: PositionalArgument<String>
// MARK: Initialization
required init(parser: ArgumentParser) {
subparser = parser.add(subparser: command, overview: overview)
path = subparser.add(positional: "path", kind: String.self, usage: "Path to root content folder")
}
// MARK: APIs
func run(with arguments: ArgumentParser.Result) throws {
guard let rootContentPath = arguments.get(path) else {
print("[Error] Content path is missing".red())
return
}
let videosValidator = VideosValidator(rootContentPath: rootContentPath)
do {
try videosValidator.validateList()
print("[Success] Videos list is valid".lightCyan())
} catch {
print("[Error] \(error)".red())
}
}
}
| 24.2 | 105 | 0.63719 |
c1d366f390ecf94965f31160f23ca3c22f685137 | 2,181 | //
// AppDelegate.swift
// SDK_SWIFT_SAMPLE
//
// Created by Kadir Guzel on 12/12/16.
// Copyright © 2016 Kadir Guzel. All rights reserved.
//
import UIKit
@UIApplicationMain
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.
// 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.404255 | 285 | 0.755617 |
ef7613140c070184923c9ff63ac2b9afa3154527 | 9,552 | //
// UIImage.swift
// TLSafone
//
// Created by Alexey Globchastyy on 15/09/14.
// Copyright (c) 2014 Alexey Globchastyy. All rights reserved.
//
import UIKit
import Accelerate
public extension UIImage {
/**
Applies a lightening (blur) effect to the image
- returns: The lightened image, or nil if error.
*/
public func applyLightEffect() -> UIImage? {
return applyBlurWithRadius(30, tintColor: UIColor(white: 1.0, alpha: 0.3), saturationDeltaFactor: 1.8)
}
/**
Applies an extra lightening (blur) effect to the image
- returns: The extra lightened image, or nil if error.
*/
public func applyExtraLightEffect() -> UIImage? {
return applyBlurWithRadius(20, tintColor: UIColor(white: 0.97, alpha: 0.82), saturationDeltaFactor: 1.8)
}
/**
Applies a darkening (blur) effect to the image.
- returns: The darkened image, or nil if error.
*/
public func applyDarkEffect() -> UIImage? {
return applyBlurWithRadius(20, tintColor: UIColor(white: 0.11, alpha: 0.73), saturationDeltaFactor: 1.8)
}
/**
Tints the image with the given color.
- parameter tintColor: The tint color
- returns: The tinted image, or nil if error.
*/
public func applyTintEffectWithColor(_ tintColor: UIColor) -> UIImage? {
let effectColorAlpha: CGFloat = 0.6
var effectColor = tintColor
let componentCount = tintColor.cgColor.numberOfComponents
if componentCount == 2 {
var b: CGFloat = 0
if tintColor.getWhite(&b, alpha: nil) {
effectColor = UIColor(white: b, alpha: effectColorAlpha)
}
} else {
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
if tintColor.getRed(&red, green: &green, blue: &blue, alpha: nil) {
effectColor = UIColor(red: red, green: green, blue: blue, alpha: effectColorAlpha)
}
}
return applyBlurWithRadius(10, tintColor: effectColor, saturationDeltaFactor: -1.0, maskImage: nil)
}
/**
Core function to create a new image with the given blur.
- parameter blurRadius: The blur radius
- parameter tintColor: The color to tint the image; optional.
- parameter saturationDeltaFactor: The delta by which to change the image saturation
- parameter maskImage: An optional image mask.
- returns: The adjusted image, or nil if error.
*/
public func applyBlurWithRadius(_ blurRadius: CGFloat, tintColor: UIColor?, saturationDeltaFactor: CGFloat, maskImage: UIImage? = nil) -> UIImage? {
//Check pre-conditions.
if size.width < 1 || size.height < 1 {
print("*** error: invalid size: \(size.width) x \(size.height). Both dimensions must be >= 1: \(self)")
return nil
}
guard let cgImage = self.cgImage else {
print("*** error: image must be backed by a CGImage: \(self)")
return nil
}
if maskImage != nil && maskImage!.cgImage == nil {
print("*** error: maskImage must be backed by a CGImage: \(maskImage)")
return nil
}
let __FLT_EPSILON__ = CGFloat(FLT_EPSILON)
let screenScale = UIScreen.main.scale
let imageRect = CGRect(origin: CGPoint.zero, size: size)
var effectImage = self
let hasBlur = blurRadius > __FLT_EPSILON__
let hasSaturationChange = fabs(saturationDeltaFactor - 1.0) > __FLT_EPSILON__
if hasBlur || hasSaturationChange {
func createEffectBuffer(_ context: CGContext) -> vImage_Buffer {
let data = context.data
let width = context.width
let height = context.height
let rowBytes = context.bytesPerRow
return vImage_Buffer(data: data, height: UInt(height), width: UInt(width), rowBytes: rowBytes)
}
UIGraphicsBeginImageContextWithOptions(size, false, screenScale)
guard let effectInContext = UIGraphicsGetCurrentContext() else {
UIGraphicsEndImageContext()
return self
}
effectInContext.scaleBy(x: 1.0, y: -1.0)
effectInContext.translateBy(x: 0, y: -size.height)
effectInContext.draw(cgImage, in: imageRect)
var effectInBuffer = createEffectBuffer(effectInContext)
UIGraphicsBeginImageContextWithOptions(size, false, screenScale)
guard let effectOutContext = UIGraphicsGetCurrentContext() else {
UIGraphicsEndImageContext()
return self
}
var effectOutBuffer = createEffectBuffer(effectOutContext)
if hasBlur {
// A description of how to compute the box kernel width from the Gaussian
// radius (aka standard deviation) appears in the SVG spec:
// http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement
// For larger values of 's' (s >= 2.0), an approximation can be used: Three
// successive box-blurs build a piece-wise quadratic convolution kernel, which
// approximates the Gaussian kernel to within roughly 3%.
// let d = floor(s * 3*sqrt(2*pi)/4 + 0.5)
// ... if d is odd, use three box-blurs of size 'd', centered on the output pixel.
let inputRadius = blurRadius * screenScale
// var radius = UInt32(floor(inputRadius * 3.0 * CGFloat(sqrt(2 * M_PI)) / 4 + 0.5))
let inputradius = inputRadius * 3.0 * CGFloat(sqrt(2 * M_PI))
var radius = UInt32(floor((inputradius / 4) + 0.5))
if radius % 2 != 1 {
radius += 1 // force radius to be odd so that the three box-blur methodology works.
}
let imageEdgeExtendFlags = vImage_Flags(kvImageEdgeExtend)
vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags)
vImageBoxConvolve_ARGB8888(&effectOutBuffer, &effectInBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags)
vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags)
}
var effectImageBuffersAreSwapped = false
if hasSaturationChange {
let s: CGFloat = saturationDeltaFactor
let floatingPointSaturationMatrix: [CGFloat] = [
0.0722 + 0.9278 * s, 0.0722 - 0.0722 * s, 0.0722 - 0.0722 * s, 0,
0.7152 - 0.7152 * s, 0.7152 + 0.2848 * s, 0.7152 - 0.7152 * s, 0,
0.2126 - 0.2126 * s, 0.2126 - 0.2126 * s, 0.2126 + 0.7873 * s, 0,
0, 0, 0, 1
]
let divisor: CGFloat = 256
let matrixSize = floatingPointSaturationMatrix.count
var saturationMatrix = [Int16](repeating: 0, count: matrixSize)
for i in 0..<matrixSize {
saturationMatrix[i] = Int16(round(floatingPointSaturationMatrix[i] * divisor))
}
if hasBlur {
vImageMatrixMultiply_ARGB8888(&effectOutBuffer,
&effectInBuffer,
saturationMatrix,
Int32(divisor),
nil,
nil,
vImage_Flags(kvImageNoFlags))
effectImageBuffersAreSwapped = true
} else {
vImageMatrixMultiply_ARGB8888(&effectInBuffer,
&effectOutBuffer,
saturationMatrix,
Int32(divisor),
nil,
nil,
vImage_Flags(kvImageNoFlags))
}
}
if !effectImageBuffersAreSwapped {
effectImage = UIGraphicsGetImageFromCurrentImageContext()!
}
UIGraphicsEndImageContext()
if effectImageBuffersAreSwapped {
effectImage = UIGraphicsGetImageFromCurrentImageContext()!
}
UIGraphicsEndImageContext()
}
// Set up output context.
UIGraphicsBeginImageContextWithOptions(size, false, screenScale)
let outputContext = UIGraphicsGetCurrentContext()
outputContext?.scaleBy(x: 1.0, y: -1.0)
outputContext?.translateBy(x: 0, y: -size.height)
// Draw base image.
outputContext?.draw(cgImage, in: imageRect)
// Draw effect image.
if hasBlur {
outputContext?.saveGState()
if let image = maskImage {
outputContext?.clip(to: imageRect, mask: image.cgImage!)
}
outputContext?.draw(effectImage.cgImage!, in: imageRect)
outputContext?.restoreGState()
}
// Add in color tint.
if let color = tintColor {
outputContext?.saveGState()
outputContext?.setFillColor(color.cgColor)
outputContext?.fill(imageRect)
outputContext?.restoreGState()
}
// Output image is ready.
let outputImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return outputImage
}
}
| 42.453333 | 152 | 0.579355 |
eb4d4d4c23b70a24c7dc4552dc7ea5fee040cc70 | 496 | import SwiftUI
struct ChartTypeKey: EnvironmentKey {
static let defaultValue: AnyChartType = AnyChartType(BarChart())
//AnyChartType(LineChart())
}
struct ChartStyleKey: EnvironmentKey {
static let defaultValue: ChartStyle = ChartStyle(backgroundColor: .white,
foregroundColor: ColorGradient(ChartColors.orangeDark,
ChartColors.orangeBright))
}
| 38.153846 | 110 | 0.574597 |
03d6a06e0774c5c2758967ca496f4508ed244936 | 6,804 | //
// sdmEffectView.swift
// RadialSlider
//
// Created by Peter JC Spencer on 29/06/2015.
// Copyright (c) 2015 Spencer's digital media. All rights reserved.
//
import UIKit
class EffectView : UIView
{
// MARK: -
var locked: Bool = false
private var _ramp: CGFloat = 0.0
var ramp: CGFloat
{
get { return self._ramp }
set
{
if !self.locked
{
self._ramp = newValue < 0.0 ? 0.0 : newValue
self._ramp = newValue > 1.0 ? 1.0 : newValue
if let aLayer = self.layer as? EffectLayer
{ aLayer.offset = newValue }
self.setNeedsDisplay()
}
}
}
var sourceRadius: CGFloat = 100.0
var destinationRadius: CGFloat = 18.0
var destinationOffset: CGFloat = 125.0
var srcCentre: CGPoint!
var srcScale: CGFloat = 0.7
var dstCentre: CGPoint!
var dstScale: CGFloat = 1.0
var controlOffset: CGPoint!
// MARK: -
override var frame: CGRect {
didSet
{
self.srcCentre = CGPointMake(self.bounds.size.width * 0.5,
self.bounds.size.width * 0.5)
self.dstCentre = CGPointMake(self.srcCentre.x + self.destinationOffset,
self.srcCentre.y)
}
}
// MARK: - Initializing a View Object (UIView)
override init(frame: CGRect) {
super.init(frame: frame)
self.clipsToBounds = false
self.backgroundColor = UIColor.clearColor()
self.userInteractionEnabled = false
self.srcCentre = CGPointMake(self.bounds.size.width * 0.5, self.bounds.size.width * 0.5)
self.dstCentre = CGPointMake(self.srcCentre.x + self.destinationOffset, self.srcCentre.y)
self.controlOffset = CGPointMake(20.0, 10.0)
}
// MARK: - NSCoding Protocol
required init(coder decoder: NSCoder) { super.init(coder: decoder)! }
// MARK: -
override class func layerClass() -> AnyClass { return EffectLayer.self }
// MARK: -
func setRamp(newValue: CGFloat, animated: Bool)
{
if animated
{
let animation: CABasicAnimation = CABasicAnimation(keyPath: "offset")
animation.duration = 0.35
animation.timingFunction = CAMediaTimingFunction(controlPoints: 0.7, 0.0, 0.2, 1.0)
animation.fromValue = self._ramp
animation.toValue = 0.0
self.layer.addAnimation(animation, forKey: nil)
}
else { self._ramp = newValue }
if let aLayer = self.layer as? EffectLayer
{
aLayer.offset = 0.0
}
}
// MARK: -
override func drawRect(rect: CGRect) {
// Super.
super.drawRect(rect)
let context: CGContextRef = UIGraphicsGetCurrentContext ()!
CGContextSetFillColorWithColor(context, UIColor.cyanColor().CGColor)
if self.locked && (self._ramp <= 0.0)
{
CGContextAddEllipseInRect(context,
CGRectMake((rect.size.width * 0.5) - (self.sourceRadius * 0.5),
(rect.size.height * 0.5) - (self.sourceRadius * 0.5),
self.sourceRadius,
self.sourceRadius));
CGContextFillPath (context)
return
}
let srcRadius: CGFloat = Math.interpLinear(self._ramp, start: self.sourceRadius, end: self.sourceRadius * self.srcScale)
let dstRadius: CGFloat = Math.interpLinear(self._ramp, start: self.sourceRadius, end: self.destinationRadius * self.dstScale)
let dstCentreX: CGFloat = Math.interpLinear(self._ramp, start: self.srcCentre.x, end: self.dstCentre.x)
var controlAngle: CGFloat = CGFloat( Math.degreesToRadians( Double(Math.interpLinear(self._ramp, start: 280.0, end: 300.0))) )
var endAngle: CGFloat = CGFloat( Math.degreesToRadians( Double(Math.interpLinear(self._ramp, start: 290.0, end: 260.0))) )
let xOffset: CGFloat = Math.interpLinear(self._ramp, start: 0.0, end: self.controlOffset.x)
let yOffset: CGFloat = Math.interpLinear(self._ramp, start: 0.0, end: self.controlOffset.y)
// Top.
CGContextAddArc(context,
self.srcCentre.x,
self.srcCentre.y,
srcRadius * 0.5,
CGFloat(Math.degreesToRadians(180.0)),
controlAngle,
0)
CGContextAddQuadCurveToPoint(context,
self.srcCentre.x + cos(controlAngle) * (srcRadius * 0.5) + xOffset,
self.srcCentre.y + sin(controlAngle) * (srcRadius * 0.5) + yOffset,
dstCentreX + cos(endAngle) * (dstRadius * 0.5),
self.dstCentre.y + sin(endAngle) * (dstRadius * 0.5))
CGContextAddArc(context,
dstCentreX,
self.dstCentre.y,
dstRadius * 0.5,
CGFloat(Math.degreesToRadians(290.0)),
0.0,
0)
// Move.
CGContextMoveToPoint(context, self.srcCentre.x - (srcRadius * 0.5), self.srcCentre.y)
controlAngle = CGFloat( Math.degreesToRadians( Double(Math.interpLinear(self._ramp, start: 80.0, end: 60.0))) )
endAngle = CGFloat( Math.degreesToRadians( Double(Math.interpLinear(self._ramp, start: 70.0, end: 100.0))) )
// Bottom.
CGContextAddArc(context,
self.srcCentre.x,
self.srcCentre.y,
srcRadius * 0.5,
CGFloat(Math.degreesToRadians(180.0)),
CGFloat(Math.degreesToRadians(Double(Math.interpLinear(self._ramp, start: 80.0, end: 60.0)))),
1)
CGContextAddQuadCurveToPoint(context,
self.srcCentre.x + cos(controlAngle) * (srcRadius * 0.5) + xOffset,
self.srcCentre.y + sin(controlAngle) * (srcRadius * 0.5) - yOffset,
dstCentreX + cos(endAngle) * (dstRadius * 0.5),
self.dstCentre.y + sin(endAngle) * (dstRadius * 0.5))
CGContextAddArc(context,
dstCentreX,
self.dstCentre.y,
dstRadius * 0.5,
CGFloat(Math.degreesToRadians(70.0)),
0.0,
1)
CGContextFillPath (context)
}
override func drawLayer(layer: CALayer, inContext ctx: CGContext) {
if let aLayer = layer as? EffectLayer
{
self._ramp = aLayer.offset
}
if self._ramp < 0.0 { self._ramp = 0.0 }
// Super.
super.drawLayer(layer, inContext: ctx)
}
}
| 31.794393 | 134 | 0.55629 |
26070b438503437c137b4c9bc14543b0e0242406 | 7,866 | //
// ToolType.swift
// DevToys
//
// Created by yuki on 2022/01/29.
//
import Cocoa
enum ToolType: String, CaseIterable {
case allTools
case jsonYamlConvertor
case numberBaseConvertor
case dateConvertor
case htmlDecoder
case urlDecoder
case base64Decoder
case jwtDecoder
case jsonFormatter
case xmlFormatter
case hashGenerator
case uuidGenerator
case loremIpsumGenerator
case checksumGenerator
case caseConverter
case regexTester
case hyphenationRemover
case imageCompressor
case pdfGenerator
case imageConverter
case networkInformation
case apiTest
}
extension ToolType {
var sidebarIcon: NSImage {
switch self {
case .allTools: return R.Image.Sidebar.home
case .jsonYamlConvertor: return R.Image.Sidebar.jsonConvert
case .numberBaseConvertor: return R.Image.Sidebar.numberBaseConvert
case .htmlDecoder: return R.Image.Sidebar.htmlCoder
case .urlDecoder: return R.Image.Sidebar.urlCoder
case .base64Decoder: return R.Image.Sidebar.base64Coder
case .jwtDecoder: return R.Image.Sidebar.jwtCoder
case .jsonFormatter: return R.Image.Sidebar.jsonFormatter
case .xmlFormatter: return R.Image.Sidebar.jsonFormatter
case .hashGenerator: return R.Image.Sidebar.hashGenerator
case .uuidGenerator: return R.Image.Sidebar.uuidGenerator
case .loremIpsumGenerator: return R.Image.Sidebar.loremIpsumGenerator
case .checksumGenerator: return R.Image.Sidebar.hashGenerator
case .caseConverter: return R.Image.Sidebar.textInspector
case .regexTester: return R.Image.Sidebar.regexTester
case .hyphenationRemover: return R.Image.Sidebar.textIspector
case .imageCompressor: return R.Image.Sidebar.imageCompressor
case .imageConverter: return R.Image.Sidebar.imageCompressor
case .pdfGenerator: return R.Image.Sidebar.graphic
case .networkInformation: return R.Image.Sidebar.network
case .apiTest: return R.Image.Sidebar.api
case .dateConvertor: return R.Image.speed
}
}
var toolListIcon: NSImage {
switch self {
case .allTools: return R.Image.ToolList.home
case .jsonYamlConvertor: return R.Image.ToolList.jsonConvert
case .numberBaseConvertor: return R.Image.ToolList.numberBaseConvert
case .htmlDecoder: return R.Image.ToolList.htmlCoder
case .urlDecoder: return R.Image.ToolList.urlCoder
case .base64Decoder: return R.Image.ToolList.base64Coder
case .jwtDecoder: return R.Image.ToolList.jwtCoder
case .jsonFormatter: return R.Image.ToolList.jsonFormatter
case .xmlFormatter: return R.Image.ToolList.jsonFormatter
case .hashGenerator: return R.Image.ToolList.hashGenerator
case .uuidGenerator: return R.Image.ToolList.uuidGenerator
case .loremIpsumGenerator: return R.Image.ToolList.loremIpsumGenerator
case .checksumGenerator: return R.Image.ToolList.hashGenerator
case .caseConverter: return R.Image.ToolList.textInspector
case .regexTester: return R.Image.ToolList.regexTester
case .hyphenationRemover: return R.Image.ToolList.textIspector
case .imageCompressor: return R.Image.ToolList.imageCompressor
case .imageConverter: return R.Image.ToolList.imageCompressor
case .pdfGenerator: return R.Image.ToolList.graphic
case .networkInformation: return R.Image.ToolList.network
case .apiTest: return R.Image.ToolList.api
case .dateConvertor: return R.Image.speed
}
}
var sidebarTitle: String {
switch self {
case .allTools: return "Home"
case .jsonYamlConvertor: return "JSON <> Yaml"
case .numberBaseConvertor: return "Number Base"
case .htmlDecoder: return "HTML"
case .urlDecoder: return "URL"
case .base64Decoder: return "Base 64"
case .jwtDecoder: return "JWT Decoder"
case .jsonFormatter: return "JSON"
case .xmlFormatter: return "XML"
case .hashGenerator: return "Hash"
case .uuidGenerator: return "UUID"
case .loremIpsumGenerator: return "Lorem Ipsum"
case .checksumGenerator: return "Checksum"
case .caseConverter: return "Inspector & Case Converter"
case .regexTester: return "Regex"
case .hyphenationRemover: return "Hyphen Remover"
case .imageCompressor: return "PNG / JPEG Compressor"
case .imageConverter: return "Image Converter"
case .pdfGenerator: return "PDF Generator"
case .networkInformation: return "Information"
case .apiTest: return "API"
case .dateConvertor: return "Date"
}
}
var toolListTitle: String {
switch self {
case .allTools: return "Home"
case .jsonYamlConvertor: return "JSON <> Yaml"
case .numberBaseConvertor: return "Number Base Converter"
case .htmlDecoder: return "HTML Encoder / Decoder"
case .urlDecoder: return "URL Encoder / Decoder"
case .base64Decoder: return "Base 64 Encoder / Decoder"
case .jwtDecoder: return "JWT Decoder"
case .jsonFormatter: return "JSON Formatter"
case .xmlFormatter: return "XML Formatter"
case .hashGenerator: return "Hash Generator"
case .uuidGenerator: return "UUID Generator"
case .loremIpsumGenerator: return "Lorem Ipsum Generator"
case .checksumGenerator: return "Checksum Generator"
case .caseConverter: return "Text Case Converter and Inspector"
case .regexTester: return "Regex Tester"
case .hyphenationRemover: return "Hyphenation Remover"
case .pdfGenerator: return "PDF Generator"
case .imageCompressor: return "PNG / JPEG Compressor"
case .imageConverter: return "Image Converter"
case .networkInformation: return "Network Information"
case .apiTest: return "API Tester"
case .dateConvertor: return "Date Converter"
}
}
var toolDescription: String {
switch self {
case .allTools: return "All Tools"
case .jsonYamlConvertor: return "Convert Json data to Yaml and vice versa"
case .numberBaseConvertor: return "Convert numbers from one base to another"
case .htmlDecoder: return "Encoder or decode all the applicable charactors to their corresponding HTML"
case .urlDecoder: return "Encoder or decode all the applicable charactors to their corresponding URL"
case .base64Decoder: return "Encode and decode Base64 data"
case .jwtDecoder: return "Decode a JWT header playload and signature"
case .jsonFormatter: return "Indent or minify Json data"
case .xmlFormatter: return "Indent or minify XML data"
case .hashGenerator: return "Calculate MD5, SHA1, SHA256 and SHA 512 hash from text data"
case .uuidGenerator: return "Generate UUIDs version 1 and 4"
case .loremIpsumGenerator: return "Generate Lorem Ipsum placeholder text"
case .checksumGenerator: return "Generate or Test checksum of a file"
case .caseConverter: return "Analyze text and convert it to differenct case"
case .regexTester: return "Test reguler expression"
case .hyphenationRemover: return "Remove hyphenations copied from PDF text"
case .pdfGenerator: return "Generate PDF from images"
case .imageCompressor: return "Lossless PNG and JPEG optimizer"
case .imageConverter: return "Convert image format and size"
case .networkInformation: return "Observe network information"
case .apiTest: return "Send request to servers"
case .dateConvertor: return "Convert date to other style"
}
}
}
| 44.440678 | 111 | 0.694762 |
acb8e4d57ce0298be3276b889d765e039cade97f | 1,867 | import XCTest
import UIKit
import Nimble
@testable import Bento
final class DeletableTests: XCTestCase {
func test_it_has_correct_title() {
let section = Section(id: 0)
|---+ Node(id: 0, component: DummyComponent()
.deletable(deleteActionText: "Remove", didDelete: {}))
let tableView = UITableView()
let adapter = TableViewAdapterBase<Int, Int>(with: tableView)
adapter.update(sections: [section])
if #available(iOS 11.0, *) {
let action = adapter.tableView(tableView, trailingSwipeActionsConfigurationForRowAt: IndexPath(row: 0, section: 0))
expect(action?.actions.first?.title) == "Remove"
}
}
func test_it_calls_delete() {
var called = false
let section = Section(id: 0)
|---+ Node(id: 0, component: DummyComponent()
.deletable(deleteActionText: "", didDelete: {
called = true
})
)
let tableView = UITableView()
let adapter = BentoTableViewAdapter<Int, Int>(with: tableView)
tableView.delegate = adapter
tableView.dataSource = adapter
adapter.update(sections: [section])
if #available(iOS 11.0, *) {
let action = adapter.tableView(tableView, trailingSwipeActionsConfigurationForRowAt: IndexPath(row: 0, section: 0))!.actions.first!
action.handler(action, UIView(), {_ in })
expect(called).toEventually(beTrue())
}
}
func test_it_is_deletable_after_composing_with_other() {
let component = DummyComponent()
.deletable(deleteActionText: "Delete", didDelete: {})
.on()
expect(component.cast(to: Deletable.self)).toNot(beNil())
}
}
final class DummyComponent: Renderable {
func render(in view: UIView) {}
}
| 33.339286 | 143 | 0.610605 |
2336ba67d643b7366e527f910fdfa82d66f62bbf | 789 | //
// ___FILENAME___
// ___PROJECTNAME___
//
// Created by ___FULLUSERNAME___ on ___DATE___.
//___COPYRIGHT___
//
import UIKit
import BDNetworking
class ___FILEBASENAMEASIDENTIFIER___: NSObject {
static let kIsSuccesss = "success" // bool
}
extension ___FILEBASENAMEASIDENTIFIER___: BDAPIManagerDataReformer {
@objc func reformData(manager: BDAPIBaseManager, data: Any?) -> Any {
var result: [String: Any] = [:]
guard let dic = data as? [String: Any] else { return [:] }
guard let isSuccess = dic["success"] as? Bool, isSuccess else { return [:] }
guard let userInfo = dic["data"] as? [String: Any] else { return [:] }
result[___FILEBASENAMEASIDENTIFIER___.kIsSuccesss] = true
result = userInfo
return result
}
}
| 27.206897 | 84 | 0.670469 |
c118926b0e858ed57924eb1b2a1863899dc888e7 | 1,683 | // Copyright 2020 Carton contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
import Vapor
extension Application {
func configure(
mainWasmPath: String,
onWebSocketOpen: @escaping (WebSocket) -> (),
onWebSocketClose: @escaping (WebSocket) -> ()
) {
let directory = FileManager.default.homeDirectoryForCurrentUser
.appendingPathComponent(".carton")
.appendingPathComponent("static")
.path
middleware.use(FileMiddleware(publicDirectory: directory))
// register routes
get { _ in
HTML(value: #"""
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script type="text/javascript" src="dev.js"></script>
</head>
<body>
</body>
</html>
"""#)
}
webSocket("watcher") { _, ws in
onWebSocketOpen(ws)
ws.onClose.whenComplete { _ in onWebSocketClose(ws) }
}
get("main.wasm") { (request: Request) in
// stream the file
request.eventLoop.makeSucceededFuture(request.fileio.streamFile(at: mainWasmPath))
}
}
}
| 30.053571 | 88 | 0.658348 |
46d65639db56f726de16324a907c5e07e18a4a5c | 824 | //
// Created by duan on 2018/3/7.
// 2018 Copyright (c) RxSwiftCommunity. All rights reserved.
//
#if os(iOS)
import UIKit
import RxSwift
import RxCocoa
public extension Reactive where Base: UISearchBar {
/// Bindable sink for `barStyle` property
var barStyle: Binder<UIBarStyle> {
return Binder(self.base) { view, attr in
view.barStyle = attr
}
}
/// Bindable sink for `barTintColor` property
var barTintColor: Binder<UIColor?> {
return Binder(self.base) { view, attr in
view.barTintColor = attr
}
}
/// Bindable sink for `keyboardAppearance` property
var keyboardAppearance: Binder<UIKeyboardAppearance> {
return Binder(self.base) { view, attr in
view.keyboardAppearance = attr
}
}
}
#endif
| 21.684211 | 61 | 0.632282 |
1605cd3c15fb019f25cc7424bbc893f06a9eddc9 | 14,093 | /***
*
* ███╗ ██╗ █████╗ ████████╗██████╗ ███████╗ ████████╗██╗ ██╗███████╗███╗ ███╗███████╗███████╗
* ████╗ ██║██╔══██╗╚══██╔══╝██╔══██╗██╔════╝ ╚══██╔══╝██║ ██║██╔════╝████╗ ████║██╔════╝██╔════╝
* ██╔██╗ ██║███████║ ██║ ██║ ██║███████╗█████╗██║ ███████║█████╗ ██╔████╔██║█████╗ ███████╗
* ██║╚██╗██║██╔══██║ ██║ ██║ ██║╚════██║╚════╝██║ ██╔══██║██╔══╝ ██║╚██╔╝██║██╔══╝ ╚════██║
* ██║ ╚████║██║ ██║ ██║ ██████╔╝███████║ ██║ ██║ ██║███████╗██║ ╚═╝ ██║███████╗███████║
* ╚═╝ ╚═══╝╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚══════╝ ╚═╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚══════╝╚══════╝
*
* https://github.com/natura-cosmeticos/natds-commons/tree/master/packages/natds-themes
*
* Generated by natds-themes in Thu Aug 19 2021
* Do not edit this file.
*
* If you have any trouble or a feature request, open an issue:
* https://github.com/natura-cosmeticos/natds-commons/issues
*
*/
struct AesopLightTheme: Theme {
let tokens: Tokens = AesopLightTokens()
let components: Components = AesopLightComponents()
}
struct AesopLightTokens: Tokens {
let assetFontFileDisplay = "ZapfHumanist601BT-Roman"
let assetFontFileHeadline = "SuisseIntl-Regular"
let assetFontFileBodyRegular = "SuisseIntl-Regular"
let assetFontFileBodyBold = "SuisseIntl-Regular"
let assetBrandNeutralAFile = "aesop-a-official"
let assetBrandNeutralAWidth: CGFloat = 256
let assetBrandNeutralAHeight: CGFloat = 82
let assetBrandNeutralBFile = "aesop-a-official"
let assetBrandNeutralBWidth: CGFloat = 256
let assetBrandNeutralBHeight: CGFloat = 82
let assetBrandCustomAFile = "aesop-a-custom"
let assetBrandCustomAWidth: CGFloat = 256
let assetBrandCustomAHeight: CGFloat = 82
let assetBrandCustomBFile = "aesop-a-custom"
let assetBrandCustomBWidth: CGFloat = 256
let assetBrandCustomBHeight: CGFloat = 82
let borderRadiusNone: CGFloat = 0
let borderRadiusSmall: CGFloat = 2
let borderRadiusMedium: CGFloat = 4
let borderRadiusLarge: CGFloat = 8
let colorPrimary = "#262625"
let colorOnPrimary = "#FFFFFF"
let colorPrimaryLight = "#4E4E4D"
let colorOnPrimaryLight = "#FFFFFF"
let colorPrimaryDark = "#000000"
let colorOnPrimaryDark = "#FFFFFF"
let colorSecondary = "#A6662B"
let colorOnSecondary = "#FFFFFF"
let colorSecondaryLight = "#DB9457"
let colorOnSecondaryLight = "#000000"
let colorSecondaryDark = "#733B00"
let colorOnSecondaryDark = "#FFFFFF"
let colorBackground = "#FAFAFA"
let colorOnBackground = "#333333"
let colorSurface = "#FFFFFF"
let colorOnSurface = "#333333"
let colorHighlight = "#000000"
let colorHighEmphasis = "#333333"
let colorMediumEmphasis = "#777777"
let colorLowEmphasis = "#BBBBBB"
let colorLink = "#227BBD"
let colorOnLink = "#FFFFFF"
let colorSuccess = "#569A32"
let colorOnSuccess = "#FFFFFF"
let colorWarning = "#FCC433"
let colorOnWarning = "#333333"
let colorAlert = "#E74627"
let colorOnAlert = "#FFFFFF"
let elevationNoneShadowColor = "nil"
let elevationNoneShadowOffsetWidth: CGFloat = 0
let elevationNoneShadowOffsetHeight: CGFloat = -3
let elevationNoneShadowRadius: CGFloat = 3
let elevationNoneShadowOpacity: Float = 0
let elevationMicroShadowColor = "#000000"
let elevationMicroShadowOffsetWidth: CGFloat = 0
let elevationMicroShadowOffsetHeight: CGFloat = 1
let elevationMicroShadowRadius: CGFloat = 1
let elevationMicroShadowOpacity: Float = 0.14
let elevationTinyShadowColor = "#000000"
let elevationTinyShadowOffsetWidth: CGFloat = 0
let elevationTinyShadowOffsetHeight: CGFloat = 2
let elevationTinyShadowRadius: CGFloat = 2
let elevationTinyShadowOpacity: Float = 0.14
let elevationSmallShadowColor = "#000000"
let elevationSmallShadowOffsetWidth: CGFloat = 0
let elevationSmallShadowOffsetHeight: CGFloat = 3
let elevationSmallShadowRadius: CGFloat = 4
let elevationSmallShadowOpacity: Float = 0.14
let elevationMediumShadowColor = "#000000"
let elevationMediumShadowOffsetWidth: CGFloat = 0
let elevationMediumShadowOffsetHeight: CGFloat = 4
let elevationMediumShadowRadius: CGFloat = 5
let elevationMediumShadowOpacity: Float = 0.14
let elevationLargeShadowColor = "#000000"
let elevationLargeShadowOffsetWidth: CGFloat = 0
let elevationLargeShadowOffsetHeight: CGFloat = 6
let elevationLargeShadowRadius: CGFloat = 10
let elevationLargeShadowOpacity: Float = 0.14
let elevationLargeXShadowColor = "#000000"
let elevationLargeXShadowOffsetWidth: CGFloat = 0
let elevationLargeXShadowOffsetHeight: CGFloat = 8
let elevationLargeXShadowRadius: CGFloat = 10
let elevationLargeXShadowOpacity: Float = 0.14
let elevationLargeXXShadowColor = "#000000"
let elevationLargeXXShadowOffsetWidth: CGFloat = 0
let elevationLargeXXShadowOffsetHeight: CGFloat = 9
let elevationLargeXXShadowRadius: CGFloat = 12
let elevationLargeXXShadowOpacity: Float = 0.14
let elevationHugeShadowColor = "#000000"
let elevationHugeShadowOffsetWidth: CGFloat = 0
let elevationHugeShadowOffsetHeight: CGFloat = 12
let elevationHugeShadowRadius: CGFloat = 17
let elevationHugeShadowOpacity: Float = 0.14
let elevationHugeXShadowColor = "#000000"
let elevationHugeXShadowOffsetWidth: CGFloat = 0
let elevationHugeXShadowOffsetHeight: CGFloat = 16
let elevationHugeXShadowRadius: CGFloat = 24
let elevationHugeXShadowOpacity: Float = 0.14
let elevationHugeXXShadowColor = "#000000"
let elevationHugeXXShadowOffsetWidth: CGFloat = 0
let elevationHugeXXShadowOffsetHeight: CGFloat = 24
let elevationHugeXXShadowRadius: CGFloat = 38
let elevationHugeXXShadowOpacity: Float = 0.14
let opacityTransparent: CGFloat = 0
let opacityLower: CGFloat = 0.04
let opacityVeryLow: CGFloat = 0.08
let opacityLow: CGFloat = 0.12
let opacityMediumLow: CGFloat = 0.16
let opacityDisabledLow: CGFloat = 0.24
let opacityDisabled: CGFloat = 0.32
let opacityMedium: CGFloat = 0.48
let opacityMediumHigh: CGFloat = 0.56
let opacityHigh: CGFloat = 0.64
let opacityVeryHigh: CGFloat = 0.8
let opacityOpaque: CGFloat = 1
let sizeNone: CGFloat = 0
let sizeMicro: CGFloat = 4
let sizeTiny: CGFloat = 8
let sizeSmall: CGFloat = 16
let sizeStandard: CGFloat = 24
let sizeSemi: CGFloat = 32
let sizeSemiX: CGFloat = 40
let sizeMedium: CGFloat = 48
let sizeMediumX: CGFloat = 56
let sizeLarge: CGFloat = 64
let sizeLargeX: CGFloat = 72
let sizeLargeXX: CGFloat = 80
let sizeLargeXXX: CGFloat = 88
let sizeHuge: CGFloat = 96
let sizeHugeX: CGFloat = 128
let sizeHugeXX: CGFloat = 144
let sizeHugeXXX: CGFloat = 192
let sizeVeryHuge: CGFloat = 256
let spacingNone: CGFloat = 0
let spacingMicro: CGFloat = 4
let spacingTiny: CGFloat = 8
let spacingSmall: CGFloat = 16
let spacingStandard: CGFloat = 24
let spacingSemi: CGFloat = 32
let spacingLarge: CGFloat = 48
let spacingXLarge: CGFloat = 64
let typographyFontFamilyPrimary = "San Francisco"
let typographyFontFamilySecondary = "sans-serif"
let typographyFontFamilyBranding = "Helvetica Now"
let typographyFontFamilyCode = "SF Mono"
let typographyLineHeightReset: CGFloat = 1
let typographyLineHeightSmall: CGFloat = 1.25
let typographyLineHeightMedium: CGFloat = 1.5
let typographyLineHeightLarge: CGFloat = 2
let typographyFontWeightRegular: UIFont.Weight = .regular
let typographyFontWeightMedium: UIFont.Weight = .medium
let typographyDisplayFontFamily = "Zapf Humanist 601"
let typographyDisplayFontWeight: UIFont.Weight = .regular
let typographyHeadlineFontFamily = "Suisse Int'l"
let typographyHeadlineFontWeight: UIFont.Weight = .regular
let typographyBodyRegularFontFamily = "Suisse Int'l"
let typographyBodyRegularFontWeight: UIFont.Weight = .regular
let typographyBodyBoldFontFamily = "Suisse Int'l"
let typographyBodyBoldFontWeight: UIFont.Weight = .bold
let typographyFallbackFontFamily = "San Francisco"
let typographyFallbackFontWeight: UIFont.Weight = .regular
}
struct AesopLightComponents: Components {
let badgeLabelFontSize: CGFloat = 12
let badgeLabelLetterSpacing: CGFloat = 0.16
let badgeLabelLineHeight: CGFloat = 1.5
let badgeLabelPrimaryFontFamily = "San Francisco"
let badgeLabelPrimaryFontWeight: UIFont.Weight = .regular
let badgeLabelFallbackFontFamily = "San Francisco"
let badgeLabelFallbackFontWeight: UIFont.Weight = .regular
let badgeStandardHeight: CGFloat = 16
let badgeStandardBorderRadius: CGFloat = 8
let badgeDotHeight: CGFloat = 8
let badgeDotBorderRadius: CGFloat = 4
let badgeColorPrimaryLabel = "#FFFFFF"
let badgeColorPrimaryBackground = "#262625"
let badgeColorSecondaryLabel = "#FFFFFF"
let badgeColorSecondaryBackground = "#A6662B"
let badgeColorSuccessLabel = "#FFFFFF"
let badgeColorSuccessBackground = "#569A32"
let badgeColorAlertLabel = "#FFFFFF"
let badgeColorAlertBackground = "#E74627"
let buttonDefaultFontSize: CGFloat = 14
let buttonDefaultFontWeight: UIFont.Weight = .medium
let buttonDefaultLetterSpacing: CGFloat = 0.44
let buttonDefaultLineHeight: CGFloat = 1.5
let buttonLabelFontSize: CGFloat = 14
let buttonLabelLetterSpacing: CGFloat = 0.44
let buttonLabelLineHeight: CGFloat = 1.5
let buttonLabelPrimaryFontFamily = "San Francisco"
let buttonLabelPrimaryFontWeight: UIFont.Weight = .medium
let buttonLabelFallbackFontFamily = "San Francisco"
let buttonLabelFallbackFontWeight: UIFont.Weight = .medium
let buttonBorderRadius: CGFloat = 4
let buttonContainedColorEnableBackground = "#262625"
let buttonContainedColorEnableBorder = "#FFFFFF00"
let buttonContainedColorEnableLabel = "#FFFFFF"
let buttonContainedColorDisableBackground = "#BBBBBB"
let buttonContainedColorDisableBorder = "#FFFFFF00"
let buttonContainedColorDisableLabel = "#333333"
let buttonContainedColorHoverBackground = "#000000"
let buttonContainedColorHoverBorder = "#FFFFFF00"
let buttonContainedColorHoverLabel = "#FFFFFF"
let buttonContainedColorFocusBackground = "#232323"
let buttonContainedColorFocusBorder = "#FFFFFF00"
let buttonContainedColorFocusLabel = "#FFFFFF"
let buttonOutlinedColorEnableBackground = "#FFFFFF00"
let buttonOutlinedColorEnableBorder = "#262625"
let buttonOutlinedColorEnableLabel = "#333333"
let buttonOutlinedColorDisableBackground = "#FFFFFF00"
let buttonOutlinedColorDisableBorder = "#BBBBBB"
let buttonOutlinedColorDisableLabel = "#777777"
let buttonOutlinedColorHoverBackground = "#EEEEEE"
let buttonOutlinedColorHoverBorder = "#262625"
let buttonOutlinedColorHoverLabel = "#333333"
let buttonOutlinedColorFocusBackground = "#E3E3E3"
let buttonOutlinedColorFocusBorder = "#262625"
let buttonOutlinedColorFocusLabel = "#333333"
let buttonTextColorEnableBackground = "#FFFFFF00"
let buttonTextColorEnableBorder = "#FFFFFF00"
let buttonTextColorEnableLabel = "#333333"
let buttonTextColorDisableBackground = "#FFFFFF00"
let buttonTextColorDisableBorder = "#FFFFFF00"
let buttonTextColorDisableLabel = "#777777"
let buttonTextColorHoverBackground = "#EEEEEE"
let buttonTextColorHoverBorder = "#FFFFFF00"
let buttonTextColorHoverLabel = "#333333"
let buttonTextColorFocusBackground = "#E3E3E3"
let buttonTextColorFocusBorder = "#FFFFFF00"
let buttonTextColorFocusLabel = "#333333"
let dialogTitleFontSize: CGFloat = 20
let dialogTitleLetterSpacing: CGFloat = 0.12
let dialogTitleLineHeight: CGFloat = 1.25
let dialogTitlePrimaryFontFamily = "San Francisco"
let dialogTitlePrimaryFontWeight: UIFont.Weight = .medium
let dialogTitleFallbackFontFamily = "San Francisco"
let dialogTitleFallbackFontWeight: UIFont.Weight = .regular
let dialogBodyFontSize: CGFloat = 16
let dialogBodyLetterSpacing: CGFloat = 0.32
let dialogBodyLineHeight: CGFloat = 1.5
let dialogBodyPrimaryFontFamily = "San Francisco"
let dialogBodyPrimaryFontWeight: UIFont.Weight = .regular
let dialogBodyFallbackFontFamily = "San Francisco"
let dialogBodyFallbackFontWeight: UIFont.Weight = .regular
let heading1FontSize: CGFloat = 96
let heading1FontWeight: UIFont.Weight = .regular
let heading1LetterSpacing: CGFloat = 0
let heading2FontSize: CGFloat = 60
let heading2FontWeight: UIFont.Weight = .regular
let heading2LetterSpacing: CGFloat = 0
let heading3FontSize: CGFloat = 48
let heading3FontWeight: UIFont.Weight = .regular
let heading3LetterSpacing: CGFloat = 0
let heading4FontSize: CGFloat = 34
let heading4FontWeight: UIFont.Weight = .regular
let heading4LetterSpacing: CGFloat = 0.08
let heading5FontSize: CGFloat = 24
let heading5FontWeight: UIFont.Weight = .regular
let heading5LetterSpacing: CGFloat = 0
let heading6FontSize: CGFloat = 20
let heading6FontWeight: UIFont.Weight = .medium
let heading6LetterSpacing: CGFloat = 0.12
let subtitle1FontSize: CGFloat = 16
let subtitle1FontWeight: UIFont.Weight = .medium
let subtitle1LetterSpacing: CGFloat = 0.08
let subtitle2FontSize: CGFloat = 14
let subtitle2FontWeight: UIFont.Weight = .medium
let subtitle2LetterSpacing: CGFloat = 0.08
let body1FontSize: CGFloat = 16
let body1FontWeight: UIFont.Weight = .regular
let body1LetterSpacing: CGFloat = 0.32
let body2FontSize: CGFloat = 14
let body2FontWeight: UIFont.Weight = .regular
let body2LetterSpacing: CGFloat = 0.16
let captionFontSize: CGFloat = 12
let captionFontWeight: UIFont.Weight = .regular
let captionLetterSpacing: CGFloat = 0.16
let overlineFontSize: CGFloat = 12
let overlineFontWeight: UIFont.Weight = .medium
let overlineLetterSpacing: CGFloat = 0.8
}
| 45.905537 | 102 | 0.713546 |
acf0f59f7a542c2bbcff400f52557d98da698039 | 3,713 | //
// SuperheroViewController.swift
// flixxer
//
// Created by jordan on 3/17/18.
// Copyright © 2018 MMI. All rights reserved.
//
import UIKit
class SuperheroViewController: UIViewController,UICollectionViewDataSource {
@IBOutlet weak var collectionView: UICollectionView!
var movies: [[String: Any]] = []
var refreshControl: UIRefreshControl!
override func viewDidLoad()
{
super.viewDidLoad()
collectionView.dataSource = self
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.minimumInteritemSpacing = 5
layout.minimumLineSpacing = layout.minimumInteritemSpacing
let cellsPerLine :CGFloat = 3
let interItemSpacingTotal = layout.minimumInteritemSpacing * (cellsPerLine - 1)
let width = collectionView.frame.size.width / cellsPerLine - interItemSpacingTotal / cellsPerLine
layout.itemSize = CGSize(width: width, height: width * 3/2)
print ("About to fetch movies")
fetchMovies()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return movies.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
print ("setting collection cells")
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PosterCell", for: indexPath) as! PosterCell
let movie = movies[indexPath.item]
if let posterPathString = movie["poster_path"] as? String{
let baseURLString="https://image.tmdb.org/t/p/w500"
let posterURL = URL(string: baseURLString + posterPathString )!
print ("adding image")
cell.posterImageView.af_setImage(withURL: posterURL)
}
return cell
}
func fetchMovies()
{
let url = URL(string: "https://api.themoviedb.org/3/movie/now_playing?api_key=a07e22bc18f5cb106bfe4cc1f83ad8ed")!
let request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 10)
let session = URLSession(configuration: .default, delegate: nil, delegateQueue: OperationQueue.main)
let task = session.dataTask(with: request) { (data, response, error) in
// This will run when the network request returns
if let error = error
{
print ("code came here")
print(error.localizedDescription)
} else if let data = data
{
print("code works")
let dataDictionary = try! JSONSerialization.jsonObject(with: data, options: []) as! [String: Any]
let movies = dataDictionary["results"] as! [[String: Any]]
self.movies = movies
self.collectionView.reloadData()
self.refreshControl.endRefreshing()
}
}
task.resume()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let cell = sender as! UICollectionViewCell
if let indexPath = collectionView.indexPath(for: cell) {
let movie = movies[indexPath.row]
let movieDetailViewController = segue.destination as! DetailViewController
movieDetailViewController.movie = movie
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 34.37963 | 121 | 0.620522 |
f854de8ed6b756cddadd0b285e13ea43af692678 | 12,745 | //
// DeprecatedCacheModelV5Spec.swift
// LaunchDarklyTests
//
// Created by Mark Pokorny on 4/2/19. +JMJ
// Copyright © 2019 Catamorphic Co. All rights reserved.
//
import Foundation
import Quick
import Nimble
@testable import LaunchDarkly
final class DeprecatedCacheModelV5Spec: QuickSpec {
struct Constants {
static let offsetInterval: TimeInterval = 0.1
}
struct TestContext {
var clientServiceFactoryMock = ClientServiceMockFactory()
var keyedValueCacheMock: KeyedValueCachingMock
var modelV5cache: DeprecatedCacheModelV5
var users: [LDUser]
var userEnvironmentsCollection: [UserKey: CacheableUserEnvironmentFlags]
var uncachedUser: LDUser
var mobileKeys: [MobileKey]
var uncachedMobileKey: MobileKey
var lastUpdatedDates: [UserKey: Date] {
return userEnvironmentsCollection.compactMapValues { (cacheableUserFlags) in
return cacheableUserFlags.lastUpdated
}
}
var sortedLastUpdatedDates: [(userKey: UserKey, lastUpdated: Date)] {
return lastUpdatedDates.map { (userKey, lastUpdated) in
return (userKey, lastUpdated)
}.sorted { (tuple1, tuple2) in
return tuple1.lastUpdated.isEarlierThan(tuple2.lastUpdated)
}
}
var userKeys: [UserKey] {
return users.map { (user) in
return user.key
}
}
init(userCount: Int = 0) {
keyedValueCacheMock = clientServiceFactoryMock.makeKeyedValueCache() as! KeyedValueCachingMock
modelV5cache = DeprecatedCacheModelV5(keyedValueCache: keyedValueCacheMock)
(users, userEnvironmentsCollection, mobileKeys) = CacheableUserEnvironmentFlags.stubCollection(userCount: userCount)
uncachedUser = LDUser.stub()
uncachedMobileKey = UUID().uuidString
keyedValueCacheMock.dictionaryReturnValue = modelV5Dictionary(for: users, and: userEnvironmentsCollection, mobileKeys: mobileKeys)
}
func featureFlags(for userKey: UserKey, and mobileKey: MobileKey) -> [LDFlagKey: FeatureFlag]? {
return userEnvironmentsCollection[userKey]?.environmentFlags[mobileKey]?.featureFlags.modelV5flagCollection
}
func modelV5Dictionary(for users: [LDUser], and userEnvironmentsCollection: [UserKey: CacheableUserEnvironmentFlags], mobileKeys: [MobileKey]) -> [UserKey: Any]? {
guard !users.isEmpty
else {
return nil
}
var cacheDictionary = [UserKey: [String: Any]]()
users.forEach { (user) in
guard let userEnvironment = userEnvironmentsCollection[user.key]
else {
return
}
var environmentsDictionary = [MobileKey: Any]()
let lastUpdated = userEnvironmentsCollection[user.key]?.lastUpdated
mobileKeys.forEach { (mobileKey) in
guard let featureFlags = userEnvironment.environmentFlags[mobileKey]?.featureFlags
else {
return
}
environmentsDictionary[mobileKey] = user.modelV5DictionaryValue(including: featureFlags, using: lastUpdated)
}
cacheDictionary[user.key] = [CacheableEnvironmentFlags.CodingKeys.userKey.rawValue: user.key,
DeprecatedCacheModelV5.CacheKeys.environments: environmentsDictionary]
}
return cacheDictionary
}
func expiredUserKeys(for expirationDate: Date) -> [UserKey] {
return sortedLastUpdatedDates.compactMap { (tuple) in
guard tuple.lastUpdated.isEarlierThan(expirationDate)
else {
return nil
}
return tuple.userKey
}
}
}
override func spec() {
initSpec()
retrieveFlagsSpec()
removeDataSpec()
}
private func initSpec() {
var testContext: TestContext!
describe("init") {
context("with keyed value cache") {
beforeEach {
testContext = TestContext()
}
it("creates a model version 5 cache with the keyed value cache") {
expect(testContext.modelV5cache.keyedValueCache) === testContext.keyedValueCacheMock
}
}
}
}
private func retrieveFlagsSpec() {
var testContext: TestContext!
var cachedData: (featureFlags: [LDFlagKey: FeatureFlag]?, lastUpdated: Date?)!
describe("retrieveFlags") {
context("when no cached data exists") {
beforeEach {
testContext = TestContext()
cachedData = testContext.modelV5cache.retrieveFlags(for: testContext.uncachedUser.key, and: testContext.uncachedMobileKey)
}
it("returns nil values") {
expect(cachedData.featureFlags).to(beNil())
expect(cachedData.lastUpdated).to(beNil())
}
}
context("when cached data exists") {
context("and a cached user is requested") {
beforeEach {
testContext = TestContext(userCount: UserEnvironmentFlagCache.Constants.maxCachedUsers)
}
it("retrieves the cached data") {
testContext.users.forEach { (user) in
let expectedLastUpdated = testContext.userEnvironmentsCollection.lastUpdated(forKey: user.key)?.stringEquivalentDate
testContext.mobileKeys.forEach { (mobileKey) in
let expectedFlags = testContext.featureFlags(for: user.key, and: mobileKey)
cachedData = testContext.modelV5cache.retrieveFlags(for: user.key, and: mobileKey)
expect(cachedData.featureFlags) == expectedFlags
expect(cachedData.lastUpdated) == expectedLastUpdated
}
}
}
}
context("and an uncached mobileKey is requested") {
beforeEach {
testContext = TestContext(userCount: UserEnvironmentFlagCache.Constants.maxCachedUsers)
cachedData = testContext.modelV5cache.retrieveFlags(for: testContext.users.first!.key, and: testContext.uncachedMobileKey)
}
it("returns nil values") {
expect(cachedData.featureFlags).to(beNil())
expect(cachedData.lastUpdated).to(beNil())
}
}
context("and an uncached user is requested") {
beforeEach {
testContext = TestContext(userCount: UserEnvironmentFlagCache.Constants.maxCachedUsers)
cachedData = testContext.modelV5cache.retrieveFlags(for: testContext.uncachedUser.key, and: testContext.mobileKeys.first!)
}
it("returns nil values") {
expect(cachedData.featureFlags).to(beNil())
expect(cachedData.lastUpdated).to(beNil())
}
}
}
}
}
private func removeDataSpec() {
var testContext: TestContext!
var expirationDate: Date!
describe("removeData") {
context("no modelV5 cached data expired") {
beforeEach {
testContext = TestContext(userCount: UserEnvironmentFlagCache.Constants.maxCachedUsers)
let oldestLastUpdatedDate = testContext.sortedLastUpdatedDates.first!
expirationDate = oldestLastUpdatedDate.lastUpdated.addingTimeInterval(-Constants.offsetInterval)
testContext.modelV5cache.removeData(olderThan: expirationDate)
}
it("does not remove any modelV5 cached data") {
expect(testContext.keyedValueCacheMock.setCallCount) == 0
}
}
context("some modelV5 cached data expired") {
beforeEach {
testContext = TestContext(userCount: UserEnvironmentFlagCache.Constants.maxCachedUsers)
let selectedLastUpdatedDate = testContext.sortedLastUpdatedDates[testContext.users.count / 2]
expirationDate = selectedLastUpdatedDate.lastUpdated.addingTimeInterval(-Constants.offsetInterval)
testContext.modelV5cache.removeData(olderThan: expirationDate)
}
it("removes expired modelV5 cached data") {
expect(testContext.keyedValueCacheMock.setCallCount) == 1
expect(testContext.keyedValueCacheMock.setReceivedArguments?.forKey) == DeprecatedCacheModelV5.CacheKeys.userEnvironments
let recachedData = testContext.keyedValueCacheMock.setReceivedArguments?.value as? [String: Any]
let expiredUserKeys = testContext.expiredUserKeys(for: expirationDate)
testContext.userKeys.forEach { (userKey) in
expect(recachedData?.keys.contains(userKey)) == !expiredUserKeys.contains(userKey)
}
}
}
context("all modelV5 cached data expired") {
beforeEach {
testContext = TestContext(userCount: UserEnvironmentFlagCache.Constants.maxCachedUsers)
let newestLastUpdatedDate = testContext.sortedLastUpdatedDates.last!
expirationDate = newestLastUpdatedDate.lastUpdated.addingTimeInterval(Constants.offsetInterval)
testContext.modelV5cache.removeData(olderThan: expirationDate)
}
it("removes all modelV5 cached data") {
expect(testContext.keyedValueCacheMock.removeObjectCallCount) == 1
expect(testContext.keyedValueCacheMock.removeObjectReceivedForKey) == DeprecatedCacheModelV5.CacheKeys.userEnvironments
}
}
context("no modelV5 cached data exists") {
beforeEach {
testContext = TestContext(userCount: UserEnvironmentFlagCache.Constants.maxCachedUsers)
let newestLastUpdatedDate = testContext.sortedLastUpdatedDates.last!
expirationDate = newestLastUpdatedDate.lastUpdated.addingTimeInterval(Constants.offsetInterval)
testContext.keyedValueCacheMock.dictionaryReturnValue = nil //mock simulates no modelV5 cached data
testContext.modelV5cache.removeData(olderThan: expirationDate)
}
it("makes no cached data changes") {
expect(testContext.keyedValueCacheMock.setCallCount) == 0
}
}
}
}
}
// MARK: Expected value from conversion
extension Dictionary where Key == LDFlagKey, Value == FeatureFlag {
var modelV5flagCollection: [LDFlagKey: FeatureFlag] {
return compactMapValues { (originalFeatureFlag) in
guard originalFeatureFlag.value != nil
else {
return nil
}
return originalFeatureFlag
}
}
}
// MARK: Dictionary value to cache
extension LDUser {
func modelV5DictionaryValue(including featureFlags: [LDFlagKey: FeatureFlag], using lastUpdated: Date?) -> [String: Any] {
var userDictionary = dictionaryValueWithAllAttributes(includeFlagConfig: false)
userDictionary.setLastUpdated(lastUpdated)
userDictionary[LDUser.CodingKeys.config.rawValue] = featureFlags.compactMapValues { (featureFlag) in
return featureFlag.modelV5dictionaryValue
}
return userDictionary
}
}
extension FeatureFlag {
/*
[“version”: <modelVersion>,
“flagVersion”: <flagVersion>,
“variation”: <variation>,
“value”: <value>,
“trackEvents”: <trackEvents>,
“debugEventsUntilDate”: <debugEventsUntilDate>]
*/
var modelV5dictionaryValue: [String: Any]? {
guard value != nil
else {
return nil
}
var flagDictionary = dictionaryValue
flagDictionary.removeValue(forKey: FeatureFlag.CodingKeys.flagKey.rawValue)
return flagDictionary
}
}
| 43.797251 | 171 | 0.596783 |
2134ca571db47bf0d3eff799684052a78ce9922b | 954 | //
// Cell.swift
// Mine
//
// Created by kaz on 2020/09/30.
//
import SwiftUI
struct Cell: View, Equatable {
var state: CellState
private func color() -> NSColor {
if state.opened {
if state.mined {
return .red
} else {
return .black
}
} else {
return .lightGray
}
}
private func label() -> String {
if state.opened && state.mined {
return "X"
}
if state.opened, state.numMinesAround > 0 {
return String(state.numMinesAround)
}
return ""
}
var body: some View {
ZStack {
Color(color())
Text(label())
}
.frame(width: 18, height: 18)
}
}
struct Cell_Previews: PreviewProvider {
static var previews: some View {
Cell(state: CellState(id: 0, mined: false, opened: false))
}
}
| 19.469388 | 66 | 0.484277 |
f4381d8dff02bd65ad2bc4f06c7631522b9e20f0 | 214 | //
// VirtualViewControllers.swift
// SwiftElmButtonSample
//
// Created by Yoshikuni Kato on 2018/12/03.
//
import Foundation
indirect enum ViewController<Message> {
case _viewController(View<Message>)
}
| 16.461538 | 44 | 0.738318 |
f5a746dba6876b5e164ffc72934db8165b464eb9 | 1,064 | import XCTest
@testable import Schedule
final class ExtensionsTests: XCTestCase {
func testClampedToInt() {
let a: Double = 0.1
XCTAssertEqual(a.clampedToInt(), 0)
}
func testClampedAdding() {
let a: Int = 1
let b: Int = .max
XCTAssertEqual(a.clampedAdding(b), Int.max)
}
func testClampedSubtracting() {
let a: Int = .min
let b: Int = 1
XCTAssertEqual(a.clampedSubtracting(b), Int.min)
}
func testZeroClock() {
let z = Date().zeroToday()
let components = z.dateComponents
guard let h = components.hour, let m = components.minute, let s = components.second else {
XCTFail()
return
}
XCTAssertEqual(h, 0)
XCTAssertEqual(m, 0)
XCTAssertEqual(s, 0)
}
static var allTests = [
("testClampedToInt", testClampedToInt),
("testClampedAdding", testClampedAdding),
("testClampedSubtracting", testClampedSubtracting),
("testZeroClock", testZeroClock)
]
}
| 25.333333 | 98 | 0.592105 |
14057ab95d98321cd435448034ec88acf302be75 | 620 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
func j<s>() -> (s, s -> s) -> s {
d h d.n = {
}
{
s) {
s }
}
t u) {
}
n j {
func d((q, j))(m: (q, d)) {
{
}
}
.= l>(j: k<p>) {
}
}
func j() r> {
}
func m<d>() -> [j{
enum d {
case
| 20 | 79 | 0.575806 |
200ec0b42dce9dc5bb32755b0b3eccc3507cc72d | 3,661 | //
// Created by Mengyu Li on 2020/3/16.
// Copyright (c) 2020 Mengyu Li. All rights reserved.
//
@_implementationOnly import CMarauders
import Foundation
class _MachPortInfo {
let port: mach_port_name_t
let type: mach_port_type_t
let object: natural_t
let objectType: UInt32
// let members: [mach_port_name_t]
private(set) var connect = [String]()
// public init(port: mach_port_name_t, type: mach_port_type_t, object: natural_t, objectType: UInt32, members: [mach_port_name_t]) {
public init(port: mach_port_name_t, type: mach_port_type_t, object: natural_t, objectType: UInt32) {
self.port = port
self.type = type
self.object = object
self.objectType = objectType
// self.members = members
}
public func add(connect: String) {
self.connect.append(connect)
}
}
public struct MachPortInfo: Codable {
public let port: String
public let type: String
// public let members: [String]
let object: String
public let connect: [String]
init(info: _MachPortInfo) {
port = "0x\(String(info.port, radix: 16))"
type = info.objectType.portType
// self.members = info.members.map { name_t -> String in "0x\(String(name_t, radix: 16))" }
object = "0x\(String(info.object, radix: 16))"
connect = info.connect
}
}
private extension UInt32 {
var portType: String {
switch Int32(self) {
case IKOT_NONE: return "NONE"
case IKOT_THREAD: return "THREAD"
case IKOT_TASK: return "TASK"
case IKOT_HOST: return "HOST"
case IKOT_HOST_PRIV: return "HOST_PRIV"
case IKOT_PROCESSOR: return "PROCESSOR"
case IKOT_PSET: return "PSET"
case IKOT_PSET_NAME: return "PSET_NAME"
case IKOT_TIMER: return "TIMER"
case IKOT_PAGING_REQUEST: return "PAGING_REQUEST"
case IKOT_MIG: return "MIG"
case IKOT_MEMORY_OBJECT: return "MEMORY_OBJECT"
case IKOT_XMM_PAGER: return "XMM_PAGER"
case IKOT_XMM_KERNEL: return "XMM_KERNEL"
case IKOT_XMM_REPLY: return "XMM_REPLY"
case IKOT_UND_REPLY: return "UND_REPLY"
case IKOT_HOST_NOTIFY: return "HOST_NOTIFY"
case IKOT_HOST_SECURITY: return "HOST_SECURITY"
case IKOT_LEDGER: return "LEDGER"
case IKOT_MASTER_DEVICE: return "MASTER_DEVICE"
case IKOT_TASK_NAME: return "TASK_NAME"
case IKOT_SUBSYSTEM: return "SUBSYSTEM"
case IKOT_IO_DONE_QUEUE: return "IO_DONE_QUEUE"
case IKOT_SEMAPHORE: return "SEMAPHORE"
case IKOT_LOCK_SET: return "LOCK_SET"
case IKOT_CLOCK: return "CLOCK"
case IKOT_CLOCK_CTRL: return "CLOCK_CTRL"
case IKOT_IOKIT_IDENT: return "IOKIT_IDENT"
case IKOT_NAMED_ENTRY: return "NAMED_ENTRY"
case IKOT_IOKIT_CONNECT: return "IOKIT_CONNECT"
case IKOT_IOKIT_OBJECT: return "IOKIT_OBJECT"
case IKOT_UPL: return "UPL"
case IKOT_MEM_OBJ_CONTROL: return "MEM_OBJ_CONTROL"
case IKOT_AU_SESSIONPORT: return "AU_SESSIONPORT"
case IKOT_FILEPORT: return "FILEPORT"
case IKOT_LABELH: return "LABELH"
case IKOT_TASK_RESUME: return "TASK_RESUME"
case IKOT_VOUCHER: return "VOUCHER"
case IKOT_VOUCHER_ATTR_CONTROL: return "VOUCHER_ATTR_CONTROL"
case IKOT_WORK_INTERVAL: return "WORK_INTERVAL"
case IKOT_UX_HANDLER: return "UX_HANDLER"
case IKOT_UEXT_OBJECT: return "UEXT_OBJECT"
case IKOT_ARCADE_REG: return "ARCADE_REG"
case IKOT_UNKNOWN: return "UNKNOWN"
default: return "UNKNOWN"
}
}
}
| 37.357143 | 139 | 0.668943 |
46d07ef760668575ab6bc8112726c0159db88936 | 3,633 | //
// JournalRoutes.swift
// Application
//
// Created by Angus yeung on 7/16/18.
//
import Foundation
import KituraStencil
import Kitura
func initializeJournalRoutes(app: App, journal: JournalController) {
let mainPage = "/journal/all"
let title = "My Journal"
let author = "Angus"
struct JournalContext : Encodable {
let title: String
let author: String
let count: String
let entries: [Entry]
}
app.router.get("/journal/all") { _, response, _ in
let total = journal.total()
let entries : [Entry] = journal.readAll()
let count = "\(total)"
let context = JournalContext(title: title, author: author, count: count, entries: entries)
do {
try response.render("main", with: context)
} catch let error {
response.send(error.localizedDescription)
}
}
app.router.get("/journal/create") { request, response, next in
response.headers["Content-Type"] = "text/html; charset=utf-8"
try response.render("new", context: ["title": title, "author": author])
}
app.router.post("/journal/new") { request, response, next in
guard let entry = try? request.read(as: Entry.self)
else {
return try response.status(.unprocessableEntity).end()
}
let newID = UUID().uuidString
if let result = journal.create(Entry(id: newID,
title: entry.title,
content: entry.content)) {
print("Created: \(result)")
try response.redirect(mainPage)
}
}
app.router.get("/journal/get/:index?") { request, response, next in
guard let index = request.parameters["index"] else {
return try response.status(.badRequest).send("Missing entry index").end()
}
guard let idx = Int(index) else {
return try response.status(.badRequest).send("Invalid entry index").end()
}
guard let entry = journal.read(index: idx) else {
return try response.status(.unprocessableEntity).end()
}
try response.render("entry", context: ["title": title, "author": author, "index": idx, "entry": entry])
}
app.router.post("/journal/edit/:index?") { request, response, next in
guard let index = request.parameters["index"] else {
return try response.status(.badRequest).send("Missing entry index").end()
}
guard let idx = Int(index) else {
return try response.status(.badRequest).send("Invalid entry index").end()
}
if let entry = try? request.read(as: Entry.self) {
if let result = journal.update(index: idx, entry: entry) {
print("Updated: Entry[\(index)]: \(result)")
try response.redirect(mainPage)
}
}
try response.status(.unprocessableEntity).end()
}
app.router.get("/journal/remove/:index?") { request, response, next in
guard let index = request.parameters["index"] else {
return try response.status(.badRequest).send("Missing entry index").end()
}
guard let idx = Int(index) else {
return try response.status(.badRequest).send("Invalid entry index").end()
}
if let entry = journal.delete(index: idx) {
print("Deleted: Entry[\(index)]: \(entry)")
try response.redirect(mainPage)
}
try response.status(.unprocessableEntity).end()
}
}
| 34.932692 | 111 | 0.571979 |
14b68aa2e3231cba2ebf5f5f3c70204a3c5a4758 | 321 | //
// Encodable+URLQueryItems.swift
// CodableExtensions
//
// Created by Brian Strobach on 6/5/19.
//
import Foundation
public extension Encodable {
func encodeAsURLQueryItems(using encoder: URLQueryItemEncoder = URLQueryItemEncoder()) throws -> [URLQueryItem] {
return try encoder.encode(self)
}
}
| 21.4 | 117 | 0.719626 |
38406d32cbd1a2454c669bffb36f5e4341cee34c | 568 | //
// Colors.swift
// WeTrade
//
// Created by Felipe Joglar on 7/4/22.
//
import SwiftUI
struct Colors {
// THEME
let primary = Color("colorPrimary")
let background = Color("colorBackground")
let surface = Color("colorSurface")
let onPrimary = Color("colorOnPrimary")
let onBackground = Color("colorOnBackground")
let onSurface = Color("colorOnSurface")
// CUSTOM
let custom1 = Color("colorCustom1")
let custom2 = Color("colorCustom2")
// COMPONENTS
let textFieldBorder = Color("colorTextFieldBorder")
}
| 21.846154 | 55 | 0.658451 |
11a14d0775ce060905b727c14876b4ececcdac8a | 3,777 | //
// CoursesNavigationController.swift
// CourseGrab
//
// Created by Reade Plunkett on 1/26/20.
// Copyright © 2020 Cornell AppDev. All rights reserved.
//
import UIKit
// MARK: - InteractivePopRecognizer
class InteractivePopRecognizer: NSObject, UIGestureRecognizerDelegate {
// Source: https://stackoverflow.com/a/41248703/5078779
private var navigationController: UINavigationController
init(navigationController: UINavigationController) {
self.navigationController = navigationController
}
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
navigationController.viewControllers.count > 1
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer,
shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
true
}
}
// MARK: - BigHitNavigationBar
private class BigHitNavigationBar: UINavigationBar {
private let tapOffset: CGFloat = 40
weak var navigationController: UINavigationController?
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
if bounds.insetBy(dx: 0, dy: -tapOffset).contains(point), let item = navigationController?.topViewController?.navigationItem {
var candidateViews = [
item.backBarButtonItem?.customView,
item.leftBarButtonItem?.customView,
item.rightBarButtonItem?.customView
].compactMap { $0 }
item.leftBarButtonItems?
.compactMap { $0.customView }
.forEach { candidateViews.append($0) }
item.rightBarButtonItems?
.compactMap { $0.customView }
.forEach { candidateViews.append($0) }
for view in candidateViews {
let viewFrame = view.convert(view.frame, to: self).insetBy(dx: -tapOffset, dy: -tapOffset)
if viewFrame.contains(point) {
return view
}
}
}
return super.hitTest(point, with: event)
}
}
// MARK: - MainNavigationController
class MainNavigationController: UINavigationController {
override init(rootViewController: UIViewController) {
super.init(navigationBarClass: BigHitNavigationBar.self, toolbarClass: nil)
(navigationBar as? BigHitNavigationBar)?.navigationController = self
setViewControllers([rootViewController], animated: false)
APNNotificationCenter.default.addListener { [weak self] payload in
guard let self = self else { return }
let vc = NotificationModalViewController(payload: payload)
self.pushViewController(vc, animated: true)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
navigationBar.barTintColor = .black
navigationBar.tintColor = .white
navigationBar.titleTextAttributes = [.foregroundColor: UIColor.white]
navigationBar.largeTitleTextAttributes = [.foregroundColor: UIColor.white]
navigationBar.isTranslucent = false
navigationBar.barStyle = .black
navigationBar.titleTextAttributes = [NSAttributedString.Key.font: UIFont._20Semibold]
// Add insets to the back button so it perfectly aligns with the HomeTableViewController back button.
navigationBar.backIndicatorImage = UIImage.backIcon?.with(insets: UIEdgeInsets(top: 0, left: 8, bottom: 2.5, right: 0))
navigationBar.backIndicatorTransitionMaskImage = .backIcon
}
override var preferredStatusBarStyle: UIStatusBarStyle {
.lightContent
}
}
| 34.336364 | 134 | 0.675933 |
6147c8e4a530b826ad1f8a78a53a79856e1cff6f | 97 | import ParzyCore
let parzy = Parzy()
do {
try parzy.run()
} catch {
print("erkasdlksan;d")
}
| 9.7 | 23 | 0.649485 |
769d4a28789e4f71039ac85744e76014a2381d4b | 15,687 | //
// Popover.swift
// Popover
//
// Created by corin8823 on 8/16/15.
// Copyright (c) 2015 corin8823. All rights reserved.
//
import Foundation
import UIKit
public enum iGrant_PopoverOption {
case arrowSize(CGSize)
case animationIn(TimeInterval)
case animationOut(TimeInterval)
case cornerRadius(CGFloat)
case sideEdge(CGFloat)
case blackOverlayColor(UIColor)
case overlayBlur(UIBlurEffect.Style)
case type(PopoverType)
case color(UIColor)
case dismissOnBlackOverlayTap(Bool)
case showBlackOverlay(Bool)
case springDamping(CGFloat)
case initialSpringVelocity(CGFloat)
}
@objc public enum PopoverType: Int {
case up
case down
case auto
}
open class iGrant_Popover: UIView {
// custom property
open var arrowSize: CGSize = CGSize(width: 16.0, height: 10.0)
open var animationIn: TimeInterval = 0.6
open var animationOut: TimeInterval = 0.3
open var popUpCornerRadius: CGFloat = 6.0
open var sideEdge: CGFloat = 20.0
open var popoverType: PopoverType = .down
open var blackOverlayColor: UIColor = UIColor(white: 0.0, alpha: 0.2)
open var overlayBlur: UIBlurEffect?
open var popoverColor: UIColor = UIColor.white
open var dismissOnBlackOverlayTap: Bool = true
open var showBlackOverlay: Bool = true
open var highlightFromView: Bool = false
open var highlightCornerRadius: CGFloat = 0
open var springDamping: CGFloat = 0.7
open var initialSpringVelocity: CGFloat = 3
// custom closure
open var willShowHandler: (() -> ())?
open var willDismissHandler: (() -> ())?
open var didShowHandler: (() -> ())?
open var didDismissHandler: (() -> ())?
public fileprivate(set) var blackOverlay: UIControl = UIControl()
fileprivate var containerView: UIView!
fileprivate var contentView: UIView!
fileprivate var contentViewFrame: CGRect!
fileprivate var arrowShowPoint: CGPoint!
public init() {
super.init(frame: .zero)
self.backgroundColor = .clear
self.accessibilityViewIsModal = true
}
public init(showHandler: (() -> ())?, dismissHandler: (() -> ())?) {
super.init(frame: .zero)
self.backgroundColor = .clear
self.didShowHandler = showHandler
self.didDismissHandler = dismissHandler
self.accessibilityViewIsModal = true
}
public init(options: [iGrant_PopoverOption]?, showHandler: (() -> ())? = nil, dismissHandler: (() -> ())? = nil) {
super.init(frame: .zero)
self.backgroundColor = .clear
self.setOptions(options)
self.didShowHandler = showHandler
self.didDismissHandler = dismissHandler
self.accessibilityViewIsModal = true
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override open func layoutSubviews() {
super.layoutSubviews()
self.contentView.frame = self.bounds
}
open func showAsDialog(_ contentView: UIView) {
guard let rootView = UIApplication.shared.keyWindow else {
return
}
self.showAsDialog(contentView, inView: rootView)
}
open func showAsDialog(_ contentView: UIView, inView: UIView) {
self.arrowSize = .zero
let point = CGPoint(x: inView.center.x,
y: inView.center.y - contentView.frame.height / 2)
self.show(contentView, point: point, inView: inView)
}
open func show(_ contentView: UIView, fromView: UIView) {
guard let rootView = UIApplication.shared.keyWindow else {
return
}
self.show(contentView, fromView: fromView, inView: rootView)
}
open func show(_ contentView: UIView, fromView: UIView, inView: UIView) {
let point: CGPoint
if self.popoverType == .auto {
if let point = fromView.superview?.convert(fromView.frame.origin, to: nil),
point.y + fromView.frame.height + self.arrowSize.height + contentView.frame.height > inView.frame.height {
self.popoverType = .up
} else {
self.popoverType = .down
}
}
switch self.popoverType {
case .up:
point = inView.convert(
CGPoint(
x: fromView.frame.origin.x + (fromView.frame.size.width / 2),
y: fromView.frame.origin.y
), from: fromView.superview)
case .down, .auto:
point = inView.convert(
CGPoint(
x: fromView.frame.origin.x + (fromView.frame.size.width / 2),
y: fromView.frame.origin.y + fromView.frame.size.height
), from: fromView.superview)
}
if self.highlightFromView {
self.createHighlightLayer(fromView: fromView, inView: inView)
}
self.show(contentView, point: point, inView: inView)
}
open func show(_ contentView: UIView, point: CGPoint) {
guard let rootView = UIApplication.shared.keyWindow else {
return
}
self.show(contentView, point: point, inView: rootView)
}
open func show(_ contentView: UIView, point: CGPoint, inView: UIView) {
if self.dismissOnBlackOverlayTap || self.showBlackOverlay {
self.blackOverlay.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.blackOverlay.frame = inView.bounds
inView.addSubview(self.blackOverlay)
if showBlackOverlay {
if let overlayBlur = self.overlayBlur {
let effectView = UIVisualEffectView(effect: overlayBlur)
effectView.frame = self.blackOverlay.bounds
effectView.isUserInteractionEnabled = false
self.blackOverlay.addSubview(effectView)
} else {
if !self.highlightFromView {
self.blackOverlay.backgroundColor = self.blackOverlayColor
}
self.blackOverlay.alpha = 0
}
}
if self.dismissOnBlackOverlayTap {
self.blackOverlay.addTarget(self, action: #selector(iGrant_Popover.dismiss), for: .touchUpInside)
}
}
self.containerView = inView
self.contentView = contentView
self.contentView.backgroundColor = UIColor.clear
self.contentView.layer.cornerRadius = self.cornerRadius
self.contentView.layer.masksToBounds = true
self.arrowShowPoint = point
self.show()
}
open override func accessibilityPerformEscape() -> Bool {
self.dismiss()
return true
}
@objc open func dismiss() {
if self.superview != nil {
self.willDismissHandler?()
UIView.animate(withDuration: self.animationOut, delay: 0,
options: UIView.AnimationOptions(),
animations: {
self.transform = CGAffineTransform(scaleX: 0.0001, y: 0.0001)
self.blackOverlay.alpha = 0
}){ _ in
self.contentView.removeFromSuperview()
self.blackOverlay.removeFromSuperview()
self.removeFromSuperview()
self.transform = CGAffineTransform.identity
self.didDismissHandler?()
}
}
}
override open func draw(_ rect: CGRect) {
super.draw(rect)
let arrow = UIBezierPath()
let color = self.popoverColor
let arrowPoint = self.containerView.convert(self.arrowShowPoint, to: self)
switch self.popoverType {
case .up:
arrow.move(to: CGPoint(x: arrowPoint.x, y: self.bounds.height))
arrow.addLine(
to: CGPoint(
x: arrowPoint.x - self.arrowSize.width * 0.5,
y: self.isCornerLeftArrow ? self.arrowSize.height : self.bounds.height - self.arrowSize.height
)
)
arrow.addLine(to: CGPoint(x: self.cornerRadius, y: self.bounds.height - self.arrowSize.height))
arrow.addArc(
withCenter: CGPoint(
x: self.cornerRadius,
y: self.bounds.height - self.arrowSize.height - self.cornerRadius
),
radius: self.cornerRadius,
startAngle: self.radians(90),
endAngle: self.radians(180),
clockwise: true)
arrow.addLine(to: CGPoint(x: 0, y: self.cornerRadius))
arrow.addArc(
withCenter: CGPoint(
x: self.cornerRadius,
y: self.cornerRadius
),
radius: self.cornerRadius,
startAngle: self.radians(180),
endAngle: self.radians(270),
clockwise: true)
arrow.addLine(to: CGPoint(x: self.bounds.width - self.cornerRadius, y: 0))
arrow.addArc(
withCenter: CGPoint(
x: self.bounds.width - self.cornerRadius,
y: self.cornerRadius
),
radius: self.cornerRadius,
startAngle: self.radians(270),
endAngle: self.radians(0),
clockwise: true)
arrow.addLine(to: CGPoint(x: self.bounds.width, y: self.bounds.height - self.arrowSize.height - self.cornerRadius))
arrow.addArc(
withCenter: CGPoint(
x: self.bounds.width - self.cornerRadius,
y: self.bounds.height - self.arrowSize.height - self.cornerRadius
),
radius: self.cornerRadius,
startAngle: self.radians(0),
endAngle: self.radians(90),
clockwise: true)
arrow.addLine(
to: CGPoint(
x: arrowPoint.x + self.arrowSize.width * 0.5,
y: self.isCornerRightArrow ? self.arrowSize.height : self.bounds.height - self.arrowSize.height
)
)
case .down, .auto:
arrow.move(to: CGPoint(x: arrowPoint.x, y: 0))
arrow.addLine(
to: CGPoint(
x: arrowPoint.x + self.arrowSize.width * 0.5,
y: self.isCornerRightArrow ? self.arrowSize.height + self.bounds.height : self.arrowSize.height
)
)
arrow.addLine(to: CGPoint(x: self.bounds.width - self.cornerRadius, y: self.arrowSize.height))
arrow.addArc(
withCenter: CGPoint(
x: self.bounds.width - self.cornerRadius,
y: self.arrowSize.height + self.cornerRadius
),
radius: self.cornerRadius,
startAngle: self.radians(270.0),
endAngle: self.radians(0),
clockwise: true)
arrow.addLine(to: CGPoint(x: self.bounds.width, y: self.bounds.height - self.cornerRadius))
arrow.addArc(
withCenter: CGPoint(
x: self.bounds.width - self.cornerRadius,
y: self.bounds.height - self.cornerRadius
),
radius: self.cornerRadius,
startAngle: self.radians(0),
endAngle: self.radians(90),
clockwise: true)
arrow.addLine(to: CGPoint(x: 0, y: self.bounds.height))
arrow.addArc(
withCenter: CGPoint(
x: self.cornerRadius,
y: self.bounds.height - self.cornerRadius
),
radius: self.cornerRadius,
startAngle: self.radians(90),
endAngle: self.radians(180),
clockwise: true)
arrow.addLine(to: CGPoint(x: 0, y: self.arrowSize.height + self.cornerRadius))
arrow.addArc(
withCenter: CGPoint(
x: self.cornerRadius,
y: self.arrowSize.height + self.cornerRadius
),
radius: self.cornerRadius,
startAngle: self.radians(180),
endAngle: self.radians(270),
clockwise: true)
arrow.addLine(to: CGPoint(
x: arrowPoint.x - self.arrowSize.width * 0.5,
y: self.isCornerLeftArrow ? self.arrowSize.height + self.bounds.height : self.arrowSize.height))
}
color.setFill()
arrow.fill()
}
}
private extension iGrant_Popover {
func setOptions(_ options: [iGrant_PopoverOption]?){
if let options = options {
for option in options {
switch option {
case let .arrowSize(value):
self.arrowSize = value
case let .animationIn(value):
self.animationIn = value
case let .animationOut(value):
self.animationOut = value
case let .cornerRadius(value):
self.cornerRadius = value
case let .sideEdge(value):
self.sideEdge = value
case let .blackOverlayColor(value):
self.blackOverlayColor = value
case let .overlayBlur(style):
self.overlayBlur = UIBlurEffect(style: style)
case let .type(value):
self.popoverType = value
case let .color(value):
self.popoverColor = value
case let .dismissOnBlackOverlayTap(value):
self.dismissOnBlackOverlayTap = value
case let .showBlackOverlay(value):
self.showBlackOverlay = value
case let .springDamping(value):
self.springDamping = value
case let .initialSpringVelocity(value):
self.initialSpringVelocity = value
}
}
}
}
func create() {
var frame = self.contentView.frame
frame.origin.x = self.arrowShowPoint.x - frame.size.width * 0.5
var sideEdge: CGFloat = 0.0
if frame.size.width < self.containerView.frame.size.width {
sideEdge = self.sideEdge
}
let outerSideEdge = frame.maxX - self.containerView.bounds.size.width
if outerSideEdge > 0 {
frame.origin.x -= (outerSideEdge + sideEdge)
} else {
if frame.minX < 0 {
frame.origin.x += abs(frame.minX) + sideEdge
}
}
self.frame = frame
let arrowPoint = self.containerView.convert(self.arrowShowPoint, to: self)
var anchorPoint: CGPoint
switch self.popoverType {
case .up:
frame.origin.y = self.arrowShowPoint.y - frame.height - self.arrowSize.height
anchorPoint = CGPoint(x: arrowPoint.x / frame.size.width, y: 1)
case .down, .auto:
frame.origin.y = self.arrowShowPoint.y
anchorPoint = CGPoint(x: arrowPoint.x / frame.size.width, y: 0)
}
if self.arrowSize == .zero {
anchorPoint = CGPoint(x: 0.5, y: 0.5)
}
let lastAnchor = self.layer.anchorPoint
self.layer.anchorPoint = anchorPoint
let x = self.layer.position.x + (anchorPoint.x - lastAnchor.x) * self.layer.bounds.size.width
let y = self.layer.position.y + (anchorPoint.y - lastAnchor.y) * self.layer.bounds.size.height
self.layer.position = CGPoint(x: x, y: y)
frame.size.height += self.arrowSize.height
self.frame = frame
}
func createHighlightLayer(fromView: UIView, inView: UIView) {
let path = UIBezierPath(rect: inView.bounds)
let highlightRect = inView.convert(fromView.frame, from: fromView.superview)
let highlightPath = UIBezierPath(roundedRect: highlightRect, cornerRadius: self.highlightCornerRadius)
path.append(highlightPath)
path.usesEvenOddFillRule = true
let fillLayer = CAShapeLayer()
fillLayer.path = path.cgPath
fillLayer.fillRule = CAShapeLayerFillRule.evenOdd
fillLayer.fillColor = self.blackOverlayColor.cgColor
self.blackOverlay.layer.addSublayer(fillLayer)
}
func show() {
self.setNeedsDisplay()
switch self.popoverType {
case .up:
self.contentView.frame.origin.y = 0.0
case .down, .auto:
self.contentView.frame.origin.y = self.arrowSize.height
}
self.addSubview(self.contentView)
self.containerView.addSubview(self)
self.create()
self.transform = CGAffineTransform(scaleX: 0.0, y: 0.0)
self.willShowHandler?()
UIView.animate(
withDuration: self.animationIn,
delay: 0,
usingSpringWithDamping: self.springDamping,
initialSpringVelocity: self.initialSpringVelocity,
options: UIView.AnimationOptions(),
animations: {
self.transform = CGAffineTransform.identity
}){ _ in
self.didShowHandler?()
}
UIView.animate(
withDuration: self.animationIn / 3,
delay: 0,
options: .curveLinear,
animations: {
self.blackOverlay.alpha = 1
}, completion: nil)
}
var isCornerLeftArrow: Bool {
return self.arrowShowPoint.x == self.frame.origin.x
}
var isCornerRightArrow: Bool {
return self.arrowShowPoint.x == self.frame.origin.x + self.bounds.width
}
func radians(_ degrees: CGFloat) -> CGFloat {
return CGFloat.pi * degrees / 180
}
}
| 32.211499 | 121 | 0.65073 |
87f1b1868d73f18c8bec6937861c037000e5a263 | 7,153 | //___FILEHEADER___
import SnapKit
import UIKit
protocol ProfilePhotoPickerActionSheetDelegate: class {
func didTapTakeAPhoto()
func didTapSelectPhoto()
}
protocol EventPhotoPickerActionSheetDelegate: class {
func didTapTakeAPhoto()
func didTapSelectPhoto()
func didTapDeletePhoto()
}
final class AlertPresenter {
weak var profilePickerDelegate: ProfilePhotoPickerActionSheetDelegate?
// MARK: - Error alert
static func showErrorAlert(at vc: UIViewController, errorMessgage: String) {
DispatchQueue.main.async {
let alert = UIAlertController(title: Localizable.error(), message: errorMessgage, preferredStyle: .alert)
let okAction = UIAlertAction(title: Localizable.ok(), style: .default, handler: { _ in
let error = AuthError.serverError(failureReason: errorMessgage)
AuthError.handleError(error: error)
})
alert.addAction(okAction)
vc.present(alert, animated: true, completion: nil)
}
}
// MARK: - Error alert with closure
static func showErrorAlertWithHandler(at vc: UIViewController, errorMessgage: String, handler: ((UIAlertAction) -> Void)? = nil) {
DispatchQueue.main.async {
let alert = UIAlertController(title: Localizable.error(), message: errorMessgage, preferredStyle: .alert)
let okAction = UIAlertAction(title: Localizable.ok(), style: .default, handler: handler)
alert.addAction(okAction)
vc.present(alert, animated: true, completion: nil)
}
}
// MARK: - Permission denied alert
static func showPermissionDeniedAlert(at vc: UIViewController, errorMessage: String, cancelClosure: @escaping VoidClosure) {
DispatchQueue.main.async {
let alert = UIAlertController(title: Localizable.error(), message: errorMessage, preferredStyle: .alert)
let cancelAction = UIAlertAction(title: Localizable.cancel(), style: .cancel, handler: { _ in
cancelClosure()
})
let openSettignsAction = UIAlertAction(title: Localizable.appSettings(), style: .default) { _ in
guard let settingsURL = URL(string: UIApplication.openSettingsURLString) else { return }
UIApplication.shared.open(settingsURL)
}
alert.addAction(cancelAction)
alert.addAction(openSettignsAction)
vc.present(alert, animated: true, completion: nil)
}
}
// MARK: - Success alert
static func showSuccessAlert(at vc: UIViewController, message: String, handler: ((UIAlertAction) -> Void)? = nil) {
DispatchQueue.main.async {
let alert = UIAlertController(title: Localizable.success(), message: message, preferredStyle: .alert)
let okAction = UIAlertAction(title: Localizable.ok(), style: .default, handler: handler)
alert.addAction(okAction)
vc.present(alert, animated: true, completion: nil)
}
}
// MARK: - Log out alert
static func showLogOutAlert(at vc: UIViewController,
logOutClosure: @escaping VoidClosure) {
DispatchQueue.main.async {
let title = Localizable.appName()
let message = Localizable.myProfileLogOutText()
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let logOutAction = UIAlertAction(title: Localizable.myProfileLogOutTitle(), style: .default) { _ in
logOutClosure()
}
let cancelAction = UIAlertAction(title: Localizable.cancel(), style: .default) { _ in
alert.dismiss(animated: true, completion: nil)
}
alert.addAction(logOutAction)
alert.addAction(cancelAction)
alert.preferredAction = logOutAction
vc.present(alert, animated: true, completion: nil)
}
}
// MARK: - Todo alert
static func showTodoAlert(at vc: UIViewController, messgage: String, handler: ((UIAlertAction) -> Void)? = nil) {
DispatchQueue.main.async {
let alert = UIAlertController(title: Localizable.todo(), message: messgage, preferredStyle: .alert)
let okAction = UIAlertAction(title: Localizable.ok(), style: .default, handler: handler)
alert.addAction(okAction)
vc.present(alert, animated: true, completion: nil)
}
}
// MARK: - Image picker alert
func showImagePickerAlert(at vc: UIViewController, title: String) {
DispatchQueue.main.async {
let alert = UIAlertController(title: title, message: nil, preferredStyle: .actionSheet)
let takeAPhotoAction = UIAlertAction(title: Localizable.imageAlertTakePhoto(), style: .default) { [unowned self] _ in
self.profilePickerDelegate?.didTapTakeAPhoto()
}
let selectImageAction = UIAlertAction(title: Localizable.imageAlertSelectPhoto(), style: .default) { [unowned self] _ in
self.profilePickerDelegate?.didTapSelectPhoto()
}
let cancelAction = UIAlertAction(title: Localizable.cancel(), style: .cancel) { _ in
alert.dismiss(animated: true, completion: nil)
}
let actions = [takeAPhotoAction, selectImageAction, cancelAction]
actions.forEach { alert.addAction($0) }
vc.present(alert, animated: true, completion: nil)
}
}
// MARK: - Date picker alert
static func showDatePickerAlert(at vc: UIViewController, title: String, doneClosure: @escaping DateClosure) {
DispatchQueue.main.async {
let myDatePicker: UIDatePicker = UIDatePicker()
myDatePicker.datePickerMode = .date
myDatePicker.timeZone = NSTimeZone.local
let currentDate: Date = Date()
myDatePicker.minimumDate = currentDate
myDatePicker.maximumDate = currentDate.addingTimeInterval(AppConstants.eventMaxDuration)
myDatePicker.frame = CGRect(x: 10, y: 30, width: 250, height: 250)
let alertController: UIAlertController = UIAlertController(title: title, message: "\n\n\n\n\n\n\n\n\n\n\n\n\n",
preferredStyle: .alert)
alertController.view.addSubview(myDatePicker)
let selectAction: UIAlertAction = UIAlertAction(title: Localizable.ok(), style: .default, handler: { _ in
doneClosure(myDatePicker.date)
})
let cancelAction: UIAlertAction = UIAlertAction(title: Localizable.cancel(), style: .cancel, handler: nil)
alertController.addAction(selectAction)
alertController.addAction(cancelAction)
vc.present(alertController, animated: true, completion: nil)
}
}
}
| 43.883436 | 134 | 0.621418 |
ddcb37974313d6ac875eb8c6f5852e625f58e456 | 2,024 | // Copyright © 2021 Lunabee Studio
//
// 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.
//
// BottomSheetConstant.swift
// LBBottomSheet
//
// Created by Lunabee Studio / Date - 12/10/2021 - for the LBBottomSheet Swift Package.
//
import CoreGraphics
/// Bottom sheet constants.
public enum BottomSheetConstant {
/// Bottom sheet animation constants.
public enum Animation {
/// Bottom sheet animation elasticity functions.
public enum Elasticity {
/// Bottom sheet logarithmic animation function.
///
/// Here is the implementation of this function:
/// ```swift
/// let baseFunction: (_ x: CGFloat) -> CGFloat = { (2.0 * log($0 + 3.0) / log(2.0)) }
/// return baseFunction(x) - baseFunction(0.0)
/// ```
///
/// - Parameters:
/// - x: The abscissa: The bottom sheet will give the height slice that has to be computed to create the elacticity effect.
/// - Returns: The ordonate: The height value to be applied to be used by the bottom sheet to calculate its full height.
public static let logarithmic: (_ x: CGFloat) -> CGFloat = { x -> CGFloat in
let baseFunction: (_ x: CGFloat) -> CGFloat = { (2.0 * log($0 + 3.0) / log(2.0)) }
return baseFunction(x) - baseFunction(0.0)
}
}
}
internal static let preferredHeightVariableName: String = "preferredHeightInBottomSheet"
}
| 41.306122 | 139 | 0.631423 |
f9e14a9cb93da8d7a55afc299734e7748b7f61f1 | 1,193 | // Check JIT mode
// RUN: %target-jit-run %s | FileCheck %s
// REQUIRES: swift_interpreter
// REQUIRES: objc_interop
import Foundation
@objc protocol Fungible: Runcible {
func funge()
}
@objc protocol Runcible {
func runce()
}
class C: Fungible {
@objc func runce() {}
@objc func funge() {}
}
class D {}
extension D: Fungible {
@objc func runce() {}
@objc func funge() {}
}
extension NSString: Fungible {
func runce() {}
func funge() {}
}
func check(x: AnyObject) {
print("\(x is Fungible) \(x is Runcible)")
}
check(NSString()) // CHECK: true true
check(C()) // CHECK: true true
check(D()) // CHECK: true true
// Make sure partial application of methods with @autoreleased
// return values works
var count = 0
class Juice : NSObject {
override init() {
count += 1
}
deinit {
count -= 1
}
}
@objc protocol Fruit {
optional var juice: Juice { get }
}
class Durian : NSObject, Fruit {
init(juice: Juice) {
self.juice = juice
}
var juice: Juice
}
func consume(fruit: Fruit) {
_ = fruit.juice
}
autoreleasepool {
let tasty = Durian(juice: Juice())
print(count) // CHECK: 1
consume(tasty)
}
do {
print(count) // CHECK: 0
}
| 14.728395 | 62 | 0.633697 |
dd15fe642c7f5e46485a3ad702148e65ad641af9 | 146 | #if !canImport(ObjectiveC)
public func allTests() -> [XCTestCaseEntry] {
return [
testCase(SwiftyMetalTests.allTests),
]
}
#endif
| 18.25 | 45 | 0.664384 |
dbb19145f606492e71a45c9efc7b95ba41021473 | 371 | //
// Theme.swift
// OEAContentStateView
//
// Created by Omer Emre Aslan on 11.02.2018.
// Copyright © 2018 Omer Emre Aslan. All rights reserved.
//
public protocol Theme {
var backgroundColor: UIColor? { get }
var textColor: UIColor? { get }
}
class DefaultTheme : Theme {
var backgroundColor: UIColor? = .clear
var textColor: UIColor? = .black
}
| 20.611111 | 58 | 0.671159 |
f8b1ef90e51d87ef7651c934a55933fbc4833cb5 | 903 | //
// CalendarTests.swift
// CalendarTests
//
// Created by Carlos Butron on 07/12/14.
// Copyright (c) 2014 Carlos Butron. All rights reserved.
//
import UIKit
import XCTest
class CalendarTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
}
| 24.405405 | 111 | 0.614618 |
162f22b5017b86af02fa8e8f108f53055aa45398 | 557 | //
// FillingViewController.swift
// AutoLayoutConvenienceDemo
//
// Created by Andreas Verhoeven on 29/07/2021.
//
import UIKit
class FillingViewController: BaseTableViewController {
@IBOutlet var headerView: UIView!
var currentView = UIView()
func update(animated: Bool) {
currentView.removeFromSuperview()
headerView.directionalLayoutMargins = .all(16)
headerView.addSubview(currentView, filling: .layoutMargins)
}
override func viewDidLoad() {
super.viewDidLoad()
currentView.backgroundColor = .red
update(animated: false)
}
}
| 20.62963 | 61 | 0.75763 |
90e4a0b207c5ae0a1b04db5d079c6c28f10b683f | 1,989 | import XCTest
import JWT
class JWTEncodeTests: XCTestCase {
func testEncodingJWT() {
let payload = ["name": "Kyle"] as Payload
let jwt = JWT.encode(claims: payload, algorithm: .hs256("secret".data(using: .utf8)!))
let expected = [
// { "alg": "HS256", "typ": "JWT" }
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiS3lsZSJ9.zxm7xcp1eZtZhp4t-nlw09ATQnnFKIiSN83uG8u6cAg",
// { "typ": "JWT", "alg": "HS256" }
"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiS3lsZSJ9.4tCpoxfyfjbUyLjm9_zu-r52Vxn6bFq9kp6Rt9xMs4A",
]
XCTAssertTrue(expected.contains(jwt))
}
func testEncodingWithBuilder() {
let algorithm = Algorithm.hs256("secret".data(using: .utf8)!)
let jwt = JWT.encode(algorithm) { builder in
builder.issuer = "fuller.li"
}
XCTAssert(jwt == "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJmdWxsZXIubGkifQ.d7B7PAQcz1E6oNhrlxmHxHXHgg39_k7X7wWeahl8kSQ"
|| jwt == "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJmdWxsZXIubGkifQ.x5Fdll-kZBImOPtpT1fZH_8hDW01Ax3pbZx_EiljoLk")
}
func testEncodingClaimsWithHeaders() {
let algorithm = Algorithm.hs256("secret".data(using: .utf8)!)
let jwt = JWT.encode(claims: ClaimSet(), algorithm: algorithm, headers: ["kid": "x"])
XCTAssert(jwt == "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IngifQ.e30.ddEotxYYMMdat5HPgYFQnkHRdPXsxPG71ooyhIUoqGA"
|| jwt == "eyJraWQiOiJ4IiwiYWxnIjoiSFMyNTYiLCJ0eXAiOiJKV1QifQ.e30.5KqN7N5a7Cfbe2eKN41FJIfgMjcdSZ7Nt16xqlyOeMo"
|| jwt == "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiIsImtpZCI6IngifQ.e30.5t6a61tpSXFo5QBHYCnKAz2mTHrW9kaQ9n_b7e-jWw0"
|| jwt == "eyJhbGciOiJIUzI1NiIsImtpZCI6IngiLCJ0eXAiOiJKV1QifQ.e30.xiT6fWe5dWGeuq8zFb0je_14Maa_9mHbVPSyJhUIJ54"
|| jwt == "eyJ0eXAiOiJKV1QiLCJraWQiOiJ4IiwiYWxnIjoiSFMyNTYifQ.e30.DG5nmV2CVH6mV_iEm0xXZvL0DUJ22ek2xy6fNi_pGLc"
|| jwt == "eyJraWQiOiJ4IiwidHlwIjoiSldUIiwiYWxnIjoiSFMyNTYifQ.e30.h5ZvlqECBIvu9uocR5_5uF3wnhga8vTruvXpzaHpRdA")
}
}
| 46.255814 | 130 | 0.760181 |
725b747dc63ce70ea2bb0cce6a287a4f9d560faa | 1,870 | //
// MenuHeaderCell.swift
// Twitter
//
// Created by Deepthy on 10/5/17.
// Copyright © 2017 Deepthy. All rights reserved.
//
import UIKit
class MenuHeaderCell: UITableViewCell {
@IBOutlet weak var profileImageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var screenLabel: UILabel!
@IBOutlet weak var followingCountLabel: UILabel!
@IBOutlet weak var followerCountLabel: UILabel!
var loggedInuser: User! {
didSet {
if let profileImageUrl = loggedInuser?.profileImageUrl {
let largeImageUrl = profileImageUrl.replacingOccurrences(of: "normal", with: "200x200")
if let url = URL(string: largeImageUrl) {
profileImageView.setImageWith(url)
profileImageView.layer.cornerRadius = (profileImageView.frame.size.width)/2
profileImageView.clipsToBounds = true
}
}
if let name = loggedInuser.name {
nameLabel?.text = name
}
if let screenname = loggedInuser.screenname {
screenLabel?.text = "@\(screenname)"
}
if let following = loggedInuser.followingCount {
followingCountLabel.text = "\(following)"
}
if let follower = loggedInuser.followersCount {
followerCountLabel.text = "\(follower)"
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 27.5 | 103 | 0.558824 |
895d684f2263e85c6c36d9fd0c5d02a6ba87f9e5 | 1,196 | //——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// THIS FILE IS REGENERATED BY EASY BINDINGS, ONLY MODIFY IT WITHIN USER ZONES
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
import Cocoa
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
//--- START OF USER ZONE 1
//--- END OF USER ZONE 1
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
func transient_BoardTrack_actualTrackWidth (
_ self_mNet_netClassTrackWidth : Int?,
_ self_mUsesCustomTrackWidth : Bool,
_ self_mCustomTrackWidth : Int
) -> Int {
//--- START OF USER ZONE 2
if self_mUsesCustomTrackWidth {
return self_mCustomTrackWidth
}else if let w = self_mNet_netClassTrackWidth {
return w
}else{
return 0
}
//--- END OF USER ZONE 2
}
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
| 36.242424 | 120 | 0.316054 |
71cab975516ec1e3a6022def13f7587fcc5a5b59 | 2,140 | //
// AppDelegate.swift
// FoodTracker
//
// Created by Manoj Puli on 11/2/16.
// Copyright © 2016 Vineeth. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 45.531915 | 285 | 0.753738 |
48ee25556a0e8f21eb03e0c48dc47f6edb5f4419 | 6,087 | import SwiftUI
import Swinject
private extension Decimal {
func rounded(_ places: Int = 0) -> Decimal {
var inp = self
var res = Decimal()
NSDecimalRound(&res, &inp, places, .plain)
return res
}
}
extension Bolus {
final class StateModel: BaseStateModel<Provider> {
@Injected() var unlockmanager: UnlockManager!
@Injected() var apsManager: APSManager!
@Injected() var broadcaster: Broadcaster!
@Injected() var pumpHistotyStorage: PumpHistoryStorage!
@Published var amount: Decimal = 0
@Published var inslinRecommended: Decimal = 0
@Published var inslinRequired: Decimal = 0
@Published var waitForSuggestion: Bool = false
@Published var carbsAdded: Decimal = 0
@Published var carbsInsulinRequired: Decimal = 0
@Published var carbsInsulinRecommended: Decimal = 0
var waitForSuggestionInitial: Bool = false
override func subscribe() {
setupInsulinRequired()
broadcaster.register(SuggestionObserver.self, observer: self)
if waitForSuggestionInitial {
apsManager.determineBasal()
.receive(on: DispatchQueue.main)
.sink { [weak self] ok in
guard let self = self else { return }
if !ok {
self.waitForSuggestion = false
self.inslinRequired = 0
self.inslinRecommended = 0
}
}.store(in: &lifetime)
}
}
func add() {
guard amount > 0 else {
showModal(for: nil)
return
}
let maxAmount = Double(min(amount, provider.pumpSettings().maxBolus))
apsManager.enactBolus(amount: maxAmount, isSMB: false)
showModal(for: nil)
}
func addWithoutBolus() {
guard amount > 0 else {
showModal(for: nil)
return
}
pumpHistotyStorage.storeEvents(
[
PumpHistoryEvent(
id: UUID().uuidString,
type: .bolus,
timestamp: Date(),
amount: amount,
duration: nil,
durationMin: nil,
rate: nil,
temp: nil,
carbInput: nil
)
]
)
showModal(for: nil)
}
func roundInsulin(_ insulin: Decimal) -> Decimal {
insulin.rounded(1)
}
func carbRequired() -> Decimal {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
let now = dateFormatter.string(from: Date())
var ratio: Decimal = 0
for cr in provider.carbRatios.schedule {
if cr.start <= now {
ratio = cr.ratio
}
}
if ratio <= 0 {
return 0
}
let req = roundInsulin(carbsAdded / ratio)
NSLog("carbRequired Now \(now) \(ratio) \(req)")
return max(0, req)
}
func carbRecommended(_ required: Decimal) -> Decimal? {
if carbsAdded <= 0 {
return nil
}
let iob = provider.suggestion?.iob ?? 0
// Safety values should be configurable
if let bg = provider.suggestion?.bg, bg < 70 {
return nil
}
// The ratio should be configurable
// The logic here is that we trust any carbs entered to be
// somewhat correct. We err on the side of caution, substract iob, no matter the cob
// (so this will always underpredict).
// The target use case is aggressive pre-bolus for big meals with low bg.
let recommendation = max(0, 0.7 * (required - iob))
NSLog("carbRecommended Now \(iob) \(required) \(recommendation)")
return roundInsulin(recommendation)
}
func setupInsulinRequired() {
DispatchQueue.main.async {
self.carbsInsulinRequired = self.carbRequired()
self.carbsInsulinRecommended = self.carbRecommended(self.carbsInsulinRequired) ?? 0
var orefRecommended: Decimal = 0
var orefRequired: Decimal = 0
// Make sure there was a recent good suggestion. If determineBasal fails, suggestion
// is not cleared out.
// This should also check if there was a recent bolus
if let suggestion = self.provider.suggestion, let timestamp = suggestion.timestamp {
if timestamp.timeIntervalSinceNow > -5.minutes.timeInterval {
orefRequired = self.roundInsulin(suggestion.insulinReq ?? 0)
orefRecommended = self
.roundInsulin(max(orefRequired * self.settingsManager.settings.insulinReqFraction, 0))
} else {
debug(.default, "setupInsulinRequired: Suggestion too old \(timestamp.timeIntervalSinceNow) seconds")
}
}
self.inslinRequired = orefRequired
NSLog("Oref Recommended \(orefRecommended) U carbsInsulinRecommended \(self.carbsInsulinRecommended) U")
self.inslinRecommended = self.roundInsulin(max(
orefRecommended,
self.carbsInsulinRecommended
))
self.amount = self.inslinRecommended
}
}
}
}
extension Bolus.StateModel: SuggestionObserver {
func suggestionDidUpdate(_: Suggestion) {
DispatchQueue.main.async {
self.waitForSuggestion = false
}
setupInsulinRequired()
}
}
| 37.115854 | 125 | 0.523082 |
7a0d106f0f0927f88067fd5478ed37b92e9f32e1 | 7,216 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2021 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import Basics
import Dispatch
import Foundation
import PackageModel
import TSCBasic
public struct FilePackageFingerprintStorage: PackageFingerprintStorage {
let fileSystem: FileSystem
let directoryPath: AbsolutePath
private let encoder: JSONEncoder
private let decoder: JSONDecoder
public init(fileSystem: FileSystem, directoryPath: AbsolutePath) {
self.fileSystem = fileSystem
self.directoryPath = directoryPath
self.encoder = JSONEncoder.makeWithDefaults()
self.decoder = JSONDecoder.makeWithDefaults()
}
public func get(package: PackageIdentity,
version: Version,
observabilityScope: ObservabilityScope,
callbackQueue: DispatchQueue,
callback: @escaping (Result<[Fingerprint.Kind: Fingerprint], Error>) -> Void)
{
let callback = self.makeAsync(callback, on: callbackQueue)
do {
let packageFingerprints = try self.withLock {
try self.loadFromDisk(package: package)
}
guard let fingerprints = packageFingerprints[version] else {
throw PackageFingerprintStorageError.notFound
}
callback(.success(fingerprints))
} catch {
callback(.failure(error))
}
}
public func put(package: PackageIdentity,
version: Version,
fingerprint: Fingerprint,
observabilityScope: ObservabilityScope,
callbackQueue: DispatchQueue,
callback: @escaping (Result<Void, Error>) -> Void)
{
let callback = self.makeAsync(callback, on: callbackQueue)
do {
try self.withLock {
var packageFingerprints = try self.loadFromDisk(package: package)
if let existing = packageFingerprints[version]?[fingerprint.origin.kind] {
// Error if we try to write a different fingerprint
guard fingerprint == existing else {
throw PackageFingerprintStorageError.conflict(given: fingerprint, existing: existing)
}
// Don't need to do anything if fingerprints are the same
return
}
var fingerprints = packageFingerprints.removeValue(forKey: version) ?? [:]
fingerprints[fingerprint.origin.kind] = fingerprint
packageFingerprints[version] = fingerprints
try self.saveToDisk(package: package, fingerprints: packageFingerprints)
}
callback(.success(()))
} catch {
callback(.failure(error))
}
}
private func loadFromDisk(package: PackageIdentity) throws -> PackageFingerprints {
let path = self.directoryPath.appending(component: package.fingerprintFilename)
guard self.fileSystem.exists(path) else {
return .init()
}
let data: Data = try fileSystem.readFileContents(path)
guard data.count > 0 else {
return .init()
}
let container = try self.decoder.decode(StorageModel.Container.self, from: data)
return try container.packageFingerprints()
}
private func saveToDisk(package: PackageIdentity, fingerprints: PackageFingerprints) throws {
if !self.fileSystem.exists(self.directoryPath) {
try self.fileSystem.createDirectory(self.directoryPath, recursive: true)
}
let container = try StorageModel.Container(fingerprints)
let buffer = try encoder.encode(container)
let path = self.directoryPath.appending(component: package.fingerprintFilename)
try self.fileSystem.writeFileContents(path, bytes: ByteString(buffer))
}
private func withLock<T>(_ body: () throws -> T) throws -> T {
if !self.fileSystem.exists(self.directoryPath) {
try self.fileSystem.createDirectory(self.directoryPath, recursive: true)
}
return try self.fileSystem.withLock(on: self.directoryPath, type: .exclusive, body)
}
private func makeAsync<T>(_ closure: @escaping (Result<T, Error>) -> Void, on queue: DispatchQueue) -> (Result<T, Error>) -> Void {
{ result in queue.async { closure(result) } }
}
}
private enum StorageModel {
struct Container: Codable {
let versionFingerprints: [String: [String: StoredFingerprint]]
init(_ versionFingerprints: PackageFingerprints) throws {
self.versionFingerprints = try Dictionary(throwingUniqueKeysWithValues: versionFingerprints.map { version, fingerprints in
let fingerprintByKind: [String: StoredFingerprint] = Dictionary(uniqueKeysWithValues: fingerprints.map { kind, fingerprint in
let origin: String
switch fingerprint.origin {
case .sourceControl(let url):
origin = url.absoluteString
case .registry(let url):
origin = url.absoluteString
}
return (kind.rawValue, StoredFingerprint(origin: origin, fingerprint: fingerprint.value))
})
return (version.description, fingerprintByKind)
})
}
func packageFingerprints() throws -> PackageFingerprints {
try Dictionary(throwingUniqueKeysWithValues: self.versionFingerprints.map { version, fingerprints in
let fingerprintByKind: [Fingerprint.Kind: Fingerprint] = try Dictionary(uniqueKeysWithValues: fingerprints.map { kind, fingerprint in
guard let kind = Fingerprint.Kind(rawValue: kind) else {
throw SerializationError.unknownKind(kind)
}
guard let originURL = URL(string: fingerprint.origin) else {
throw SerializationError.invalidURL(fingerprint.origin)
}
let origin: Fingerprint.Origin
switch kind {
case .sourceControl:
origin = .sourceControl(originURL)
case .registry:
origin = .registry(originURL)
}
return (kind, Fingerprint(origin: origin, value: fingerprint.fingerprint))
})
return (Version(stringLiteral: version), fingerprintByKind)
})
}
}
struct StoredFingerprint: Codable {
let origin: String
let fingerprint: String
}
}
extension PackageIdentity {
var fingerprintFilename: String {
"\(self.description).json"
}
}
private enum SerializationError: Error {
case unknownKind(String)
case invalidURL(String)
}
| 37.978947 | 149 | 0.613775 |
09ec7816988e54a6f90e0e0bc89e4ea695bf66d5 | 11,318 | //
// UserDetailViewController2.swift
// News
//
// Created by 杨蒙 on 2018/1/3.
// Copyright © 2018年 hrscy. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
// MARK: - 自定义一个可以接受上层 tableView 手势的 tableView
class UserDetailTableView: UITableView, UIGestureRecognizerDelegate {
// 底层 tableView 实现这个 UIGestureRecognizerDelegate 代理方法,就可以响应上层 tableView 的滑动手势,
// otherGestureRecognizer 就是它上层的 view 持有的手势,这里的话,上层应该是 scrollView 和 顶层 tabelview
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
// 保证其他手势的存在
guard let otherView = otherGestureRecognizer.view else { return false }
// 如果其他手势的 view 是 UIScrollView,就不能让 UserDetailTableView 响应
if otherView.isMember(of: UIScrollView.self) { return false }
// 其他手势是 tableView 的 pan 手势,就让他响应
let isPan = gestureRecognizer.isKind(of: UIPanGestureRecognizer.self)
if isPan && otherView.isKind(of: UIScrollView.self) { return true }
return false
}
}
class UserDetailViewController2: UIViewController {
private let disposeBag = DisposeBag()
@IBOutlet weak var tableView: UserDetailTableView!
@IBOutlet weak var bottomview: UIView!
@IBOutlet weak var bottomViewHeight: NSLayoutConstraint!
@IBOutlet weak var bottomViewBottom: NSLayoutConstraint!
var userId: Int = 0
var userDetail = UserDetail()
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(false, animated: animated)
navigationController?.navigationBar.setBackgroundImage(UIImage(named: "navigation_background_clear"), for: .default)
}
override func viewDidLoad() {
super.viewDidLoad()
// 设置 UI
setupUI()
// 按钮点击
selectedAction()
}
/// 懒加载 头部
private lazy var headerView = UserDetailHeaderView2.loadViewFromNib()
/// 懒加载 底部
private lazy var myBottomView: UserDetailBottomView = {
let myBottomView = UserDetailBottomView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 44))
myBottomView.delegate = self
return myBottomView
}()
/// 懒加载 导航栏
private lazy var navigationBar = UserDetailNavigationBar.loadViewFromNib()
/// 懒加载 导航栏
private lazy var topTabScrollView = TopTabScrollView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 40))
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension UserDetailViewController2: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = UIView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 40))
view.addSubview(topTabScrollView)
return view
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.ym_dequeueReusableCell(indexPath: indexPath) as UserDetailCell
return cell
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offsetY = scrollView.contentOffset.y
let navigationBarHeight: CGFloat = isIPhoneX ? -88.0 : -64.0
if offsetY < navigationBarHeight {
let totalOffset = kUserDetailHeaderBGImageViewHeight + abs(offsetY)
let f = totalOffset / kUserDetailHeaderBGImageViewHeight
headerView.backgroundImageView.frame = CGRect(x: -screenWidth * (f - 1) * 0.5, y: offsetY, width: screenWidth * f, height: totalOffset)
navigationBar.navigationBar.backgroundColor = UIColor(white: 1.0, alpha: 0.0)
} else {
var alpha: CGFloat = (offsetY + 44) / 58
alpha = min(alpha, 1.0)
navigationBar.navigationBar.backgroundColor = UIColor(white: 1.0, alpha: alpha)
if alpha == 1.0 {
navigationController?.navigationBar.barStyle = .default
navigationBar.returnButton.theme_setImage("images.personal_home_back_black_24x24_", forState: .normal)
navigationBar.moreButton.theme_setImage("images.new_more_titlebar_24x24_", forState: .normal)
} else {
navigationController?.navigationBar.barStyle = .black
navigationBar.returnButton.theme_setImage("images.personal_home_back_white_24x24_", forState: .normal)
navigationBar.moreButton.theme_setImage("images.new_morewhite_titlebar_22x22_", forState: .normal)
}
// 14 + 15 + 14
var alpha1: CGFloat = offsetY / 57
if offsetY >= 43 {
alpha1 = min(alpha1, 1.0)
navigationBar.nameLabel.isHidden = false
navigationBar.concernButton.isHidden = false
navigationBar.nameLabel.textColor = UIColor(r: 0, g: 0, b: 0, alpha: alpha1)
navigationBar.concernButton.alpha = alpha1
} else {
alpha1 = min(0.0, alpha1)
navigationBar.nameLabel.textColor = UIColor(r: 0, g: 0, b: 0, alpha: alpha1)
navigationBar.concernButton.alpha = alpha1
}
}
}
}
// MARK: - 点击事件
extension UserDetailViewController2: UserDetailBottomViewDelegate {
/// 按钮点击
private func selectedAction() {
// 返回按钮点击
navigationBar.returnButton.rx.controlEvent(.touchUpInside)
.subscribe(onNext: { [weak self] in // 需要加 [weak self] 防止循环引用
self!.navigationController?.popViewController(animated: true)
})
.disposed(by: disposeBag)
// 更多按钮点击
navigationBar.moreButton.rx.controlEvent(.touchUpInside)
.subscribe(onNext: { () in // 需要加 [weak self] 防止循环引用
})
.disposed(by: disposeBag)
// 点击了关注按钮
headerView.didSelectConcernButton = { [weak self] in
self!.tableView.tableHeaderView = self!.headerView
}
// 当前的 topTab 类型
topTabScrollView.currentTopTab = { [weak self] (topTab, index) in
let cell = self!.tableView.cellForRow(at: IndexPath(row: 0, section: 0)) as! UserDetailCell
let dongtaiVC = self!.childViewControllers[index] as! DongtaiTableViewController
dongtaiVC.currentTopTabType = topTab.type
// 偏移
cell.scrollView.setContentOffset(CGPoint(x: CGFloat(index) * screenWidth, y: 0), animated: true)
}
}
// bottomView 底部按钮的点击
func bottomView(clicked button: UIButton, bottomTab: BottomTab) {
let bottomPushVC = UserDetailBottomPushController()
bottomPushVC.navigationItem.title = "网页浏览"
if bottomTab.children.count == 0 { // 直接跳转到下一控制器
bottomPushVC.url = bottomTab.value
navigationController?.pushViewController(bottomPushVC, animated: true)
} else { // 弹出 子视图
// 创建 Storyboard
let sb = UIStoryboard(name: "\(UserDetailBottomPopController.self)", bundle: nil)
// 创建 UserDetailBottomPopController
let popoverVC = sb.instantiateViewController(withIdentifier: "\(UserDetailBottomPopController.self)") as! UserDetailBottomPopController
popoverVC.children = bottomTab.children
popoverVC.modalPresentationStyle = .custom
popoverVC.didSelectedChild = { [weak self] in
bottomPushVC.url = $0.value
self!.navigationController?.pushViewController(bottomPushVC, animated: true)
}
let popoverAnimator = PopoverAnimator()
// 转化 frame
let rect = myBottomView.convert(button.frame, to: view)
let popWidth = (screenWidth - CGFloat(userDetail.bottom_tab.count + 1) * 20) / CGFloat(userDetail.bottom_tab.count)
let popX = CGFloat(button.tag) * (popWidth + 20) + 20
let popHeight = CGFloat(bottomTab.children.count) * 40 + 25
popoverAnimator.presetnFrame = CGRect(x: popX, y: rect.origin.y - popHeight, width: popWidth, height: popHeight)
popoverVC.transitioningDelegate = popoverAnimator
present(popoverVC, animated: true, completion: nil)
}
}
}
extension UserDetailViewController2 {
/// 设置 UI
private func setupUI() {
view.theme_backgroundColor = "colors.cellBackgroundColor"
navigationItem.leftBarButtonItem = UIBarButtonItem()
navigationController?.navigationBar.barStyle = .black
navigationItem.titleView = navigationBar
tableView.ym_registerCell(cell: UserDetailCell.self)
tableView.tableFooterView = UIView()
/// 获取用户详情数据 张雪峰 53271122458 马未都 51025535398
// userId = 8 // 这里可以注释掉,那么就会是不同的 userId 了
NetworkTool.loadUserDetail(userId: userId) { (userDetail) in
// 获取用户详情的动态列表数据
NetworkTool.loadUserDetailDongtaiList(userId: self.userId, maxCursor: 0, completionHandler: { (cursor, dongtais) in
if userDetail.bottom_tab.count != 0 {
// 底部 view 的高度
self.bottomViewHeight.constant = isIPhoneX ? 78 : 44
self.view.layoutIfNeeded()
self.myBottomView.bottomTabs = userDetail.bottom_tab
self.bottomview.addSubview(self.myBottomView)
}
self.userDetail = userDetail
self.headerView.userDetail = userDetail
self.navigationBar.userDetail = userDetail
self.topTabScrollView.topTabs = userDetail.top_tab
self.tableView.tableHeaderView = self.headerView
let navigationBarHeight: CGFloat = isIPhoneX ? 88.0 : 64.0
let rowHeight = screenHeight - navigationBarHeight - self.tableView.sectionHeaderHeight - self.bottomViewHeight.constant
self.tableView.rowHeight = rowHeight
// 一定要先 reload 一次,否则不能刷新数据,也不能设置行高
self.tableView.reloadData()
if userDetail.top_tab.count == 0 { return }
let cell = self.tableView.cellForRow(at: IndexPath(row: 0, section: 0)) as! UserDetailCell
// 遍历
for (index, topTab) in userDetail.top_tab.enumerated() {
let dongtaiVC = DongtaiTableViewController()
self.addChildViewController(dongtaiVC)
if index == 0 { dongtaiVC.currentTopTabType = topTab.type }
dongtaiVC.userId = userDetail.user_id
dongtaiVC.tableView.frame = CGRect(x: CGFloat(index) * screenWidth, y: 0, width: screenWidth, height: rowHeight)
cell.scrollView.addSubview(dongtaiVC.tableView)
if index == userDetail.top_tab.count - 1 {
cell.scrollView.contentSize = CGSize(width: CGFloat(userDetail.top_tab.count) * screenWidth, height: cell.scrollView.height)
}
}
})
}
}
}
| 46.576132 | 157 | 0.642163 |
7ad223a2167b231ac0c345f26e8086860743fb89 | 523 | //
// Alamofire+Extension.swift
// Open Book
//
// Created by martin chibwe on 7/12/16.
// Copyright © 2016 martin chibwe. All rights reserved.
//
import Alamofire
extension Response {
var cancelled: Bool {
switch self.result {
case .Failure(let error):
if let urlError = error as? NSURLError where urlError == .Cancelled {
return true
} else {
return false
}
case .Success(_):
return false
}
}
}
| 20.92 | 81 | 0.543021 |
48519ee491e91e4d8cf6d574457acccb37aaf305 | 312 | //
// ViewController.swift
// MiniApp
//
// Created by Huong Cao on 6/17/19.
// Copyright © 2019 HuongCao. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
| 14.857143 | 54 | 0.679487 |
dbdccc1441514ae8cb366cff80813a97c0669e6a | 65,517 | // Generated from /Users/luizfernandosilva/Documents/Projetos/objcgrammar/ObjectiveCParser.g4 by ANTLR 4.8
import Antlr4
/**
* This interface defines a complete listener for a parse tree produced by
* {@link ObjectiveCParser}.
*/
public protocol ObjectiveCParserListener: ParseTreeListener {
/**
* Enter a parse tree produced by {@link ObjectiveCParser#translationUnit}.
- Parameters:
- ctx: the parse tree
*/
func enterTranslationUnit(_ ctx: ObjectiveCParser.TranslationUnitContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#translationUnit}.
- Parameters:
- ctx: the parse tree
*/
func exitTranslationUnit(_ ctx: ObjectiveCParser.TranslationUnitContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#topLevelDeclaration}.
- Parameters:
- ctx: the parse tree
*/
func enterTopLevelDeclaration(_ ctx: ObjectiveCParser.TopLevelDeclarationContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#topLevelDeclaration}.
- Parameters:
- ctx: the parse tree
*/
func exitTopLevelDeclaration(_ ctx: ObjectiveCParser.TopLevelDeclarationContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#importDeclaration}.
- Parameters:
- ctx: the parse tree
*/
func enterImportDeclaration(_ ctx: ObjectiveCParser.ImportDeclarationContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#importDeclaration}.
- Parameters:
- ctx: the parse tree
*/
func exitImportDeclaration(_ ctx: ObjectiveCParser.ImportDeclarationContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#classInterface}.
- Parameters:
- ctx: the parse tree
*/
func enterClassInterface(_ ctx: ObjectiveCParser.ClassInterfaceContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#classInterface}.
- Parameters:
- ctx: the parse tree
*/
func exitClassInterface(_ ctx: ObjectiveCParser.ClassInterfaceContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#classInterfaceName}.
- Parameters:
- ctx: the parse tree
*/
func enterClassInterfaceName(_ ctx: ObjectiveCParser.ClassInterfaceNameContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#classInterfaceName}.
- Parameters:
- ctx: the parse tree
*/
func exitClassInterfaceName(_ ctx: ObjectiveCParser.ClassInterfaceNameContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#categoryInterface}.
- Parameters:
- ctx: the parse tree
*/
func enterCategoryInterface(_ ctx: ObjectiveCParser.CategoryInterfaceContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#categoryInterface}.
- Parameters:
- ctx: the parse tree
*/
func exitCategoryInterface(_ ctx: ObjectiveCParser.CategoryInterfaceContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#classImplementation}.
- Parameters:
- ctx: the parse tree
*/
func enterClassImplementation(_ ctx: ObjectiveCParser.ClassImplementationContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#classImplementation}.
- Parameters:
- ctx: the parse tree
*/
func exitClassImplementation(_ ctx: ObjectiveCParser.ClassImplementationContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#classImplementatioName}.
- Parameters:
- ctx: the parse tree
*/
func enterClassImplementatioName(_ ctx: ObjectiveCParser.ClassImplementatioNameContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#classImplementatioName}.
- Parameters:
- ctx: the parse tree
*/
func exitClassImplementatioName(_ ctx: ObjectiveCParser.ClassImplementatioNameContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#categoryImplementation}.
- Parameters:
- ctx: the parse tree
*/
func enterCategoryImplementation(_ ctx: ObjectiveCParser.CategoryImplementationContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#categoryImplementation}.
- Parameters:
- ctx: the parse tree
*/
func exitCategoryImplementation(_ ctx: ObjectiveCParser.CategoryImplementationContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#className}.
- Parameters:
- ctx: the parse tree
*/
func enterClassName(_ ctx: ObjectiveCParser.ClassNameContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#className}.
- Parameters:
- ctx: the parse tree
*/
func exitClassName(_ ctx: ObjectiveCParser.ClassNameContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#superclassName}.
- Parameters:
- ctx: the parse tree
*/
func enterSuperclassName(_ ctx: ObjectiveCParser.SuperclassNameContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#superclassName}.
- Parameters:
- ctx: the parse tree
*/
func exitSuperclassName(_ ctx: ObjectiveCParser.SuperclassNameContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#genericSuperclassName}.
- Parameters:
- ctx: the parse tree
*/
func enterGenericSuperclassName(_ ctx: ObjectiveCParser.GenericSuperclassNameContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#genericSuperclassName}.
- Parameters:
- ctx: the parse tree
*/
func exitGenericSuperclassName(_ ctx: ObjectiveCParser.GenericSuperclassNameContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#genericTypeSpecifier}.
- Parameters:
- ctx: the parse tree
*/
func enterGenericTypeSpecifier(_ ctx: ObjectiveCParser.GenericTypeSpecifierContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#genericTypeSpecifier}.
- Parameters:
- ctx: the parse tree
*/
func exitGenericTypeSpecifier(_ ctx: ObjectiveCParser.GenericTypeSpecifierContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#genericSuperclassSpecifier}.
- Parameters:
- ctx: the parse tree
*/
func enterGenericSuperclassSpecifier(_ ctx: ObjectiveCParser.GenericSuperclassSpecifierContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#genericSuperclassSpecifier}.
- Parameters:
- ctx: the parse tree
*/
func exitGenericSuperclassSpecifier(_ ctx: ObjectiveCParser.GenericSuperclassSpecifierContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#superclassTypeSpecifierWithPrefixes}.
- Parameters:
- ctx: the parse tree
*/
func enterSuperclassTypeSpecifierWithPrefixes(_ ctx: ObjectiveCParser.SuperclassTypeSpecifierWithPrefixesContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#superclassTypeSpecifierWithPrefixes}.
- Parameters:
- ctx: the parse tree
*/
func exitSuperclassTypeSpecifierWithPrefixes(_ ctx: ObjectiveCParser.SuperclassTypeSpecifierWithPrefixesContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#protocolDeclaration}.
- Parameters:
- ctx: the parse tree
*/
func enterProtocolDeclaration(_ ctx: ObjectiveCParser.ProtocolDeclarationContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#protocolDeclaration}.
- Parameters:
- ctx: the parse tree
*/
func exitProtocolDeclaration(_ ctx: ObjectiveCParser.ProtocolDeclarationContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#protocolDeclarationSection}.
- Parameters:
- ctx: the parse tree
*/
func enterProtocolDeclarationSection(_ ctx: ObjectiveCParser.ProtocolDeclarationSectionContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#protocolDeclarationSection}.
- Parameters:
- ctx: the parse tree
*/
func exitProtocolDeclarationSection(_ ctx: ObjectiveCParser.ProtocolDeclarationSectionContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#protocolDeclarationList}.
- Parameters:
- ctx: the parse tree
*/
func enterProtocolDeclarationList(_ ctx: ObjectiveCParser.ProtocolDeclarationListContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#protocolDeclarationList}.
- Parameters:
- ctx: the parse tree
*/
func exitProtocolDeclarationList(_ ctx: ObjectiveCParser.ProtocolDeclarationListContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#classDeclarationList}.
- Parameters:
- ctx: the parse tree
*/
func enterClassDeclarationList(_ ctx: ObjectiveCParser.ClassDeclarationListContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#classDeclarationList}.
- Parameters:
- ctx: the parse tree
*/
func exitClassDeclarationList(_ ctx: ObjectiveCParser.ClassDeclarationListContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#protocolList}.
- Parameters:
- ctx: the parse tree
*/
func enterProtocolList(_ ctx: ObjectiveCParser.ProtocolListContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#protocolList}.
- Parameters:
- ctx: the parse tree
*/
func exitProtocolList(_ ctx: ObjectiveCParser.ProtocolListContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#propertyDeclaration}.
- Parameters:
- ctx: the parse tree
*/
func enterPropertyDeclaration(_ ctx: ObjectiveCParser.PropertyDeclarationContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#propertyDeclaration}.
- Parameters:
- ctx: the parse tree
*/
func exitPropertyDeclaration(_ ctx: ObjectiveCParser.PropertyDeclarationContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#propertyAttributesList}.
- Parameters:
- ctx: the parse tree
*/
func enterPropertyAttributesList(_ ctx: ObjectiveCParser.PropertyAttributesListContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#propertyAttributesList}.
- Parameters:
- ctx: the parse tree
*/
func exitPropertyAttributesList(_ ctx: ObjectiveCParser.PropertyAttributesListContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#propertyAttribute}.
- Parameters:
- ctx: the parse tree
*/
func enterPropertyAttribute(_ ctx: ObjectiveCParser.PropertyAttributeContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#propertyAttribute}.
- Parameters:
- ctx: the parse tree
*/
func exitPropertyAttribute(_ ctx: ObjectiveCParser.PropertyAttributeContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#protocolName}.
- Parameters:
- ctx: the parse tree
*/
func enterProtocolName(_ ctx: ObjectiveCParser.ProtocolNameContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#protocolName}.
- Parameters:
- ctx: the parse tree
*/
func exitProtocolName(_ ctx: ObjectiveCParser.ProtocolNameContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#instanceVariables}.
- Parameters:
- ctx: the parse tree
*/
func enterInstanceVariables(_ ctx: ObjectiveCParser.InstanceVariablesContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#instanceVariables}.
- Parameters:
- ctx: the parse tree
*/
func exitInstanceVariables(_ ctx: ObjectiveCParser.InstanceVariablesContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#visibilitySection}.
- Parameters:
- ctx: the parse tree
*/
func enterVisibilitySection(_ ctx: ObjectiveCParser.VisibilitySectionContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#visibilitySection}.
- Parameters:
- ctx: the parse tree
*/
func exitVisibilitySection(_ ctx: ObjectiveCParser.VisibilitySectionContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#accessModifier}.
- Parameters:
- ctx: the parse tree
*/
func enterAccessModifier(_ ctx: ObjectiveCParser.AccessModifierContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#accessModifier}.
- Parameters:
- ctx: the parse tree
*/
func exitAccessModifier(_ ctx: ObjectiveCParser.AccessModifierContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#interfaceDeclarationList}.
- Parameters:
- ctx: the parse tree
*/
func enterInterfaceDeclarationList(_ ctx: ObjectiveCParser.InterfaceDeclarationListContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#interfaceDeclarationList}.
- Parameters:
- ctx: the parse tree
*/
func exitInterfaceDeclarationList(_ ctx: ObjectiveCParser.InterfaceDeclarationListContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#classMethodDeclaration}.
- Parameters:
- ctx: the parse tree
*/
func enterClassMethodDeclaration(_ ctx: ObjectiveCParser.ClassMethodDeclarationContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#classMethodDeclaration}.
- Parameters:
- ctx: the parse tree
*/
func exitClassMethodDeclaration(_ ctx: ObjectiveCParser.ClassMethodDeclarationContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#instanceMethodDeclaration}.
- Parameters:
- ctx: the parse tree
*/
func enterInstanceMethodDeclaration(_ ctx: ObjectiveCParser.InstanceMethodDeclarationContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#instanceMethodDeclaration}.
- Parameters:
- ctx: the parse tree
*/
func exitInstanceMethodDeclaration(_ ctx: ObjectiveCParser.InstanceMethodDeclarationContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#methodDeclaration}.
- Parameters:
- ctx: the parse tree
*/
func enterMethodDeclaration(_ ctx: ObjectiveCParser.MethodDeclarationContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#methodDeclaration}.
- Parameters:
- ctx: the parse tree
*/
func exitMethodDeclaration(_ ctx: ObjectiveCParser.MethodDeclarationContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#implementationDefinitionList}.
- Parameters:
- ctx: the parse tree
*/
func enterImplementationDefinitionList(_ ctx: ObjectiveCParser.ImplementationDefinitionListContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#implementationDefinitionList}.
- Parameters:
- ctx: the parse tree
*/
func exitImplementationDefinitionList(_ ctx: ObjectiveCParser.ImplementationDefinitionListContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#classMethodDefinition}.
- Parameters:
- ctx: the parse tree
*/
func enterClassMethodDefinition(_ ctx: ObjectiveCParser.ClassMethodDefinitionContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#classMethodDefinition}.
- Parameters:
- ctx: the parse tree
*/
func exitClassMethodDefinition(_ ctx: ObjectiveCParser.ClassMethodDefinitionContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#instanceMethodDefinition}.
- Parameters:
- ctx: the parse tree
*/
func enterInstanceMethodDefinition(_ ctx: ObjectiveCParser.InstanceMethodDefinitionContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#instanceMethodDefinition}.
- Parameters:
- ctx: the parse tree
*/
func exitInstanceMethodDefinition(_ ctx: ObjectiveCParser.InstanceMethodDefinitionContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#methodDefinition}.
- Parameters:
- ctx: the parse tree
*/
func enterMethodDefinition(_ ctx: ObjectiveCParser.MethodDefinitionContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#methodDefinition}.
- Parameters:
- ctx: the parse tree
*/
func exitMethodDefinition(_ ctx: ObjectiveCParser.MethodDefinitionContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#methodSelector}.
- Parameters:
- ctx: the parse tree
*/
func enterMethodSelector(_ ctx: ObjectiveCParser.MethodSelectorContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#methodSelector}.
- Parameters:
- ctx: the parse tree
*/
func exitMethodSelector(_ ctx: ObjectiveCParser.MethodSelectorContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#keywordDeclarator}.
- Parameters:
- ctx: the parse tree
*/
func enterKeywordDeclarator(_ ctx: ObjectiveCParser.KeywordDeclaratorContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#keywordDeclarator}.
- Parameters:
- ctx: the parse tree
*/
func exitKeywordDeclarator(_ ctx: ObjectiveCParser.KeywordDeclaratorContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#selector}.
- Parameters:
- ctx: the parse tree
*/
func enterSelector(_ ctx: ObjectiveCParser.SelectorContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#selector}.
- Parameters:
- ctx: the parse tree
*/
func exitSelector(_ ctx: ObjectiveCParser.SelectorContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#methodType}.
- Parameters:
- ctx: the parse tree
*/
func enterMethodType(_ ctx: ObjectiveCParser.MethodTypeContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#methodType}.
- Parameters:
- ctx: the parse tree
*/
func exitMethodType(_ ctx: ObjectiveCParser.MethodTypeContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#propertyImplementation}.
- Parameters:
- ctx: the parse tree
*/
func enterPropertyImplementation(_ ctx: ObjectiveCParser.PropertyImplementationContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#propertyImplementation}.
- Parameters:
- ctx: the parse tree
*/
func exitPropertyImplementation(_ ctx: ObjectiveCParser.PropertyImplementationContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#propertySynthesizeList}.
- Parameters:
- ctx: the parse tree
*/
func enterPropertySynthesizeList(_ ctx: ObjectiveCParser.PropertySynthesizeListContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#propertySynthesizeList}.
- Parameters:
- ctx: the parse tree
*/
func exitPropertySynthesizeList(_ ctx: ObjectiveCParser.PropertySynthesizeListContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#propertySynthesizeItem}.
- Parameters:
- ctx: the parse tree
*/
func enterPropertySynthesizeItem(_ ctx: ObjectiveCParser.PropertySynthesizeItemContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#propertySynthesizeItem}.
- Parameters:
- ctx: the parse tree
*/
func exitPropertySynthesizeItem(_ ctx: ObjectiveCParser.PropertySynthesizeItemContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#blockType}.
- Parameters:
- ctx: the parse tree
*/
func enterBlockType(_ ctx: ObjectiveCParser.BlockTypeContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#blockType}.
- Parameters:
- ctx: the parse tree
*/
func exitBlockType(_ ctx: ObjectiveCParser.BlockTypeContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#genericsSpecifier}.
- Parameters:
- ctx: the parse tree
*/
func enterGenericsSpecifier(_ ctx: ObjectiveCParser.GenericsSpecifierContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#genericsSpecifier}.
- Parameters:
- ctx: the parse tree
*/
func exitGenericsSpecifier(_ ctx: ObjectiveCParser.GenericsSpecifierContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#typeSpecifierWithPrefixes}.
- Parameters:
- ctx: the parse tree
*/
func enterTypeSpecifierWithPrefixes(_ ctx: ObjectiveCParser.TypeSpecifierWithPrefixesContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#typeSpecifierWithPrefixes}.
- Parameters:
- ctx: the parse tree
*/
func exitTypeSpecifierWithPrefixes(_ ctx: ObjectiveCParser.TypeSpecifierWithPrefixesContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#dictionaryExpression}.
- Parameters:
- ctx: the parse tree
*/
func enterDictionaryExpression(_ ctx: ObjectiveCParser.DictionaryExpressionContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#dictionaryExpression}.
- Parameters:
- ctx: the parse tree
*/
func exitDictionaryExpression(_ ctx: ObjectiveCParser.DictionaryExpressionContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#dictionaryPair}.
- Parameters:
- ctx: the parse tree
*/
func enterDictionaryPair(_ ctx: ObjectiveCParser.DictionaryPairContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#dictionaryPair}.
- Parameters:
- ctx: the parse tree
*/
func exitDictionaryPair(_ ctx: ObjectiveCParser.DictionaryPairContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#arrayExpression}.
- Parameters:
- ctx: the parse tree
*/
func enterArrayExpression(_ ctx: ObjectiveCParser.ArrayExpressionContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#arrayExpression}.
- Parameters:
- ctx: the parse tree
*/
func exitArrayExpression(_ ctx: ObjectiveCParser.ArrayExpressionContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#boxExpression}.
- Parameters:
- ctx: the parse tree
*/
func enterBoxExpression(_ ctx: ObjectiveCParser.BoxExpressionContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#boxExpression}.
- Parameters:
- ctx: the parse tree
*/
func exitBoxExpression(_ ctx: ObjectiveCParser.BoxExpressionContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#blockParameters}.
- Parameters:
- ctx: the parse tree
*/
func enterBlockParameters(_ ctx: ObjectiveCParser.BlockParametersContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#blockParameters}.
- Parameters:
- ctx: the parse tree
*/
func exitBlockParameters(_ ctx: ObjectiveCParser.BlockParametersContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#typeVariableDeclaratorOrName}.
- Parameters:
- ctx: the parse tree
*/
func enterTypeVariableDeclaratorOrName(_ ctx: ObjectiveCParser.TypeVariableDeclaratorOrNameContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#typeVariableDeclaratorOrName}.
- Parameters:
- ctx: the parse tree
*/
func exitTypeVariableDeclaratorOrName(_ ctx: ObjectiveCParser.TypeVariableDeclaratorOrNameContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#blockExpression}.
- Parameters:
- ctx: the parse tree
*/
func enterBlockExpression(_ ctx: ObjectiveCParser.BlockExpressionContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#blockExpression}.
- Parameters:
- ctx: the parse tree
*/
func exitBlockExpression(_ ctx: ObjectiveCParser.BlockExpressionContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#messageExpression}.
- Parameters:
- ctx: the parse tree
*/
func enterMessageExpression(_ ctx: ObjectiveCParser.MessageExpressionContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#messageExpression}.
- Parameters:
- ctx: the parse tree
*/
func exitMessageExpression(_ ctx: ObjectiveCParser.MessageExpressionContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#receiver}.
- Parameters:
- ctx: the parse tree
*/
func enterReceiver(_ ctx: ObjectiveCParser.ReceiverContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#receiver}.
- Parameters:
- ctx: the parse tree
*/
func exitReceiver(_ ctx: ObjectiveCParser.ReceiverContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#messageSelector}.
- Parameters:
- ctx: the parse tree
*/
func enterMessageSelector(_ ctx: ObjectiveCParser.MessageSelectorContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#messageSelector}.
- Parameters:
- ctx: the parse tree
*/
func exitMessageSelector(_ ctx: ObjectiveCParser.MessageSelectorContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#keywordArgument}.
- Parameters:
- ctx: the parse tree
*/
func enterKeywordArgument(_ ctx: ObjectiveCParser.KeywordArgumentContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#keywordArgument}.
- Parameters:
- ctx: the parse tree
*/
func exitKeywordArgument(_ ctx: ObjectiveCParser.KeywordArgumentContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#keywordArgumentType}.
- Parameters:
- ctx: the parse tree
*/
func enterKeywordArgumentType(_ ctx: ObjectiveCParser.KeywordArgumentTypeContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#keywordArgumentType}.
- Parameters:
- ctx: the parse tree
*/
func exitKeywordArgumentType(_ ctx: ObjectiveCParser.KeywordArgumentTypeContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#selectorExpression}.
- Parameters:
- ctx: the parse tree
*/
func enterSelectorExpression(_ ctx: ObjectiveCParser.SelectorExpressionContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#selectorExpression}.
- Parameters:
- ctx: the parse tree
*/
func exitSelectorExpression(_ ctx: ObjectiveCParser.SelectorExpressionContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#selectorName}.
- Parameters:
- ctx: the parse tree
*/
func enterSelectorName(_ ctx: ObjectiveCParser.SelectorNameContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#selectorName}.
- Parameters:
- ctx: the parse tree
*/
func exitSelectorName(_ ctx: ObjectiveCParser.SelectorNameContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#protocolExpression}.
- Parameters:
- ctx: the parse tree
*/
func enterProtocolExpression(_ ctx: ObjectiveCParser.ProtocolExpressionContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#protocolExpression}.
- Parameters:
- ctx: the parse tree
*/
func exitProtocolExpression(_ ctx: ObjectiveCParser.ProtocolExpressionContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#encodeExpression}.
- Parameters:
- ctx: the parse tree
*/
func enterEncodeExpression(_ ctx: ObjectiveCParser.EncodeExpressionContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#encodeExpression}.
- Parameters:
- ctx: the parse tree
*/
func exitEncodeExpression(_ ctx: ObjectiveCParser.EncodeExpressionContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#typeVariableDeclarator}.
- Parameters:
- ctx: the parse tree
*/
func enterTypeVariableDeclarator(_ ctx: ObjectiveCParser.TypeVariableDeclaratorContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#typeVariableDeclarator}.
- Parameters:
- ctx: the parse tree
*/
func exitTypeVariableDeclarator(_ ctx: ObjectiveCParser.TypeVariableDeclaratorContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#throwStatement}.
- Parameters:
- ctx: the parse tree
*/
func enterThrowStatement(_ ctx: ObjectiveCParser.ThrowStatementContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#throwStatement}.
- Parameters:
- ctx: the parse tree
*/
func exitThrowStatement(_ ctx: ObjectiveCParser.ThrowStatementContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#tryBlock}.
- Parameters:
- ctx: the parse tree
*/
func enterTryBlock(_ ctx: ObjectiveCParser.TryBlockContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#tryBlock}.
- Parameters:
- ctx: the parse tree
*/
func exitTryBlock(_ ctx: ObjectiveCParser.TryBlockContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#catchStatement}.
- Parameters:
- ctx: the parse tree
*/
func enterCatchStatement(_ ctx: ObjectiveCParser.CatchStatementContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#catchStatement}.
- Parameters:
- ctx: the parse tree
*/
func exitCatchStatement(_ ctx: ObjectiveCParser.CatchStatementContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#synchronizedStatement}.
- Parameters:
- ctx: the parse tree
*/
func enterSynchronizedStatement(_ ctx: ObjectiveCParser.SynchronizedStatementContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#synchronizedStatement}.
- Parameters:
- ctx: the parse tree
*/
func exitSynchronizedStatement(_ ctx: ObjectiveCParser.SynchronizedStatementContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#autoreleaseStatement}.
- Parameters:
- ctx: the parse tree
*/
func enterAutoreleaseStatement(_ ctx: ObjectiveCParser.AutoreleaseStatementContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#autoreleaseStatement}.
- Parameters:
- ctx: the parse tree
*/
func exitAutoreleaseStatement(_ ctx: ObjectiveCParser.AutoreleaseStatementContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#functionDeclaration}.
- Parameters:
- ctx: the parse tree
*/
func enterFunctionDeclaration(_ ctx: ObjectiveCParser.FunctionDeclarationContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#functionDeclaration}.
- Parameters:
- ctx: the parse tree
*/
func exitFunctionDeclaration(_ ctx: ObjectiveCParser.FunctionDeclarationContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#functionDefinition}.
- Parameters:
- ctx: the parse tree
*/
func enterFunctionDefinition(_ ctx: ObjectiveCParser.FunctionDefinitionContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#functionDefinition}.
- Parameters:
- ctx: the parse tree
*/
func exitFunctionDefinition(_ ctx: ObjectiveCParser.FunctionDefinitionContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#functionSignature}.
- Parameters:
- ctx: the parse tree
*/
func enterFunctionSignature(_ ctx: ObjectiveCParser.FunctionSignatureContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#functionSignature}.
- Parameters:
- ctx: the parse tree
*/
func exitFunctionSignature(_ ctx: ObjectiveCParser.FunctionSignatureContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#attribute}.
- Parameters:
- ctx: the parse tree
*/
func enterAttribute(_ ctx: ObjectiveCParser.AttributeContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#attribute}.
- Parameters:
- ctx: the parse tree
*/
func exitAttribute(_ ctx: ObjectiveCParser.AttributeContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#attributeName}.
- Parameters:
- ctx: the parse tree
*/
func enterAttributeName(_ ctx: ObjectiveCParser.AttributeNameContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#attributeName}.
- Parameters:
- ctx: the parse tree
*/
func exitAttributeName(_ ctx: ObjectiveCParser.AttributeNameContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#attributeParameters}.
- Parameters:
- ctx: the parse tree
*/
func enterAttributeParameters(_ ctx: ObjectiveCParser.AttributeParametersContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#attributeParameters}.
- Parameters:
- ctx: the parse tree
*/
func exitAttributeParameters(_ ctx: ObjectiveCParser.AttributeParametersContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#attributeParameterList}.
- Parameters:
- ctx: the parse tree
*/
func enterAttributeParameterList(_ ctx: ObjectiveCParser.AttributeParameterListContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#attributeParameterList}.
- Parameters:
- ctx: the parse tree
*/
func exitAttributeParameterList(_ ctx: ObjectiveCParser.AttributeParameterListContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#attributeParameter}.
- Parameters:
- ctx: the parse tree
*/
func enterAttributeParameter(_ ctx: ObjectiveCParser.AttributeParameterContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#attributeParameter}.
- Parameters:
- ctx: the parse tree
*/
func exitAttributeParameter(_ ctx: ObjectiveCParser.AttributeParameterContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#attributeParameterAssignment}.
- Parameters:
- ctx: the parse tree
*/
func enterAttributeParameterAssignment(_ ctx: ObjectiveCParser.AttributeParameterAssignmentContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#attributeParameterAssignment}.
- Parameters:
- ctx: the parse tree
*/
func exitAttributeParameterAssignment(_ ctx: ObjectiveCParser.AttributeParameterAssignmentContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#declaration}.
- Parameters:
- ctx: the parse tree
*/
func enterDeclaration(_ ctx: ObjectiveCParser.DeclarationContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#declaration}.
- Parameters:
- ctx: the parse tree
*/
func exitDeclaration(_ ctx: ObjectiveCParser.DeclarationContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#functionPointer}.
- Parameters:
- ctx: the parse tree
*/
func enterFunctionPointer(_ ctx: ObjectiveCParser.FunctionPointerContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#functionPointer}.
- Parameters:
- ctx: the parse tree
*/
func exitFunctionPointer(_ ctx: ObjectiveCParser.FunctionPointerContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#functionPointerParameterList}.
- Parameters:
- ctx: the parse tree
*/
func enterFunctionPointerParameterList(_ ctx: ObjectiveCParser.FunctionPointerParameterListContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#functionPointerParameterList}.
- Parameters:
- ctx: the parse tree
*/
func exitFunctionPointerParameterList(_ ctx: ObjectiveCParser.FunctionPointerParameterListContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#functionPointerParameterDeclarationList}.
- Parameters:
- ctx: the parse tree
*/
func enterFunctionPointerParameterDeclarationList(_ ctx: ObjectiveCParser.FunctionPointerParameterDeclarationListContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#functionPointerParameterDeclarationList}.
- Parameters:
- ctx: the parse tree
*/
func exitFunctionPointerParameterDeclarationList(_ ctx: ObjectiveCParser.FunctionPointerParameterDeclarationListContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#functionPointerParameterDeclaration}.
- Parameters:
- ctx: the parse tree
*/
func enterFunctionPointerParameterDeclaration(_ ctx: ObjectiveCParser.FunctionPointerParameterDeclarationContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#functionPointerParameterDeclaration}.
- Parameters:
- ctx: the parse tree
*/
func exitFunctionPointerParameterDeclaration(_ ctx: ObjectiveCParser.FunctionPointerParameterDeclarationContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#functionCallExpression}.
- Parameters:
- ctx: the parse tree
*/
func enterFunctionCallExpression(_ ctx: ObjectiveCParser.FunctionCallExpressionContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#functionCallExpression}.
- Parameters:
- ctx: the parse tree
*/
func exitFunctionCallExpression(_ ctx: ObjectiveCParser.FunctionCallExpressionContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#enumDeclaration}.
- Parameters:
- ctx: the parse tree
*/
func enterEnumDeclaration(_ ctx: ObjectiveCParser.EnumDeclarationContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#enumDeclaration}.
- Parameters:
- ctx: the parse tree
*/
func exitEnumDeclaration(_ ctx: ObjectiveCParser.EnumDeclarationContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#varDeclaration}.
- Parameters:
- ctx: the parse tree
*/
func enterVarDeclaration(_ ctx: ObjectiveCParser.VarDeclarationContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#varDeclaration}.
- Parameters:
- ctx: the parse tree
*/
func exitVarDeclaration(_ ctx: ObjectiveCParser.VarDeclarationContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#typedefDeclaration}.
- Parameters:
- ctx: the parse tree
*/
func enterTypedefDeclaration(_ ctx: ObjectiveCParser.TypedefDeclarationContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#typedefDeclaration}.
- Parameters:
- ctx: the parse tree
*/
func exitTypedefDeclaration(_ ctx: ObjectiveCParser.TypedefDeclarationContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#typeDeclaratorList}.
- Parameters:
- ctx: the parse tree
*/
func enterTypeDeclaratorList(_ ctx: ObjectiveCParser.TypeDeclaratorListContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#typeDeclaratorList}.
- Parameters:
- ctx: the parse tree
*/
func exitTypeDeclaratorList(_ ctx: ObjectiveCParser.TypeDeclaratorListContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#declarationSpecifiers}.
- Parameters:
- ctx: the parse tree
*/
func enterDeclarationSpecifiers(_ ctx: ObjectiveCParser.DeclarationSpecifiersContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#declarationSpecifiers}.
- Parameters:
- ctx: the parse tree
*/
func exitDeclarationSpecifiers(_ ctx: ObjectiveCParser.DeclarationSpecifiersContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#attributeSpecifier}.
- Parameters:
- ctx: the parse tree
*/
func enterAttributeSpecifier(_ ctx: ObjectiveCParser.AttributeSpecifierContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#attributeSpecifier}.
- Parameters:
- ctx: the parse tree
*/
func exitAttributeSpecifier(_ ctx: ObjectiveCParser.AttributeSpecifierContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#initDeclaratorList}.
- Parameters:
- ctx: the parse tree
*/
func enterInitDeclaratorList(_ ctx: ObjectiveCParser.InitDeclaratorListContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#initDeclaratorList}.
- Parameters:
- ctx: the parse tree
*/
func exitInitDeclaratorList(_ ctx: ObjectiveCParser.InitDeclaratorListContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#initDeclarator}.
- Parameters:
- ctx: the parse tree
*/
func enterInitDeclarator(_ ctx: ObjectiveCParser.InitDeclaratorContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#initDeclarator}.
- Parameters:
- ctx: the parse tree
*/
func exitInitDeclarator(_ ctx: ObjectiveCParser.InitDeclaratorContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#structOrUnionSpecifier}.
- Parameters:
- ctx: the parse tree
*/
func enterStructOrUnionSpecifier(_ ctx: ObjectiveCParser.StructOrUnionSpecifierContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#structOrUnionSpecifier}.
- Parameters:
- ctx: the parse tree
*/
func exitStructOrUnionSpecifier(_ ctx: ObjectiveCParser.StructOrUnionSpecifierContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#fieldDeclaration}.
- Parameters:
- ctx: the parse tree
*/
func enterFieldDeclaration(_ ctx: ObjectiveCParser.FieldDeclarationContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#fieldDeclaration}.
- Parameters:
- ctx: the parse tree
*/
func exitFieldDeclaration(_ ctx: ObjectiveCParser.FieldDeclarationContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#specifierQualifierList}.
- Parameters:
- ctx: the parse tree
*/
func enterSpecifierQualifierList(_ ctx: ObjectiveCParser.SpecifierQualifierListContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#specifierQualifierList}.
- Parameters:
- ctx: the parse tree
*/
func exitSpecifierQualifierList(_ ctx: ObjectiveCParser.SpecifierQualifierListContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#ibOutletQualifier}.
- Parameters:
- ctx: the parse tree
*/
func enterIbOutletQualifier(_ ctx: ObjectiveCParser.IbOutletQualifierContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#ibOutletQualifier}.
- Parameters:
- ctx: the parse tree
*/
func exitIbOutletQualifier(_ ctx: ObjectiveCParser.IbOutletQualifierContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#arcBehaviourSpecifier}.
- Parameters:
- ctx: the parse tree
*/
func enterArcBehaviourSpecifier(_ ctx: ObjectiveCParser.ArcBehaviourSpecifierContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#arcBehaviourSpecifier}.
- Parameters:
- ctx: the parse tree
*/
func exitArcBehaviourSpecifier(_ ctx: ObjectiveCParser.ArcBehaviourSpecifierContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#nullabilitySpecifier}.
- Parameters:
- ctx: the parse tree
*/
func enterNullabilitySpecifier(_ ctx: ObjectiveCParser.NullabilitySpecifierContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#nullabilitySpecifier}.
- Parameters:
- ctx: the parse tree
*/
func exitNullabilitySpecifier(_ ctx: ObjectiveCParser.NullabilitySpecifierContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#storageClassSpecifier}.
- Parameters:
- ctx: the parse tree
*/
func enterStorageClassSpecifier(_ ctx: ObjectiveCParser.StorageClassSpecifierContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#storageClassSpecifier}.
- Parameters:
- ctx: the parse tree
*/
func exitStorageClassSpecifier(_ ctx: ObjectiveCParser.StorageClassSpecifierContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#typePrefix}.
- Parameters:
- ctx: the parse tree
*/
func enterTypePrefix(_ ctx: ObjectiveCParser.TypePrefixContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#typePrefix}.
- Parameters:
- ctx: the parse tree
*/
func exitTypePrefix(_ ctx: ObjectiveCParser.TypePrefixContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#typeQualifier}.
- Parameters:
- ctx: the parse tree
*/
func enterTypeQualifier(_ ctx: ObjectiveCParser.TypeQualifierContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#typeQualifier}.
- Parameters:
- ctx: the parse tree
*/
func exitTypeQualifier(_ ctx: ObjectiveCParser.TypeQualifierContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#protocolQualifier}.
- Parameters:
- ctx: the parse tree
*/
func enterProtocolQualifier(_ ctx: ObjectiveCParser.ProtocolQualifierContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#protocolQualifier}.
- Parameters:
- ctx: the parse tree
*/
func exitProtocolQualifier(_ ctx: ObjectiveCParser.ProtocolQualifierContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#typeSpecifier}.
- Parameters:
- ctx: the parse tree
*/
func enterTypeSpecifier(_ ctx: ObjectiveCParser.TypeSpecifierContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#typeSpecifier}.
- Parameters:
- ctx: the parse tree
*/
func exitTypeSpecifier(_ ctx: ObjectiveCParser.TypeSpecifierContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#scalarTypeSpecifier}.
- Parameters:
- ctx: the parse tree
*/
func enterScalarTypeSpecifier(_ ctx: ObjectiveCParser.ScalarTypeSpecifierContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#scalarTypeSpecifier}.
- Parameters:
- ctx: the parse tree
*/
func exitScalarTypeSpecifier(_ ctx: ObjectiveCParser.ScalarTypeSpecifierContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#typeofExpression}.
- Parameters:
- ctx: the parse tree
*/
func enterTypeofExpression(_ ctx: ObjectiveCParser.TypeofExpressionContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#typeofExpression}.
- Parameters:
- ctx: the parse tree
*/
func exitTypeofExpression(_ ctx: ObjectiveCParser.TypeofExpressionContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#fieldDeclaratorList}.
- Parameters:
- ctx: the parse tree
*/
func enterFieldDeclaratorList(_ ctx: ObjectiveCParser.FieldDeclaratorListContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#fieldDeclaratorList}.
- Parameters:
- ctx: the parse tree
*/
func exitFieldDeclaratorList(_ ctx: ObjectiveCParser.FieldDeclaratorListContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#fieldDeclarator}.
- Parameters:
- ctx: the parse tree
*/
func enterFieldDeclarator(_ ctx: ObjectiveCParser.FieldDeclaratorContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#fieldDeclarator}.
- Parameters:
- ctx: the parse tree
*/
func exitFieldDeclarator(_ ctx: ObjectiveCParser.FieldDeclaratorContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#enumSpecifier}.
- Parameters:
- ctx: the parse tree
*/
func enterEnumSpecifier(_ ctx: ObjectiveCParser.EnumSpecifierContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#enumSpecifier}.
- Parameters:
- ctx: the parse tree
*/
func exitEnumSpecifier(_ ctx: ObjectiveCParser.EnumSpecifierContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#enumeratorList}.
- Parameters:
- ctx: the parse tree
*/
func enterEnumeratorList(_ ctx: ObjectiveCParser.EnumeratorListContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#enumeratorList}.
- Parameters:
- ctx: the parse tree
*/
func exitEnumeratorList(_ ctx: ObjectiveCParser.EnumeratorListContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#enumerator}.
- Parameters:
- ctx: the parse tree
*/
func enterEnumerator(_ ctx: ObjectiveCParser.EnumeratorContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#enumerator}.
- Parameters:
- ctx: the parse tree
*/
func exitEnumerator(_ ctx: ObjectiveCParser.EnumeratorContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#enumeratorIdentifier}.
- Parameters:
- ctx: the parse tree
*/
func enterEnumeratorIdentifier(_ ctx: ObjectiveCParser.EnumeratorIdentifierContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#enumeratorIdentifier}.
- Parameters:
- ctx: the parse tree
*/
func exitEnumeratorIdentifier(_ ctx: ObjectiveCParser.EnumeratorIdentifierContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#directDeclarator}.
- Parameters:
- ctx: the parse tree
*/
func enterDirectDeclarator(_ ctx: ObjectiveCParser.DirectDeclaratorContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#directDeclarator}.
- Parameters:
- ctx: the parse tree
*/
func exitDirectDeclarator(_ ctx: ObjectiveCParser.DirectDeclaratorContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#declaratorSuffix}.
- Parameters:
- ctx: the parse tree
*/
func enterDeclaratorSuffix(_ ctx: ObjectiveCParser.DeclaratorSuffixContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#declaratorSuffix}.
- Parameters:
- ctx: the parse tree
*/
func exitDeclaratorSuffix(_ ctx: ObjectiveCParser.DeclaratorSuffixContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#parameterList}.
- Parameters:
- ctx: the parse tree
*/
func enterParameterList(_ ctx: ObjectiveCParser.ParameterListContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#parameterList}.
- Parameters:
- ctx: the parse tree
*/
func exitParameterList(_ ctx: ObjectiveCParser.ParameterListContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#pointer}.
- Parameters:
- ctx: the parse tree
*/
func enterPointer(_ ctx: ObjectiveCParser.PointerContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#pointer}.
- Parameters:
- ctx: the parse tree
*/
func exitPointer(_ ctx: ObjectiveCParser.PointerContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#macro}.
- Parameters:
- ctx: the parse tree
*/
func enterMacro(_ ctx: ObjectiveCParser.MacroContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#macro}.
- Parameters:
- ctx: the parse tree
*/
func exitMacro(_ ctx: ObjectiveCParser.MacroContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#arrayInitializer}.
- Parameters:
- ctx: the parse tree
*/
func enterArrayInitializer(_ ctx: ObjectiveCParser.ArrayInitializerContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#arrayInitializer}.
- Parameters:
- ctx: the parse tree
*/
func exitArrayInitializer(_ ctx: ObjectiveCParser.ArrayInitializerContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#structInitializer}.
- Parameters:
- ctx: the parse tree
*/
func enterStructInitializer(_ ctx: ObjectiveCParser.StructInitializerContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#structInitializer}.
- Parameters:
- ctx: the parse tree
*/
func exitStructInitializer(_ ctx: ObjectiveCParser.StructInitializerContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#structInitializerItem}.
- Parameters:
- ctx: the parse tree
*/
func enterStructInitializerItem(_ ctx: ObjectiveCParser.StructInitializerItemContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#structInitializerItem}.
- Parameters:
- ctx: the parse tree
*/
func exitStructInitializerItem(_ ctx: ObjectiveCParser.StructInitializerItemContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#initializerList}.
- Parameters:
- ctx: the parse tree
*/
func enterInitializerList(_ ctx: ObjectiveCParser.InitializerListContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#initializerList}.
- Parameters:
- ctx: the parse tree
*/
func exitInitializerList(_ ctx: ObjectiveCParser.InitializerListContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#typeName}.
- Parameters:
- ctx: the parse tree
*/
func enterTypeName(_ ctx: ObjectiveCParser.TypeNameContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#typeName}.
- Parameters:
- ctx: the parse tree
*/
func exitTypeName(_ ctx: ObjectiveCParser.TypeNameContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#abstractDeclarator}.
- Parameters:
- ctx: the parse tree
*/
func enterAbstractDeclarator(_ ctx: ObjectiveCParser.AbstractDeclaratorContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#abstractDeclarator}.
- Parameters:
- ctx: the parse tree
*/
func exitAbstractDeclarator(_ ctx: ObjectiveCParser.AbstractDeclaratorContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#abstractDeclaratorSuffix}.
- Parameters:
- ctx: the parse tree
*/
func enterAbstractDeclaratorSuffix(_ ctx: ObjectiveCParser.AbstractDeclaratorSuffixContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#abstractDeclaratorSuffix}.
- Parameters:
- ctx: the parse tree
*/
func exitAbstractDeclaratorSuffix(_ ctx: ObjectiveCParser.AbstractDeclaratorSuffixContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#parameterDeclarationList}.
- Parameters:
- ctx: the parse tree
*/
func enterParameterDeclarationList(_ ctx: ObjectiveCParser.ParameterDeclarationListContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#parameterDeclarationList}.
- Parameters:
- ctx: the parse tree
*/
func exitParameterDeclarationList(_ ctx: ObjectiveCParser.ParameterDeclarationListContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#parameterDeclaration}.
- Parameters:
- ctx: the parse tree
*/
func enterParameterDeclaration(_ ctx: ObjectiveCParser.ParameterDeclarationContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#parameterDeclaration}.
- Parameters:
- ctx: the parse tree
*/
func exitParameterDeclaration(_ ctx: ObjectiveCParser.ParameterDeclarationContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#declarator}.
- Parameters:
- ctx: the parse tree
*/
func enterDeclarator(_ ctx: ObjectiveCParser.DeclaratorContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#declarator}.
- Parameters:
- ctx: the parse tree
*/
func exitDeclarator(_ ctx: ObjectiveCParser.DeclaratorContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#statement}.
- Parameters:
- ctx: the parse tree
*/
func enterStatement(_ ctx: ObjectiveCParser.StatementContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#statement}.
- Parameters:
- ctx: the parse tree
*/
func exitStatement(_ ctx: ObjectiveCParser.StatementContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#labeledStatement}.
- Parameters:
- ctx: the parse tree
*/
func enterLabeledStatement(_ ctx: ObjectiveCParser.LabeledStatementContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#labeledStatement}.
- Parameters:
- ctx: the parse tree
*/
func exitLabeledStatement(_ ctx: ObjectiveCParser.LabeledStatementContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#rangeExpression}.
- Parameters:
- ctx: the parse tree
*/
func enterRangeExpression(_ ctx: ObjectiveCParser.RangeExpressionContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#rangeExpression}.
- Parameters:
- ctx: the parse tree
*/
func exitRangeExpression(_ ctx: ObjectiveCParser.RangeExpressionContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#compoundStatement}.
- Parameters:
- ctx: the parse tree
*/
func enterCompoundStatement(_ ctx: ObjectiveCParser.CompoundStatementContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#compoundStatement}.
- Parameters:
- ctx: the parse tree
*/
func exitCompoundStatement(_ ctx: ObjectiveCParser.CompoundStatementContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#selectionStatement}.
- Parameters:
- ctx: the parse tree
*/
func enterSelectionStatement(_ ctx: ObjectiveCParser.SelectionStatementContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#selectionStatement}.
- Parameters:
- ctx: the parse tree
*/
func exitSelectionStatement(_ ctx: ObjectiveCParser.SelectionStatementContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#switchStatement}.
- Parameters:
- ctx: the parse tree
*/
func enterSwitchStatement(_ ctx: ObjectiveCParser.SwitchStatementContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#switchStatement}.
- Parameters:
- ctx: the parse tree
*/
func exitSwitchStatement(_ ctx: ObjectiveCParser.SwitchStatementContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#switchBlock}.
- Parameters:
- ctx: the parse tree
*/
func enterSwitchBlock(_ ctx: ObjectiveCParser.SwitchBlockContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#switchBlock}.
- Parameters:
- ctx: the parse tree
*/
func exitSwitchBlock(_ ctx: ObjectiveCParser.SwitchBlockContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#switchSection}.
- Parameters:
- ctx: the parse tree
*/
func enterSwitchSection(_ ctx: ObjectiveCParser.SwitchSectionContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#switchSection}.
- Parameters:
- ctx: the parse tree
*/
func exitSwitchSection(_ ctx: ObjectiveCParser.SwitchSectionContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#switchLabel}.
- Parameters:
- ctx: the parse tree
*/
func enterSwitchLabel(_ ctx: ObjectiveCParser.SwitchLabelContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#switchLabel}.
- Parameters:
- ctx: the parse tree
*/
func exitSwitchLabel(_ ctx: ObjectiveCParser.SwitchLabelContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#iterationStatement}.
- Parameters:
- ctx: the parse tree
*/
func enterIterationStatement(_ ctx: ObjectiveCParser.IterationStatementContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#iterationStatement}.
- Parameters:
- ctx: the parse tree
*/
func exitIterationStatement(_ ctx: ObjectiveCParser.IterationStatementContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#whileStatement}.
- Parameters:
- ctx: the parse tree
*/
func enterWhileStatement(_ ctx: ObjectiveCParser.WhileStatementContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#whileStatement}.
- Parameters:
- ctx: the parse tree
*/
func exitWhileStatement(_ ctx: ObjectiveCParser.WhileStatementContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#doStatement}.
- Parameters:
- ctx: the parse tree
*/
func enterDoStatement(_ ctx: ObjectiveCParser.DoStatementContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#doStatement}.
- Parameters:
- ctx: the parse tree
*/
func exitDoStatement(_ ctx: ObjectiveCParser.DoStatementContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#forStatement}.
- Parameters:
- ctx: the parse tree
*/
func enterForStatement(_ ctx: ObjectiveCParser.ForStatementContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#forStatement}.
- Parameters:
- ctx: the parse tree
*/
func exitForStatement(_ ctx: ObjectiveCParser.ForStatementContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#forLoopInitializer}.
- Parameters:
- ctx: the parse tree
*/
func enterForLoopInitializer(_ ctx: ObjectiveCParser.ForLoopInitializerContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#forLoopInitializer}.
- Parameters:
- ctx: the parse tree
*/
func exitForLoopInitializer(_ ctx: ObjectiveCParser.ForLoopInitializerContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#forInStatement}.
- Parameters:
- ctx: the parse tree
*/
func enterForInStatement(_ ctx: ObjectiveCParser.ForInStatementContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#forInStatement}.
- Parameters:
- ctx: the parse tree
*/
func exitForInStatement(_ ctx: ObjectiveCParser.ForInStatementContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#jumpStatement}.
- Parameters:
- ctx: the parse tree
*/
func enterJumpStatement(_ ctx: ObjectiveCParser.JumpStatementContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#jumpStatement}.
- Parameters:
- ctx: the parse tree
*/
func exitJumpStatement(_ ctx: ObjectiveCParser.JumpStatementContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#expressions}.
- Parameters:
- ctx: the parse tree
*/
func enterExpressions(_ ctx: ObjectiveCParser.ExpressionsContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#expressions}.
- Parameters:
- ctx: the parse tree
*/
func exitExpressions(_ ctx: ObjectiveCParser.ExpressionsContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#expression}.
- Parameters:
- ctx: the parse tree
*/
func enterExpression(_ ctx: ObjectiveCParser.ExpressionContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#expression}.
- Parameters:
- ctx: the parse tree
*/
func exitExpression(_ ctx: ObjectiveCParser.ExpressionContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#assignmentOperator}.
- Parameters:
- ctx: the parse tree
*/
func enterAssignmentOperator(_ ctx: ObjectiveCParser.AssignmentOperatorContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#assignmentOperator}.
- Parameters:
- ctx: the parse tree
*/
func exitAssignmentOperator(_ ctx: ObjectiveCParser.AssignmentOperatorContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#castExpression}.
- Parameters:
- ctx: the parse tree
*/
func enterCastExpression(_ ctx: ObjectiveCParser.CastExpressionContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#castExpression}.
- Parameters:
- ctx: the parse tree
*/
func exitCastExpression(_ ctx: ObjectiveCParser.CastExpressionContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#initializer}.
- Parameters:
- ctx: the parse tree
*/
func enterInitializer(_ ctx: ObjectiveCParser.InitializerContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#initializer}.
- Parameters:
- ctx: the parse tree
*/
func exitInitializer(_ ctx: ObjectiveCParser.InitializerContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#constantExpression}.
- Parameters:
- ctx: the parse tree
*/
func enterConstantExpression(_ ctx: ObjectiveCParser.ConstantExpressionContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#constantExpression}.
- Parameters:
- ctx: the parse tree
*/
func exitConstantExpression(_ ctx: ObjectiveCParser.ConstantExpressionContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#unaryExpression}.
- Parameters:
- ctx: the parse tree
*/
func enterUnaryExpression(_ ctx: ObjectiveCParser.UnaryExpressionContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#unaryExpression}.
- Parameters:
- ctx: the parse tree
*/
func exitUnaryExpression(_ ctx: ObjectiveCParser.UnaryExpressionContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#unaryOperator}.
- Parameters:
- ctx: the parse tree
*/
func enterUnaryOperator(_ ctx: ObjectiveCParser.UnaryOperatorContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#unaryOperator}.
- Parameters:
- ctx: the parse tree
*/
func exitUnaryOperator(_ ctx: ObjectiveCParser.UnaryOperatorContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#postfixExpression}.
- Parameters:
- ctx: the parse tree
*/
func enterPostfixExpression(_ ctx: ObjectiveCParser.PostfixExpressionContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#postfixExpression}.
- Parameters:
- ctx: the parse tree
*/
func exitPostfixExpression(_ ctx: ObjectiveCParser.PostfixExpressionContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#postfixExpr}.
- Parameters:
- ctx: the parse tree
*/
func enterPostfixExpr(_ ctx: ObjectiveCParser.PostfixExprContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#postfixExpr}.
- Parameters:
- ctx: the parse tree
*/
func exitPostfixExpr(_ ctx: ObjectiveCParser.PostfixExprContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#argumentExpressionList}.
- Parameters:
- ctx: the parse tree
*/
func enterArgumentExpressionList(_ ctx: ObjectiveCParser.ArgumentExpressionListContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#argumentExpressionList}.
- Parameters:
- ctx: the parse tree
*/
func exitArgumentExpressionList(_ ctx: ObjectiveCParser.ArgumentExpressionListContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#argumentExpression}.
- Parameters:
- ctx: the parse tree
*/
func enterArgumentExpression(_ ctx: ObjectiveCParser.ArgumentExpressionContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#argumentExpression}.
- Parameters:
- ctx: the parse tree
*/
func exitArgumentExpression(_ ctx: ObjectiveCParser.ArgumentExpressionContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#primaryExpression}.
- Parameters:
- ctx: the parse tree
*/
func enterPrimaryExpression(_ ctx: ObjectiveCParser.PrimaryExpressionContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#primaryExpression}.
- Parameters:
- ctx: the parse tree
*/
func exitPrimaryExpression(_ ctx: ObjectiveCParser.PrimaryExpressionContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#constant}.
- Parameters:
- ctx: the parse tree
*/
func enterConstant(_ ctx: ObjectiveCParser.ConstantContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#constant}.
- Parameters:
- ctx: the parse tree
*/
func exitConstant(_ ctx: ObjectiveCParser.ConstantContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#stringLiteral}.
- Parameters:
- ctx: the parse tree
*/
func enterStringLiteral(_ ctx: ObjectiveCParser.StringLiteralContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#stringLiteral}.
- Parameters:
- ctx: the parse tree
*/
func exitStringLiteral(_ ctx: ObjectiveCParser.StringLiteralContext)
/**
* Enter a parse tree produced by {@link ObjectiveCParser#identifier}.
- Parameters:
- ctx: the parse tree
*/
func enterIdentifier(_ ctx: ObjectiveCParser.IdentifierContext)
/**
* Exit a parse tree produced by {@link ObjectiveCParser#identifier}.
- Parameters:
- ctx: the parse tree
*/
func exitIdentifier(_ ctx: ObjectiveCParser.IdentifierContext)
} | 34.830941 | 122 | 0.746692 |
8f0f44bd3485003dc830f9a1e9fc3a4eab9d56ab | 1,255 | //
// RLMBookTranslator.swift
// DAO
//
// Created by Ivan Vavilov on 5/17/17.
// Copyright © 2017 RedMadRobot LLC. All rights reserved.
//
import UIKit
import DAO
class RLMBookTranslator: RealmTranslator<Book, DBBook> {
required init() {}
override func fill(_ entity: Book, fromEntry: DBBook) {
entity.entityId = fromEntry.entryId
entity.name = fromEntry.name
entity.authors = fromEntry.authors.map { $0 }
entity.dates = fromEntry.dates.map { $0 }
entity.pages = fromEntry.pages.map { $0 }
entity.attachments = fromEntry.attachments.map { $0 }
}
override func fill(_ entry: DBBook, fromEntity: Book) {
if entry.entryId != fromEntity.entityId {
entry.entryId = fromEntity.entityId
}
entry.name = fromEntity.name
entry.authors.removeAll()
entry.dates.removeAll()
entry.pages.removeAll()
entry.attachments.removeAll()
entry.authors.append(objectsIn: fromEntity.authors)
entry.dates.append(objectsIn: fromEntity.dates)
entry.pages.append(objectsIn: fromEntity.pages)
entry.attachments.append(objectsIn: fromEntity.attachments)
}
}
| 27.282609 | 67 | 0.628685 |
5df8d497a8bf83725bb9fc3bd21aca1c0a72b255 | 2,331 | //
// UndoMiddleware.swift
// ReSwift-Todo
//
// Created by Christian Tietze on 15/09/16.
// Copyright © 2016 ReSwift. All rights reserved.
//
import Foundation
import ReSwift
class UndoableStateAdapter: UndoActionContext {
let state: ToDoListState
init(toDoListState: ToDoListState) {
self.state = toDoListState
}
var toDoListTitle: String? { return state.toDoList.title }
func toDoTitle(toDoID: ToDoID) -> String? {
return state.toDoList.toDo(toDoID: toDoID)?.title
}
func toDoInList(toDoID: ToDoID) -> ToDoInList? {
guard let index = state.toDoList.indexOf(toDoID: toDoID),
let toDo = state.toDoList.toDo(toDoID: toDoID)
else { return nil }
return (toDo, index)
}
}
extension UndoCommand {
convenience init?(appAction: UndoableAction, context: UndoActionContext, dispatch: @escaping DispatchFunction) {
guard let inverseAction = appAction.inverse(context: context)
else { return nil }
self.init(undoBlock: { _ = dispatch(inverseAction.notUndoable) },
undoName: appAction.name,
redoBlock: { _ = dispatch(appAction.notUndoable) })
}
}
func undoMiddleware(undoManager: UndoManager) -> Middleware<ToDoListState> {
func undoAction(action: UndoableAction, state: ToDoListState, dispatch: @escaping DispatchFunction) -> UndoCommand? {
let context = UndoableStateAdapter(toDoListState: state)
return UndoCommand(appAction: action, context: context, dispatch: dispatch)
}
let undoMiddleware: Middleware<ToDoListState> = { dispatch, getState in
return { next in
return { action in
// Pass already undone actions through
if let undoneAction = action as? NotUndoable {
next(undoneAction.action)
return
}
if let undoableAction = action as? UndoableAction , undoableAction.isUndoable,
let state = getState(),
let undo = undoAction(action: undoableAction, state: state, dispatch: dispatch) {
undo.register(undoManager: undoManager)
}
next(action)
}
}
}
return undoMiddleware
}
| 27.423529 | 121 | 0.620764 |
e08ab82f75a7815b69c6655d129e8fd13709cde6 | 523 | //
// PlaceMarker.swift
// eMOVE
//
// Created by Bogdan Matasaru on 09/09/2018.
// Copyright © 2018 Bogdan Matasaru. All rights reserved.
//
import Foundation
import GoogleMaps
class PlaceMarker: GMSMarker {
let place: PinPoint
init(place: PinPoint) {
self.place = place
super.init()
position = CLLocationCoordinate2D(latitude: place.latitude ?? 0.0, longitude: place.longitude ?? 0.0)
groundAnchor = CGPoint(x: 0.5, y: 1)
appearAnimation = .pop
}
}
| 21.791667 | 109 | 0.632887 |
b91d8e4b4526cbb936085377137bbf960f45efad | 319 | //
// ObserverWrapper.swift
//
// Created by Aldo Fuentes on 6/28/19.
// Copyright © 2019 aldofuentes. All rights reserved.
//
import Foundation
public struct ObserverWrapper2 {
public weak var observer: QueryObserver?
public init(_ observer: QueryObserver) {
self.observer = observer
}
}
| 18.764706 | 54 | 0.683386 |
01618c863d9f0c5a08ada072266971f0f8128193 | 2,085 | //
// RegistrationViewController.swift
// FloatingTextField_Example
//
// Created by Dmitriy Zhyzhko
// Copyright © 2019 CocoaPods. All rights reserved.
//
import Foundation
import FloatingLabelTextField
// MARK: - Lifecycle
final class RegistrationViewController: UIViewController {
@IBOutlet private weak var passwordFloatingTextField: FloatingLabelTextField!
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
override func viewDidLoad() {
super.viewDidLoad()
passwordFloatingTextField.addRightImages([UIImage.init(named: "eye")!.withTintColor(UIColor.white),
UIImage.init(named: "copy")!])
passwordFloatingTextField.delegate = self
passwordFloatingTextField.events.append() { event in
switch(event) {
case .didStartEditing( _): print("DidStartEditing")
case .didEndEditing( _): print("DidEndEditing")
case .didTextChanged( _): print("DidTextChanged")
case .didRightButtonPressed(let floatingTextField, let index, _):
if index == 0 {
floatingTextField.toggleTextFormat()
}
}
}
}
}
// MARK: - FloatingTextFieldDelegate
extension RegistrationViewController: FloatingLabelTextFieldDelegate {
func state(for floatingTextField: FloatingLabelTextField) -> (state: InputTextState, description: String?, color: UIColor) {
let textLength = floatingTextField.text.count
switch textLength {
case 1...2: return (.invalid, "Invalid", UIColor(hex: "ff3f4c"))
case 3...5: return (.unreliable, "Unreliable", UIColor(hex: "ff793f"))
case 6...8: return (.medium, "Medium", UIColor(hex: "f5a623"))
case 9...11: return (.reliable, "Reliable", UIColor(hex: "00ab80"))
case let number where number >= 12: return (.max, "Max", UIColor(hex: "00c99c"))
default: return (.idle, nil, .clear)
}
}
}
| 37.232143 | 128 | 0.627818 |
8f2b123b9bb9c1a2de1857c411f7b21e9f8c2f46 | 4,104 | import Combine
import Foundation
import WebKit
// MARK: - YouTubePlayerWebView
/// The YouTubePlayer WebView
final class YouTubePlayerWebView: WKWebView {
// MARK: Properties
/// The YouTubePlayer
var player: YouTubePlayer {
didSet {
// Verify YouTubePlayer reference has changed
guard self.player !== oldValue else {
// Otherwise return out of function
return
}
// Re-Load Player
self.loadPlayer()
}
}
/// The origin URL
private(set) lazy var originURL: URL? = Bundle
.main
.bundleIdentifier
.flatMap { ["https://", $0.lowercased()].joined() }
.flatMap(URL.init)
/// The frame observation Cancellable
private var frameObservation: AnyCancellable?
// MARK: Subjects
/// The YouTubePlayer State CurrentValueSubject
private(set) lazy var playerStateSubject = CurrentValueSubject<YouTubePlayer.State?, Never>(nil)
/// The YouTubePlayer PlaybackState CurrentValueSubject
private(set) lazy var playbackStateSubject = CurrentValueSubject<YouTubePlayer.PlaybackState?, Never>(nil)
/// The YouTubePlayer PlaybackQuality CurrentValueSubject
private(set) lazy var playbackQualitySubject = CurrentValueSubject<YouTubePlayer.PlaybackQuality?, Never>(nil)
/// The YouTubePlayer PlaybackRate CurrentValueSubject
private(set) lazy var playbackRateSubject = CurrentValueSubject<YouTubePlayer.PlaybackRate?, Never>(nil)
// MARK: Initializer
/// Creates a new instance of `YouTubePlayer.WebView`
/// - Parameter player: The YouTubePlayer
init(
player: YouTubePlayer
) {
// Set player
self.player = player
// Super init
super.init(
frame: .zero,
configuration: .youTubePlayer
)
// Setup
self.setup()
}
/// Initializer with NSCoder always returns nil
required init?(coder: NSCoder) {
nil
}
}
// MARK: - Setup
private extension YouTubePlayerWebView {
/// Setup YouTubePlayerWebView
func setup() {
// Setup frame observation
self.frameObservation = self
.publisher(for: \.frame)
.sink { [weak self] frame in
// Initialize parameters
let parameters = [
frame.width,
frame.height
]
.map(String.init)
.joined(separator: ",")
// Set YouTubePlayer Size
self?.evaluate(
javaScript: "setYouTubePlayerSize(\(parameters));"
)
}
// Set YouTubePlayerAPI on current Player
self.player.api = self
// Set navigation delegate
self.navigationDelegate = self
// Set ui delegate
self.uiDelegate = self
#if !os(macOS)
// Set clear background color
self.backgroundColor = .clear
// Disable opaque
self.isOpaque = false
// Set autoresizing masks
self.autoresizingMask = [.flexibleWidth, .flexibleHeight]
// Disable scrolling
self.scrollView.isScrollEnabled = false
// Disable bounces of ScrollView
self.scrollView.bounces = false
#endif
// Load YouTubePlayer
self.loadPlayer()
}
}
// MARK: - WKWebViewConfiguration+youTubePlayer
private extension WKWebViewConfiguration {
/// The YouTubePlayer WKWebViewConfiguration
static var youTubePlayer: WKWebViewConfiguration {
// Initialize WebView Configuration
let configuration = WKWebViewConfiguration()
#if !os(macOS)
// Allows inline media playback
configuration.allowsInlineMediaPlayback = true
#endif
// No media types requiring user action for playback
configuration.mediaTypesRequiringUserActionForPlayback = []
// Return configuration
return configuration
}
}
| 29.52518 | 114 | 0.604532 |
9bbc1e7bbfabeca7073136e632d50075bb3c090d | 2,587 | //
// SpringAnimation.swift
// ShotsDemo
//
// Created by Meng To on 2014-07-04.
// Copyright (c) 2014 Meng To. All rights reserved.
//
import UIKit
func spring(duration: NSTimeInterval, animations: (() -> Void)!) {
UIView.animateWithDuration(
duration,
delay: 0,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 0.7,
options: nil,
animations: {
animations()
}, completion: { finished in
})
}
func springEaseIn(duration: NSTimeInterval, animations: (() -> Void)!) {
UIView.animateWithDuration(
duration,
delay: 0,
options: UIViewAnimationOptions.CurveEaseIn,
animations: {
animations()
}, completion: { finished in
})
}
func springEaseOut(duration: NSTimeInterval, animations: (() -> Void)!) {
UIView.animateWithDuration(
duration,
delay: 0,
options: UIViewAnimationOptions.CurveEaseOut,
animations: {
animations()
}, completion: { finished in
})
}
func springEaseInOut(duration: NSTimeInterval, animations: (() -> Void)!) {
UIView.animateWithDuration(
duration,
delay: 0,
options: UIViewAnimationOptions.CurveEaseInOut,
animations: {
animations()
}, completion: { finished in
})
}
func springLinear(duration: NSTimeInterval, animations: (() -> Void)!) {
UIView.animateWithDuration(
duration,
delay: 0,
options: UIViewAnimationOptions.CurveLinear,
animations: {
animations()
}, completion: { finished in
})
}
func springWithDelay(duration: NSTimeInterval, delay: NSTimeInterval, animations: (() -> Void)!) {
UIView.animateWithDuration(
duration,
delay: delay,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 0.7,
options: nil,
animations: {
animations()
}, completion: { finished in
})
}
func springWithCompletion(duration: NSTimeInterval, animations: (() -> Void)!, completion: ((Bool) -> Void)!) {
UIView.animateWithDuration(
duration,
delay: 0,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 0.7,
options: nil,
animations: {
animations()
}, completion: { finished in
completion(true)
})
} | 22.893805 | 111 | 0.548125 |
e52c06d8e0378a268b9e080c015ca05d5bf80217 | 3,699 | //
// AppFlowCoordinatorTests.swift
// FlowCoordinatorUIKitTests
//
// Created by Rusty Zarse on 3/11/22.
//
import Combine
import FlowCoordinatorShared
import XCTest
@testable import FlowCoordinatorUIKit
class AppFlowCoordinatorTests: XCTestCase {
private var cancellables: [AnyCancellable] = []
private var testFixture: FlowCoordinatorTestFixture = FlowCoordinatorTestFixture()
@MainActor func makeAndStartTestAppFlowCoordinator(_ testFixture: FlowCoordinatorTestFixture) -> AppFlowCoordinator {
let appFlowCoordinator = AppFlowCoordinator(appState: testFixture.appState, serviceFactory: testFixture.serviceFactory)
let window = UIWindow()
appFlowCoordinator.configure(with: window)
appFlowCoordinator.start()
return appFlowCoordinator
}
override func setUpWithError() throws {
testFixture = FlowCoordinatorTestFixture()
}
@MainActor func testStart_verifyInitialNavigationStack() throws {
let appFlowCoordinator = self.makeAndStartTestAppFlowCoordinator(self.testFixture)
let rootViewController = appFlowCoordinator.rootViewController
XCTAssert(rootViewController is UITabBarController)
let viewControllers = (rootViewController as? UITabBarController)?.viewControllers ?? []
XCTAssertEqual(2, viewControllers.count)
XCTAssert(viewControllers[0] is HomeViewController)
let tab2VC = viewControllers[1]
XCTAssert(tab2VC is UINavigationController)
let tab2RootVC = (tab2VC as? UINavigationController)?.topViewController
XCTAssert(tab2RootVC is ProfileListViewController)
}
@MainActor func testSelectTab_verifyTabIsSelectedAndStateIsUpdated() throws {
let testFixture = self.testFixture
let appState = testFixture.appState
let appFlowCoordinator = self.makeAndStartTestAppFlowCoordinator(testFixture)
assertTab(.home, isSelectedBy: appFlowCoordinator)
XCTAssertEqual(Tab.home, appState.routing.selectedTab)
var updatedTab: Tab?
let expectation = self.expectation(description: "State Updated")
appState.$routing
.debounce(for: .milliseconds(100), scheduler: RunLoop.main)
.sink { routing in
updatedTab = routing.selectedTab
expectation.fulfill()
}
.store(in: &cancellables)
appFlowCoordinator.selectTab(.profile)
wait(for: [expectation], timeout: 2)
assertTab(.profile, isSelectedBy: appFlowCoordinator)
XCTAssertEqual(Tab.profile, updatedTab)
XCTAssertEqual(Tab.profile, appState.routing.selectedTab)
}
@MainActor func testPresentProfile_verifyProfileTabIsSelected() throws {
let appFlowCoordinator = self.makeAndStartTestAppFlowCoordinator(self.testFixture)
assertTab(.home, isSelectedBy: appFlowCoordinator)
appFlowCoordinator.presentProfile(profileID: "1")
assertTab(.profile, isSelectedBy: appFlowCoordinator)
}
@MainActor private func assertTab(_ tab: Tab, isSelectedBy appFlowCoordinator: AppFlowCoordinator, file: StaticString = #file, line: UInt = #line) {
guard let tabBarController = appFlowCoordinator.rootViewController as? UITabBarController else {
XCTFail("Expected rootViewController to be UITabBarController", file: file, line: line)
return
}
let selectedTabBarItem = tabBarController.tabBar.items?[tabBarController.selectedIndex]
XCTAssertEqual(tab.rawValue, selectedTabBarItem?.tag, "Selected tab tag [\(selectedTabBarItem?.tag ?? -1)] does not match `\(tab)` [\(tab.rawValue)]", file: file, line: line)
}
}
| 42.034091 | 182 | 0.723979 |
e5a5cafe1fc6591ae1ed955c99ba0df7f0959651 | 480 | import SwiftUI
import Swinject
extension ConfigEditor {
final class StateModel: BaseStateModel<Provider> {
var file: String = ""
@Published var configText = ""
override func subscribe() {
configText = provider.load(file: file)
}
func save() {
let impactHeavy = UIImpactFeedbackGenerator(style: .heavy)
impactHeavy.impactOccurred()
provider.save(configText, as: file)
}
}
}
| 24 | 70 | 0.595833 |
bf95d4a1eda17a8e843e9704a4750eaa04e9a775 | 264 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
import Foundation
struct A
}
extension NSSet {
{
{
{
}
}
{
}
}
enum A {
}
enum a<T
class A : a
| 12.571429 | 87 | 0.704545 |
18fd7046bca5c13372560480a27d8efe55d62639 | 530 | import UIKit.UIBezierPath
public extension UIBezierPath {
@discardableResult
static func imperative(_ imperative: ((Self) -> Void)) -> Self {
Self().imperative(imperative)
}
@discardableResult
func imperative(_ imperative: (Self) -> Void) -> Self {
imperative(self)
return self
}
@discardableResult
func stroke(_ color: UIColor, lineWidth: CGFloat) -> Self {
color.setStroke()
self.lineWidth = lineWidth
self.stroke()
return self
}
}
| 22.083333 | 68 | 0.618868 |
d987240db395e31b11e34b8325bd2e7481bbaa34 | 911 | //
// IndexedCollection.swift
// TaskList
//
// Created by Stephen Wall on 2/3/20.
// Copyright © 2020 Stephen Wall. All rights reserved.
//
public struct IndexedCollection<Base: RandomAccessCollection>: RandomAccessCollection {
let base: Base
public init(_ base: Base) {
self.base = base
}
}
//MARK: RandomAccessCollection
public extension IndexedCollection {
typealias Index = Base.Index
typealias Element = (index: Index, element: Base.Element)
var startIndex: Index { base.startIndex }
var endIndex: Index { base.endIndex }
func index(after i: Index) -> Index {
base.index(after: i)
}
func index(before i: Index) -> Index {
base.index(before: i)
}
func index(_ i: Index, offsetBy distance: Int) -> Index {
base.index(i, offsetBy: distance)
}
subscript(position: Index) -> Element {
(index: position, element: base[position])
}
}
| 21.186047 | 87 | 0.669594 |
e014118604164e503542eb6b17f47f5dec38b345 | 114,494 | /**
* Copyright IBM Corporation 2018
*
* 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
/**
The IBM Watson Assistant service combines machine learning, natural language understanding, and integrated dialog tools
to create conversation flows between your apps and your users.
*/
public class Assistant {
/// The base URL to use when contacting the service.
public var serviceURL = "https://gateway.watsonplatform.net/assistant/api"
/// The default HTTP headers for all requests to the service.
public var defaultHeaders = [String: String]()
private let credentials: Credentials
private let domain = "com.ibm.watson.developer-cloud.AssistantV1"
private let version: String
/**
Create a `Assistant` object.
- parameter username: The username used to authenticate with the service.
- parameter password: The password used to authenticate with the service.
- parameter version: The release date of the version of the API to use. Specify the date
in "YYYY-MM-DD" format.
*/
public init(username: String, password: String, version: String) {
self.credentials = .basicAuthentication(username: username, password: password)
self.version = version
}
/**
If the response or data represents an error returned by the Watson Assistant service,
then return NSError with information about the error that occured. Otherwise, return nil.
- parameter response: the URL response returned from the service.
- parameter data: Raw data returned from the service that may represent an error.
*/
private func responseToError(response: HTTPURLResponse?, data: Data?) -> NSError? {
// First check http status code in response
if let response = response {
if (200..<300).contains(response.statusCode) {
return nil
}
}
// ensure data is not nil
guard let data = data else {
if let code = response?.statusCode {
return NSError(domain: domain, code: code, userInfo: nil)
}
return nil // RestKit will generate error for this case
}
do {
let json = try JSONWrapper(data: data)
let code = response?.statusCode ?? 400
let message = try json.getString(at: "error")
let userInfo = [NSLocalizedDescriptionKey: message]
return NSError(domain: domain, code: code, userInfo: userInfo)
} catch {
return nil
}
}
/**
Get response to user input.
Get a response to a user's input. There is no rate limit for this operation.
- parameter workspaceID: Unique identifier of the workspace.
- parameter request: The message to be sent. This includes the user's input, along with optional intents, entities, and context from the
last response.
- parameter nodesVisitedDetails: Whether to include additional diagnostic information about the dialog nodes that were visited during processing of
the message.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func message(
workspaceID: String,
request: MessageRequest? = nil,
nodesVisitedDetails: Bool? = nil,
failure: ((Error) -> Void)? = nil,
success: @escaping (MessageResponse) -> Void)
{
// construct body
guard let body = try? JSONEncoder().encodeIfPresent(request) else {
failure?(RestError.serializationError)
return
}
// construct header parameters
var headers = defaultHeaders
headers["Accept"] = "application/json"
headers["Content-Type"] = "application/json"
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
if let nodesVisitedDetails = nodesVisitedDetails {
let queryParameter = URLQueryItem(name: "nodes_visited_details", value: "\(nodesVisitedDetails)")
queryParameters.append(queryParameter)
}
// construct REST request
let path = "/v1/workspaces/\(workspaceID)/message"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
failure?(RestError.encodingError)
return
}
let request = RestRequest(
method: "POST",
url: serviceURL + encodedPath,
credentials: credentials,
headerParameters: headers,
queryItems: queryParameters,
messageBody: body
)
// execute REST request
request.responseObject(responseToError: responseToError) {
(response: RestResponse<MessageResponse>) in
switch response.result {
case .success(let retval): success(retval)
case .failure(let error): failure?(error)
}
}
}
/**
List workspaces.
List the workspaces associated with a Watson Assistant service instance. This operation is limited to 500
requests per 30 minutes. For more information, see **Rate limiting**.
- parameter pageLimit: The number of records to return in each page of results.
- parameter includeCount: Whether to include information about the number of records returned.
- parameter sort: The attribute by which returned results will be sorted. To reverse the sort order, prefix the value with a minus
sign (`-`). Supported values are `name`, `updated`, and `workspace_id`.
- parameter cursor: A token identifying the page of results to retrieve.
- parameter includeAudit: Whether to include the audit properties (`created` and `updated` timestamps) in the response.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func listWorkspaces(
pageLimit: Int? = nil,
includeCount: Bool? = nil,
sort: String? = nil,
cursor: String? = nil,
includeAudit: Bool? = nil,
failure: ((Error) -> Void)? = nil,
success: @escaping (WorkspaceCollection) -> Void)
{
// construct header parameters
var headers = defaultHeaders
headers["Accept"] = "application/json"
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
if let pageLimit = pageLimit {
let queryParameter = URLQueryItem(name: "page_limit", value: "\(pageLimit)")
queryParameters.append(queryParameter)
}
if let includeCount = includeCount {
let queryParameter = URLQueryItem(name: "include_count", value: "\(includeCount)")
queryParameters.append(queryParameter)
}
if let sort = sort {
let queryParameter = URLQueryItem(name: "sort", value: sort)
queryParameters.append(queryParameter)
}
if let cursor = cursor {
let queryParameter = URLQueryItem(name: "cursor", value: cursor)
queryParameters.append(queryParameter)
}
if let includeAudit = includeAudit {
let queryParameter = URLQueryItem(name: "include_audit", value: "\(includeAudit)")
queryParameters.append(queryParameter)
}
// construct REST request
let request = RestRequest(
method: "GET",
url: serviceURL + "/v1/workspaces",
credentials: credentials,
headerParameters: headers,
queryItems: queryParameters
)
// execute REST request
request.responseObject(responseToError: responseToError) {
(response: RestResponse<WorkspaceCollection>) in
switch response.result {
case .success(let retval): success(retval)
case .failure(let error): failure?(error)
}
}
}
/**
Create workspace.
Create a workspace based on component objects. You must provide workspace components defining the content of the
new workspace. This operation is limited to 30 requests per 30 minutes. For more information, see **Rate
limiting**.
- parameter properties: The content of the new workspace. The maximum size for this data is 50MB. If you need to import a larger
workspace, consider importing the workspace without intents and entities and then adding them separately.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func createWorkspace(
properties: CreateWorkspace? = nil,
failure: ((Error) -> Void)? = nil,
success: @escaping (Workspace) -> Void)
{
// construct body
guard let body = try? JSONEncoder().encodeIfPresent(properties) else {
failure?(RestError.serializationError)
return
}
// construct header parameters
var headers = defaultHeaders
headers["Accept"] = "application/json"
headers["Content-Type"] = "application/json"
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
// construct REST request
let request = RestRequest(
method: "POST",
url: serviceURL + "/v1/workspaces",
credentials: credentials,
headerParameters: headers,
queryItems: queryParameters,
messageBody: body
)
// execute REST request
request.responseObject(responseToError: responseToError) {
(response: RestResponse<Workspace>) in
switch response.result {
case .success(let retval): success(retval)
case .failure(let error): failure?(error)
}
}
}
/**
Get information about a workspace.
Get information about a workspace, optionally including all workspace content. With **export**=`false`, this
operation is limited to 6000 requests per 5 minutes. With **export**=`true`, the limit is 20 requests per 30
minutes. For more information, see **Rate limiting**.
- parameter workspaceID: Unique identifier of the workspace.
- parameter export: Whether to include all element content in the returned data. If **export**=`false`, the returned data includes only
information about the element itself. If **export**=`true`, all content, including subelements, is included.
- parameter includeAudit: Whether to include the audit properties (`created` and `updated` timestamps) in the response.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func getWorkspace(
workspaceID: String,
export: Bool? = nil,
includeAudit: Bool? = nil,
failure: ((Error) -> Void)? = nil,
success: @escaping (WorkspaceExport) -> Void)
{
// construct header parameters
var headers = defaultHeaders
headers["Accept"] = "application/json"
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
if let export = export {
let queryParameter = URLQueryItem(name: "export", value: "\(export)")
queryParameters.append(queryParameter)
}
if let includeAudit = includeAudit {
let queryParameter = URLQueryItem(name: "include_audit", value: "\(includeAudit)")
queryParameters.append(queryParameter)
}
// construct REST request
let path = "/v1/workspaces/\(workspaceID)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
failure?(RestError.encodingError)
return
}
let request = RestRequest(
method: "GET",
url: serviceURL + encodedPath,
credentials: credentials,
headerParameters: headers,
queryItems: queryParameters
)
// execute REST request
request.responseObject(responseToError: responseToError) {
(response: RestResponse<WorkspaceExport>) in
switch response.result {
case .success(let retval): success(retval)
case .failure(let error): failure?(error)
}
}
}
/**
Update workspace.
Update an existing workspace with new or modified data. You must provide component objects defining the content of
the updated workspace. This operation is limited to 30 request per 30 minutes. For more information, see **Rate
limiting**.
- parameter workspaceID: Unique identifier of the workspace.
- parameter properties: Valid data defining the new and updated workspace content. The maximum size for this data is 50MB. If you need
to import a larger amount of workspace data, consider importing components such as intents and entities using
separate operations.
- parameter append: Whether the new data is to be appended to the existing data in the workspace. If **append**=`false`, elements
included in the new data completely replace the corresponding existing elements, including all subelements. For
example, if the new data includes **entities** and **append**=`false`, all existing entities in the workspace are
discarded and replaced with the new entities. If **append**=`true`, existing elements are preserved, and the new
elements are added. If any elements in the new data collide with existing elements, the update request fails.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func updateWorkspace(
workspaceID: String,
properties: UpdateWorkspace? = nil,
append: Bool? = nil,
failure: ((Error) -> Void)? = nil,
success: @escaping (Workspace) -> Void)
{
// construct body
guard let body = try? JSONEncoder().encodeIfPresent(properties) else {
failure?(RestError.serializationError)
return
}
// construct header parameters
var headers = defaultHeaders
headers["Accept"] = "application/json"
headers["Content-Type"] = "application/json"
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
if let append = append {
let queryParameter = URLQueryItem(name: "append", value: "\(append)")
queryParameters.append(queryParameter)
}
// construct REST request
let path = "/v1/workspaces/\(workspaceID)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
failure?(RestError.encodingError)
return
}
let request = RestRequest(
method: "POST",
url: serviceURL + encodedPath,
credentials: credentials,
headerParameters: headers,
queryItems: queryParameters,
messageBody: body
)
// execute REST request
request.responseObject(responseToError: responseToError) {
(response: RestResponse<Workspace>) in
switch response.result {
case .success(let retval): success(retval)
case .failure(let error): failure?(error)
}
}
}
/**
Delete workspace.
Delete a workspace from the service instance. This operation is limited to 30 requests per 30 minutes. For more
information, see **Rate limiting**.
- parameter workspaceID: Unique identifier of the workspace.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func deleteWorkspace(
workspaceID: String,
failure: ((Error) -> Void)? = nil,
success: @escaping () -> Void)
{
// construct header parameters
var headers = defaultHeaders
headers["Accept"] = "application/json"
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
// construct REST request
let path = "/v1/workspaces/\(workspaceID)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
failure?(RestError.encodingError)
return
}
let request = RestRequest(
method: "DELETE",
url: serviceURL + encodedPath,
credentials: credentials,
headerParameters: headers,
queryItems: queryParameters
)
// execute REST request
request.responseVoid(responseToError: responseToError) {
(response: RestResponse) in
switch response.result {
case .success: success()
case .failure(let error): failure?(error)
}
}
}
/**
List intents.
List the intents for a workspace. With **export**=`false`, this operation is limited to 2000 requests per 30
minutes. With **export**=`true`, the limit is 400 requests per 30 minutes. For more information, see **Rate
limiting**.
- parameter workspaceID: Unique identifier of the workspace.
- parameter export: Whether to include all element content in the returned data. If **export**=`false`, the returned data includes only
information about the element itself. If **export**=`true`, all content, including subelements, is included.
- parameter pageLimit: The number of records to return in each page of results.
- parameter includeCount: Whether to include information about the number of records returned.
- parameter sort: The attribute by which returned results will be sorted. To reverse the sort order, prefix the value with a minus
sign (`-`). Supported values are `name`, `updated`, and `workspace_id`.
- parameter cursor: A token identifying the page of results to retrieve.
- parameter includeAudit: Whether to include the audit properties (`created` and `updated` timestamps) in the response.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func listIntents(
workspaceID: String,
export: Bool? = nil,
pageLimit: Int? = nil,
includeCount: Bool? = nil,
sort: String? = nil,
cursor: String? = nil,
includeAudit: Bool? = nil,
failure: ((Error) -> Void)? = nil,
success: @escaping (IntentCollection) -> Void)
{
// construct header parameters
var headers = defaultHeaders
headers["Accept"] = "application/json"
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
if let export = export {
let queryParameter = URLQueryItem(name: "export", value: "\(export)")
queryParameters.append(queryParameter)
}
if let pageLimit = pageLimit {
let queryParameter = URLQueryItem(name: "page_limit", value: "\(pageLimit)")
queryParameters.append(queryParameter)
}
if let includeCount = includeCount {
let queryParameter = URLQueryItem(name: "include_count", value: "\(includeCount)")
queryParameters.append(queryParameter)
}
if let sort = sort {
let queryParameter = URLQueryItem(name: "sort", value: sort)
queryParameters.append(queryParameter)
}
if let cursor = cursor {
let queryParameter = URLQueryItem(name: "cursor", value: cursor)
queryParameters.append(queryParameter)
}
if let includeAudit = includeAudit {
let queryParameter = URLQueryItem(name: "include_audit", value: "\(includeAudit)")
queryParameters.append(queryParameter)
}
// construct REST request
let path = "/v1/workspaces/\(workspaceID)/intents"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
failure?(RestError.encodingError)
return
}
let request = RestRequest(
method: "GET",
url: serviceURL + encodedPath,
credentials: credentials,
headerParameters: headers,
queryItems: queryParameters
)
// execute REST request
request.responseObject(responseToError: responseToError) {
(response: RestResponse<IntentCollection>) in
switch response.result {
case .success(let retval): success(retval)
case .failure(let error): failure?(error)
}
}
}
/**
Create intent.
Create a new intent. This operation is limited to 2000 requests per 30 minutes. For more information, see **Rate
limiting**.
- parameter workspaceID: Unique identifier of the workspace.
- parameter intent: The name of the intent. This string must conform to the following restrictions: - It can contain only Unicode
alphanumeric, underscore, hyphen, and dot characters. - It cannot begin with the reserved prefix `sys-`. - It
must be no longer than 128 characters.
- parameter description: The description of the intent. This string cannot contain carriage return, newline, or tab characters, and it must
be no longer than 128 characters.
- parameter examples: An array of user input examples for the intent.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func createIntent(
workspaceID: String,
intent: String,
description: String? = nil,
examples: [CreateExample]? = nil,
failure: ((Error) -> Void)? = nil,
success: @escaping (Intent) -> Void)
{
// construct body
let createIntentRequest = CreateIntent(intent: intent, description: description, examples: examples)
guard let body = try? JSONEncoder().encode(createIntentRequest) else {
failure?(RestError.serializationError)
return
}
// construct header parameters
var headers = defaultHeaders
headers["Accept"] = "application/json"
headers["Content-Type"] = "application/json"
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
// construct REST request
let path = "/v1/workspaces/\(workspaceID)/intents"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
failure?(RestError.encodingError)
return
}
let request = RestRequest(
method: "POST",
url: serviceURL + encodedPath,
credentials: credentials,
headerParameters: headers,
queryItems: queryParameters,
messageBody: body
)
// execute REST request
request.responseObject(responseToError: responseToError) {
(response: RestResponse<Intent>) in
switch response.result {
case .success(let retval): success(retval)
case .failure(let error): failure?(error)
}
}
}
/**
Get intent.
Get information about an intent, optionally including all intent content. With **export**=`false`, this
operation is limited to 6000 requests per 5 minutes. With **export**=`true`, the limit is 400 requests per 30
minutes. For more information, see **Rate limiting**.
- parameter workspaceID: Unique identifier of the workspace.
- parameter intent: The intent name.
- parameter export: Whether to include all element content in the returned data. If **export**=`false`, the returned data includes only
information about the element itself. If **export**=`true`, all content, including subelements, is included.
- parameter includeAudit: Whether to include the audit properties (`created` and `updated` timestamps) in the response.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func getIntent(
workspaceID: String,
intent: String,
export: Bool? = nil,
includeAudit: Bool? = nil,
failure: ((Error) -> Void)? = nil,
success: @escaping (IntentExport) -> Void)
{
// construct header parameters
var headers = defaultHeaders
headers["Accept"] = "application/json"
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
if let export = export {
let queryParameter = URLQueryItem(name: "export", value: "\(export)")
queryParameters.append(queryParameter)
}
if let includeAudit = includeAudit {
let queryParameter = URLQueryItem(name: "include_audit", value: "\(includeAudit)")
queryParameters.append(queryParameter)
}
// construct REST request
let path = "/v1/workspaces/\(workspaceID)/intents/\(intent)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
failure?(RestError.encodingError)
return
}
let request = RestRequest(
method: "GET",
url: serviceURL + encodedPath,
credentials: credentials,
headerParameters: headers,
queryItems: queryParameters
)
// execute REST request
request.responseObject(responseToError: responseToError) {
(response: RestResponse<IntentExport>) in
switch response.result {
case .success(let retval): success(retval)
case .failure(let error): failure?(error)
}
}
}
/**
Update intent.
Update an existing intent with new or modified data. You must provide component objects defining the content of the
updated intent. This operation is limited to 2000 requests per 30 minutes. For more information, see **Rate
limiting**.
- parameter workspaceID: Unique identifier of the workspace.
- parameter intent: The intent name.
- parameter newIntent: The name of the intent. This string must conform to the following restrictions: - It can contain only Unicode
alphanumeric, underscore, hyphen, and dot characters. - It cannot begin with the reserved prefix `sys-`. - It
must be no longer than 128 characters.
- parameter newDescription: The description of the intent.
- parameter newExamples: An array of user input examples for the intent.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func updateIntent(
workspaceID: String,
intent: String,
newIntent: String? = nil,
newDescription: String? = nil,
newExamples: [CreateExample]? = nil,
failure: ((Error) -> Void)? = nil,
success: @escaping (Intent) -> Void)
{
// construct body
let updateIntentRequest = UpdateIntent(intent: newIntent, description: newDescription, examples: newExamples)
guard let body = try? JSONEncoder().encode(updateIntentRequest) else {
failure?(RestError.serializationError)
return
}
// construct header parameters
var headers = defaultHeaders
headers["Accept"] = "application/json"
headers["Content-Type"] = "application/json"
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
// construct REST request
let path = "/v1/workspaces/\(workspaceID)/intents/\(intent)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
failure?(RestError.encodingError)
return
}
let request = RestRequest(
method: "POST",
url: serviceURL + encodedPath,
credentials: credentials,
headerParameters: headers,
queryItems: queryParameters,
messageBody: body
)
// execute REST request
request.responseObject(responseToError: responseToError) {
(response: RestResponse<Intent>) in
switch response.result {
case .success(let retval): success(retval)
case .failure(let error): failure?(error)
}
}
}
/**
Delete intent.
Delete an intent from a workspace. This operation is limited to 2000 requests per 30 minutes. For more
information, see **Rate limiting**.
- parameter workspaceID: Unique identifier of the workspace.
- parameter intent: The intent name.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func deleteIntent(
workspaceID: String,
intent: String,
failure: ((Error) -> Void)? = nil,
success: @escaping () -> Void)
{
// construct header parameters
var headers = defaultHeaders
headers["Accept"] = "application/json"
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
// construct REST request
let path = "/v1/workspaces/\(workspaceID)/intents/\(intent)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
failure?(RestError.encodingError)
return
}
let request = RestRequest(
method: "DELETE",
url: serviceURL + encodedPath,
credentials: credentials,
headerParameters: headers,
queryItems: queryParameters
)
// execute REST request
request.responseVoid(responseToError: responseToError) {
(response: RestResponse) in
switch response.result {
case .success: success()
case .failure(let error): failure?(error)
}
}
}
/**
List user input examples.
List the user input examples for an intent. This operation is limited to 2500 requests per 30 minutes. For more
information, see **Rate limiting**.
- parameter workspaceID: Unique identifier of the workspace.
- parameter intent: The intent name.
- parameter pageLimit: The number of records to return in each page of results.
- parameter includeCount: Whether to include information about the number of records returned.
- parameter sort: The attribute by which returned results will be sorted. To reverse the sort order, prefix the value with a minus
sign (`-`). Supported values are `name`, `updated`, and `workspace_id`.
- parameter cursor: A token identifying the page of results to retrieve.
- parameter includeAudit: Whether to include the audit properties (`created` and `updated` timestamps) in the response.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func listExamples(
workspaceID: String,
intent: String,
pageLimit: Int? = nil,
includeCount: Bool? = nil,
sort: String? = nil,
cursor: String? = nil,
includeAudit: Bool? = nil,
failure: ((Error) -> Void)? = nil,
success: @escaping (ExampleCollection) -> Void)
{
// construct header parameters
var headers = defaultHeaders
headers["Accept"] = "application/json"
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
if let pageLimit = pageLimit {
let queryParameter = URLQueryItem(name: "page_limit", value: "\(pageLimit)")
queryParameters.append(queryParameter)
}
if let includeCount = includeCount {
let queryParameter = URLQueryItem(name: "include_count", value: "\(includeCount)")
queryParameters.append(queryParameter)
}
if let sort = sort {
let queryParameter = URLQueryItem(name: "sort", value: sort)
queryParameters.append(queryParameter)
}
if let cursor = cursor {
let queryParameter = URLQueryItem(name: "cursor", value: cursor)
queryParameters.append(queryParameter)
}
if let includeAudit = includeAudit {
let queryParameter = URLQueryItem(name: "include_audit", value: "\(includeAudit)")
queryParameters.append(queryParameter)
}
// construct REST request
let path = "/v1/workspaces/\(workspaceID)/intents/\(intent)/examples"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
failure?(RestError.encodingError)
return
}
let request = RestRequest(
method: "GET",
url: serviceURL + encodedPath,
credentials: credentials,
headerParameters: headers,
queryItems: queryParameters
)
// execute REST request
request.responseObject(responseToError: responseToError) {
(response: RestResponse<ExampleCollection>) in
switch response.result {
case .success(let retval): success(retval)
case .failure(let error): failure?(error)
}
}
}
/**
Create user input example.
Add a new user input example to an intent. This operation is limited to 1000 requests per 30 minutes. For more
information, see **Rate limiting**.
- parameter workspaceID: Unique identifier of the workspace.
- parameter intent: The intent name.
- parameter text: The text of a user input example. This string must conform to the following restrictions: - It cannot contain
carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - It must be no
longer than 1024 characters.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func createExample(
workspaceID: String,
intent: String,
text: String,
failure: ((Error) -> Void)? = nil,
success: @escaping (Example) -> Void)
{
// construct body
let createExampleRequest = CreateExample(text: text)
guard let body = try? JSONEncoder().encode(createExampleRequest) else {
failure?(RestError.serializationError)
return
}
// construct header parameters
var headers = defaultHeaders
headers["Accept"] = "application/json"
headers["Content-Type"] = "application/json"
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
// construct REST request
let path = "/v1/workspaces/\(workspaceID)/intents/\(intent)/examples"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
failure?(RestError.encodingError)
return
}
let request = RestRequest(
method: "POST",
url: serviceURL + encodedPath,
credentials: credentials,
headerParameters: headers,
queryItems: queryParameters,
messageBody: body
)
// execute REST request
request.responseObject(responseToError: responseToError) {
(response: RestResponse<Example>) in
switch response.result {
case .success(let retval): success(retval)
case .failure(let error): failure?(error)
}
}
}
/**
Get user input example.
Get information about a user input example. This operation is limited to 6000 requests per 5 minutes. For more
information, see **Rate limiting**.
- parameter workspaceID: Unique identifier of the workspace.
- parameter intent: The intent name.
- parameter text: The text of the user input example.
- parameter includeAudit: Whether to include the audit properties (`created` and `updated` timestamps) in the response.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func getExample(
workspaceID: String,
intent: String,
text: String,
includeAudit: Bool? = nil,
failure: ((Error) -> Void)? = nil,
success: @escaping (Example) -> Void)
{
// construct header parameters
var headers = defaultHeaders
headers["Accept"] = "application/json"
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
if let includeAudit = includeAudit {
let queryParameter = URLQueryItem(name: "include_audit", value: "\(includeAudit)")
queryParameters.append(queryParameter)
}
// construct REST request
let path = "/v1/workspaces/\(workspaceID)/intents/\(intent)/examples/\(text)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
failure?(RestError.encodingError)
return
}
let request = RestRequest(
method: "GET",
url: serviceURL + encodedPath,
credentials: credentials,
headerParameters: headers,
queryItems: queryParameters
)
// execute REST request
request.responseObject(responseToError: responseToError) {
(response: RestResponse<Example>) in
switch response.result {
case .success(let retval): success(retval)
case .failure(let error): failure?(error)
}
}
}
/**
Update user input example.
Update the text of a user input example. This operation is limited to 1000 requests per 30 minutes. For more
information, see **Rate limiting**.
- parameter workspaceID: Unique identifier of the workspace.
- parameter intent: The intent name.
- parameter text: The text of the user input example.
- parameter newText: The text of the user input example. This string must conform to the following restrictions: - It cannot contain
carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - It must be no
longer than 1024 characters.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func updateExample(
workspaceID: String,
intent: String,
text: String,
newText: String? = nil,
failure: ((Error) -> Void)? = nil,
success: @escaping (Example) -> Void)
{
// construct body
let updateExampleRequest = UpdateExample(text: newText)
guard let body = try? JSONEncoder().encode(updateExampleRequest) else {
failure?(RestError.serializationError)
return
}
// construct header parameters
var headers = defaultHeaders
headers["Accept"] = "application/json"
headers["Content-Type"] = "application/json"
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
// construct REST request
let path = "/v1/workspaces/\(workspaceID)/intents/\(intent)/examples/\(text)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
failure?(RestError.encodingError)
return
}
let request = RestRequest(
method: "POST",
url: serviceURL + encodedPath,
credentials: credentials,
headerParameters: headers,
queryItems: queryParameters,
messageBody: body
)
// execute REST request
request.responseObject(responseToError: responseToError) {
(response: RestResponse<Example>) in
switch response.result {
case .success(let retval): success(retval)
case .failure(let error): failure?(error)
}
}
}
/**
Delete user input example.
Delete a user input example from an intent. This operation is limited to 1000 requests per 30 minutes. For more
information, see **Rate limiting**.
- parameter workspaceID: Unique identifier of the workspace.
- parameter intent: The intent name.
- parameter text: The text of the user input example.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func deleteExample(
workspaceID: String,
intent: String,
text: String,
failure: ((Error) -> Void)? = nil,
success: @escaping () -> Void)
{
// construct header parameters
var headers = defaultHeaders
headers["Accept"] = "application/json"
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
// construct REST request
let path = "/v1/workspaces/\(workspaceID)/intents/\(intent)/examples/\(text)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
failure?(RestError.encodingError)
return
}
let request = RestRequest(
method: "DELETE",
url: serviceURL + encodedPath,
credentials: credentials,
headerParameters: headers,
queryItems: queryParameters
)
// execute REST request
request.responseVoid(responseToError: responseToError) {
(response: RestResponse) in
switch response.result {
case .success: success()
case .failure(let error): failure?(error)
}
}
}
/**
List counterexamples.
List the counterexamples for a workspace. Counterexamples are examples that have been marked as irrelevant input.
This operation is limited to 2500 requests per 30 minutes. For more information, see **Rate limiting**.
- parameter workspaceID: Unique identifier of the workspace.
- parameter pageLimit: The number of records to return in each page of results.
- parameter includeCount: Whether to include information about the number of records returned.
- parameter sort: The attribute by which returned results will be sorted. To reverse the sort order, prefix the value with a minus
sign (`-`). Supported values are `name`, `updated`, and `workspace_id`.
- parameter cursor: A token identifying the page of results to retrieve.
- parameter includeAudit: Whether to include the audit properties (`created` and `updated` timestamps) in the response.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func listCounterexamples(
workspaceID: String,
pageLimit: Int? = nil,
includeCount: Bool? = nil,
sort: String? = nil,
cursor: String? = nil,
includeAudit: Bool? = nil,
failure: ((Error) -> Void)? = nil,
success: @escaping (CounterexampleCollection) -> Void)
{
// construct header parameters
var headers = defaultHeaders
headers["Accept"] = "application/json"
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
if let pageLimit = pageLimit {
let queryParameter = URLQueryItem(name: "page_limit", value: "\(pageLimit)")
queryParameters.append(queryParameter)
}
if let includeCount = includeCount {
let queryParameter = URLQueryItem(name: "include_count", value: "\(includeCount)")
queryParameters.append(queryParameter)
}
if let sort = sort {
let queryParameter = URLQueryItem(name: "sort", value: sort)
queryParameters.append(queryParameter)
}
if let cursor = cursor {
let queryParameter = URLQueryItem(name: "cursor", value: cursor)
queryParameters.append(queryParameter)
}
if let includeAudit = includeAudit {
let queryParameter = URLQueryItem(name: "include_audit", value: "\(includeAudit)")
queryParameters.append(queryParameter)
}
// construct REST request
let path = "/v1/workspaces/\(workspaceID)/counterexamples"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
failure?(RestError.encodingError)
return
}
let request = RestRequest(
method: "GET",
url: serviceURL + encodedPath,
credentials: credentials,
headerParameters: headers,
queryItems: queryParameters
)
// execute REST request
request.responseObject(responseToError: responseToError) {
(response: RestResponse<CounterexampleCollection>) in
switch response.result {
case .success(let retval): success(retval)
case .failure(let error): failure?(error)
}
}
}
/**
Create counterexample.
Add a new counterexample to a workspace. Counterexamples are examples that have been marked as irrelevant input.
This operation is limited to 1000 requests per 30 minutes. For more information, see **Rate limiting**.
- parameter workspaceID: Unique identifier of the workspace.
- parameter text: The text of a user input marked as irrelevant input. This string must conform to the following restrictions: - It
cannot contain carriage return, newline, or tab characters - It cannot consist of only whitespace characters - It
must be no longer than 1024 characters.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func createCounterexample(
workspaceID: String,
text: String,
failure: ((Error) -> Void)? = nil,
success: @escaping (Counterexample) -> Void)
{
// construct body
let createCounterexampleRequest = CreateCounterexample(text: text)
guard let body = try? JSONEncoder().encode(createCounterexampleRequest) else {
failure?(RestError.serializationError)
return
}
// construct header parameters
var headers = defaultHeaders
headers["Accept"] = "application/json"
headers["Content-Type"] = "application/json"
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
// construct REST request
let path = "/v1/workspaces/\(workspaceID)/counterexamples"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
failure?(RestError.encodingError)
return
}
let request = RestRequest(
method: "POST",
url: serviceURL + encodedPath,
credentials: credentials,
headerParameters: headers,
queryItems: queryParameters,
messageBody: body
)
// execute REST request
request.responseObject(responseToError: responseToError) {
(response: RestResponse<Counterexample>) in
switch response.result {
case .success(let retval): success(retval)
case .failure(let error): failure?(error)
}
}
}
/**
Get counterexample.
Get information about a counterexample. Counterexamples are examples that have been marked as irrelevant input.
This operation is limited to 6000 requests per 5 minutes. For more information, see **Rate limiting**.
- parameter workspaceID: Unique identifier of the workspace.
- parameter text: The text of a user input counterexample (for example, `What are you wearing?`).
- parameter includeAudit: Whether to include the audit properties (`created` and `updated` timestamps) in the response.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func getCounterexample(
workspaceID: String,
text: String,
includeAudit: Bool? = nil,
failure: ((Error) -> Void)? = nil,
success: @escaping (Counterexample) -> Void)
{
// construct header parameters
var headers = defaultHeaders
headers["Accept"] = "application/json"
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
if let includeAudit = includeAudit {
let queryParameter = URLQueryItem(name: "include_audit", value: "\(includeAudit)")
queryParameters.append(queryParameter)
}
// construct REST request
let path = "/v1/workspaces/\(workspaceID)/counterexamples/\(text)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
failure?(RestError.encodingError)
return
}
let request = RestRequest(
method: "GET",
url: serviceURL + encodedPath,
credentials: credentials,
headerParameters: headers,
queryItems: queryParameters
)
// execute REST request
request.responseObject(responseToError: responseToError) {
(response: RestResponse<Counterexample>) in
switch response.result {
case .success(let retval): success(retval)
case .failure(let error): failure?(error)
}
}
}
/**
Update counterexample.
Update the text of a counterexample. Counterexamples are examples that have been marked as irrelevant input.
This operation is limited to 1000 requests per 30 minutes. For more information, see **Rate limiting**.
- parameter workspaceID: Unique identifier of the workspace.
- parameter text: The text of a user input counterexample (for example, `What are you wearing?`).
- parameter newText: The text of a user input counterexample.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func updateCounterexample(
workspaceID: String,
text: String,
newText: String? = nil,
failure: ((Error) -> Void)? = nil,
success: @escaping (Counterexample) -> Void)
{
// construct body
let updateCounterexampleRequest = UpdateCounterexample(text: newText)
guard let body = try? JSONEncoder().encode(updateCounterexampleRequest) else {
failure?(RestError.serializationError)
return
}
// construct header parameters
var headers = defaultHeaders
headers["Accept"] = "application/json"
headers["Content-Type"] = "application/json"
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
// construct REST request
let path = "/v1/workspaces/\(workspaceID)/counterexamples/\(text)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
failure?(RestError.encodingError)
return
}
let request = RestRequest(
method: "POST",
url: serviceURL + encodedPath,
credentials: credentials,
headerParameters: headers,
queryItems: queryParameters,
messageBody: body
)
// execute REST request
request.responseObject(responseToError: responseToError) {
(response: RestResponse<Counterexample>) in
switch response.result {
case .success(let retval): success(retval)
case .failure(let error): failure?(error)
}
}
}
/**
Delete counterexample.
Delete a counterexample from a workspace. Counterexamples are examples that have been marked as irrelevant input.
This operation is limited to 1000 requests per 30 minutes. For more information, see **Rate limiting**.
- parameter workspaceID: Unique identifier of the workspace.
- parameter text: The text of a user input counterexample (for example, `What are you wearing?`).
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func deleteCounterexample(
workspaceID: String,
text: String,
failure: ((Error) -> Void)? = nil,
success: @escaping () -> Void)
{
// construct header parameters
var headers = defaultHeaders
headers["Accept"] = "application/json"
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
// construct REST request
let path = "/v1/workspaces/\(workspaceID)/counterexamples/\(text)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
failure?(RestError.encodingError)
return
}
let request = RestRequest(
method: "DELETE",
url: serviceURL + encodedPath,
credentials: credentials,
headerParameters: headers,
queryItems: queryParameters
)
// execute REST request
request.responseVoid(responseToError: responseToError) {
(response: RestResponse) in
switch response.result {
case .success: success()
case .failure(let error): failure?(error)
}
}
}
/**
List entities.
List the entities for a workspace. With **export**=`false`, this operation is limited to 1000 requests per 30
minutes. With **export**=`true`, the limit is 200 requests per 30 minutes. For more information, see **Rate
limiting**.
- parameter workspaceID: Unique identifier of the workspace.
- parameter export: Whether to include all element content in the returned data. If **export**=`false`, the returned data includes only
information about the element itself. If **export**=`true`, all content, including subelements, is included.
- parameter pageLimit: The number of records to return in each page of results.
- parameter includeCount: Whether to include information about the number of records returned.
- parameter sort: The attribute by which returned results will be sorted. To reverse the sort order, prefix the value with a minus
sign (`-`). Supported values are `name`, `updated`, and `workspace_id`.
- parameter cursor: A token identifying the page of results to retrieve.
- parameter includeAudit: Whether to include the audit properties (`created` and `updated` timestamps) in the response.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func listEntities(
workspaceID: String,
export: Bool? = nil,
pageLimit: Int? = nil,
includeCount: Bool? = nil,
sort: String? = nil,
cursor: String? = nil,
includeAudit: Bool? = nil,
failure: ((Error) -> Void)? = nil,
success: @escaping (EntityCollection) -> Void)
{
// construct header parameters
var headers = defaultHeaders
headers["Accept"] = "application/json"
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
if let export = export {
let queryParameter = URLQueryItem(name: "export", value: "\(export)")
queryParameters.append(queryParameter)
}
if let pageLimit = pageLimit {
let queryParameter = URLQueryItem(name: "page_limit", value: "\(pageLimit)")
queryParameters.append(queryParameter)
}
if let includeCount = includeCount {
let queryParameter = URLQueryItem(name: "include_count", value: "\(includeCount)")
queryParameters.append(queryParameter)
}
if let sort = sort {
let queryParameter = URLQueryItem(name: "sort", value: sort)
queryParameters.append(queryParameter)
}
if let cursor = cursor {
let queryParameter = URLQueryItem(name: "cursor", value: cursor)
queryParameters.append(queryParameter)
}
if let includeAudit = includeAudit {
let queryParameter = URLQueryItem(name: "include_audit", value: "\(includeAudit)")
queryParameters.append(queryParameter)
}
// construct REST request
let path = "/v1/workspaces/\(workspaceID)/entities"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
failure?(RestError.encodingError)
return
}
let request = RestRequest(
method: "GET",
url: serviceURL + encodedPath,
credentials: credentials,
headerParameters: headers,
queryItems: queryParameters
)
// execute REST request
request.responseObject(responseToError: responseToError) {
(response: RestResponse<EntityCollection>) in
switch response.result {
case .success(let retval): success(retval)
case .failure(let error): failure?(error)
}
}
}
/**
Create entity.
Create a new entity. This operation is limited to 1000 requests per 30 minutes. For more information, see **Rate
limiting**.
- parameter workspaceID: Unique identifier of the workspace.
- parameter properties: The content of the new entity.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func createEntity(
workspaceID: String,
properties: CreateEntity,
failure: ((Error) -> Void)? = nil,
success: @escaping (Entity) -> Void)
{
// construct body
guard let body = try? JSONEncoder().encode(properties) else {
failure?(RestError.serializationError)
return
}
// construct header parameters
var headers = defaultHeaders
headers["Accept"] = "application/json"
headers["Content-Type"] = "application/json"
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
// construct REST request
let path = "/v1/workspaces/\(workspaceID)/entities"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
failure?(RestError.encodingError)
return
}
let request = RestRequest(
method: "POST",
url: serviceURL + encodedPath,
credentials: credentials,
headerParameters: headers,
queryItems: queryParameters,
messageBody: body
)
// execute REST request
request.responseObject(responseToError: responseToError) {
(response: RestResponse<Entity>) in
switch response.result {
case .success(let retval): success(retval)
case .failure(let error): failure?(error)
}
}
}
/**
Get entity.
Get information about an entity, optionally including all entity content. With **export**=`false`, this
operation is limited to 6000 requests per 5 minutes. With **export**=`true`, the limit is 200 requests per 30
minutes. For more information, see **Rate limiting**.
- parameter workspaceID: Unique identifier of the workspace.
- parameter entity: The name of the entity.
- parameter export: Whether to include all element content in the returned data. If **export**=`false`, the returned data includes only
information about the element itself. If **export**=`true`, all content, including subelements, is included.
- parameter includeAudit: Whether to include the audit properties (`created` and `updated` timestamps) in the response.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func getEntity(
workspaceID: String,
entity: String,
export: Bool? = nil,
includeAudit: Bool? = nil,
failure: ((Error) -> Void)? = nil,
success: @escaping (EntityExport) -> Void)
{
// construct header parameters
var headers = defaultHeaders
headers["Accept"] = "application/json"
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
if let export = export {
let queryParameter = URLQueryItem(name: "export", value: "\(export)")
queryParameters.append(queryParameter)
}
if let includeAudit = includeAudit {
let queryParameter = URLQueryItem(name: "include_audit", value: "\(includeAudit)")
queryParameters.append(queryParameter)
}
// construct REST request
let path = "/v1/workspaces/\(workspaceID)/entities/\(entity)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
failure?(RestError.encodingError)
return
}
let request = RestRequest(
method: "GET",
url: serviceURL + encodedPath,
credentials: credentials,
headerParameters: headers,
queryItems: queryParameters
)
// execute REST request
request.responseObject(responseToError: responseToError) {
(response: RestResponse<EntityExport>) in
switch response.result {
case .success(let retval): success(retval)
case .failure(let error): failure?(error)
}
}
}
/**
Update entity.
Update an existing entity with new or modified data. You must provide component objects defining the content of the
updated entity. This operation is limited to 1000 requests per 30 minutes. For more information, see **Rate
limiting**.
- parameter workspaceID: Unique identifier of the workspace.
- parameter entity: The name of the entity.
- parameter properties: The updated content of the entity. Any elements included in the new data will completely replace the equivalent
existing elements, including all subelements. (Previously existing subelements are not retained unless they are
also included in the new data.) For example, if you update the values for an entity, the previously existing values
are discarded and replaced with the new values specified in the update.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func updateEntity(
workspaceID: String,
entity: String,
properties: UpdateEntity,
failure: ((Error) -> Void)? = nil,
success: @escaping (Entity) -> Void)
{
// construct body
guard let body = try? JSONEncoder().encode(properties) else {
failure?(RestError.serializationError)
return
}
// construct header parameters
var headers = defaultHeaders
headers["Accept"] = "application/json"
headers["Content-Type"] = "application/json"
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
// construct REST request
let path = "/v1/workspaces/\(workspaceID)/entities/\(entity)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
failure?(RestError.encodingError)
return
}
let request = RestRequest(
method: "POST",
url: serviceURL + encodedPath,
credentials: credentials,
headerParameters: headers,
queryItems: queryParameters,
messageBody: body
)
// execute REST request
request.responseObject(responseToError: responseToError) {
(response: RestResponse<Entity>) in
switch response.result {
case .success(let retval): success(retval)
case .failure(let error): failure?(error)
}
}
}
/**
Delete entity.
Delete an entity from a workspace. This operation is limited to 1000 requests per 30 minutes. For more
information, see **Rate limiting**.
- parameter workspaceID: Unique identifier of the workspace.
- parameter entity: The name of the entity.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func deleteEntity(
workspaceID: String,
entity: String,
failure: ((Error) -> Void)? = nil,
success: @escaping () -> Void)
{
// construct header parameters
var headers = defaultHeaders
headers["Accept"] = "application/json"
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
// construct REST request
let path = "/v1/workspaces/\(workspaceID)/entities/\(entity)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
failure?(RestError.encodingError)
return
}
let request = RestRequest(
method: "DELETE",
url: serviceURL + encodedPath,
credentials: credentials,
headerParameters: headers,
queryItems: queryParameters
)
// execute REST request
request.responseVoid(responseToError: responseToError) {
(response: RestResponse) in
switch response.result {
case .success: success()
case .failure(let error): failure?(error)
}
}
}
/**
List entity values.
List the values for an entity. This operation is limited to 2500 requests per 30 minutes. For more information,
see **Rate limiting**.
- parameter workspaceID: Unique identifier of the workspace.
- parameter entity: The name of the entity.
- parameter export: Whether to include all element content in the returned data. If **export**=`false`, the returned data includes only
information about the element itself. If **export**=`true`, all content, including subelements, is included.
- parameter pageLimit: The number of records to return in each page of results.
- parameter includeCount: Whether to include information about the number of records returned.
- parameter sort: The attribute by which returned results will be sorted. To reverse the sort order, prefix the value with a minus
sign (`-`). Supported values are `name`, `updated`, and `workspace_id`.
- parameter cursor: A token identifying the page of results to retrieve.
- parameter includeAudit: Whether to include the audit properties (`created` and `updated` timestamps) in the response.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func listValues(
workspaceID: String,
entity: String,
export: Bool? = nil,
pageLimit: Int? = nil,
includeCount: Bool? = nil,
sort: String? = nil,
cursor: String? = nil,
includeAudit: Bool? = nil,
failure: ((Error) -> Void)? = nil,
success: @escaping (ValueCollection) -> Void)
{
// construct header parameters
var headers = defaultHeaders
headers["Accept"] = "application/json"
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
if let export = export {
let queryParameter = URLQueryItem(name: "export", value: "\(export)")
queryParameters.append(queryParameter)
}
if let pageLimit = pageLimit {
let queryParameter = URLQueryItem(name: "page_limit", value: "\(pageLimit)")
queryParameters.append(queryParameter)
}
if let includeCount = includeCount {
let queryParameter = URLQueryItem(name: "include_count", value: "\(includeCount)")
queryParameters.append(queryParameter)
}
if let sort = sort {
let queryParameter = URLQueryItem(name: "sort", value: sort)
queryParameters.append(queryParameter)
}
if let cursor = cursor {
let queryParameter = URLQueryItem(name: "cursor", value: cursor)
queryParameters.append(queryParameter)
}
if let includeAudit = includeAudit {
let queryParameter = URLQueryItem(name: "include_audit", value: "\(includeAudit)")
queryParameters.append(queryParameter)
}
// construct REST request
let path = "/v1/workspaces/\(workspaceID)/entities/\(entity)/values"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
failure?(RestError.encodingError)
return
}
let request = RestRequest(
method: "GET",
url: serviceURL + encodedPath,
credentials: credentials,
headerParameters: headers,
queryItems: queryParameters
)
// execute REST request
request.responseObject(responseToError: responseToError) {
(response: RestResponse<ValueCollection>) in
switch response.result {
case .success(let retval): success(retval)
case .failure(let error): failure?(error)
}
}
}
/**
Add entity value.
Create a new value for an entity. This operation is limited to 1000 requests per 30 minutes. For more
information, see **Rate limiting**.
- parameter workspaceID: Unique identifier of the workspace.
- parameter entity: The name of the entity.
- parameter properties: The new entity value.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func createValue(
workspaceID: String,
entity: String,
properties: CreateValue,
failure: ((Error) -> Void)? = nil,
success: @escaping (Value) -> Void)
{
// construct body
guard let body = try? JSONEncoder().encode(properties) else {
failure?(RestError.serializationError)
return
}
// construct header parameters
var headers = defaultHeaders
headers["Accept"] = "application/json"
headers["Content-Type"] = "application/json"
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
// construct REST request
let path = "/v1/workspaces/\(workspaceID)/entities/\(entity)/values"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
failure?(RestError.encodingError)
return
}
let request = RestRequest(
method: "POST",
url: serviceURL + encodedPath,
credentials: credentials,
headerParameters: headers,
queryItems: queryParameters,
messageBody: body
)
// execute REST request
request.responseObject(responseToError: responseToError) {
(response: RestResponse<Value>) in
switch response.result {
case .success(let retval): success(retval)
case .failure(let error): failure?(error)
}
}
}
/**
Get entity value.
Get information about an entity value. This operation is limited to 6000 requests per 5 minutes. For more
information, see **Rate limiting**.
- parameter workspaceID: Unique identifier of the workspace.
- parameter entity: The name of the entity.
- parameter value: The text of the entity value.
- parameter export: Whether to include all element content in the returned data. If **export**=`false`, the returned data includes only
information about the element itself. If **export**=`true`, all content, including subelements, is included.
- parameter includeAudit: Whether to include the audit properties (`created` and `updated` timestamps) in the response.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func getValue(
workspaceID: String,
entity: String,
value: String,
export: Bool? = nil,
includeAudit: Bool? = nil,
failure: ((Error) -> Void)? = nil,
success: @escaping (ValueExport) -> Void)
{
// construct header parameters
var headers = defaultHeaders
headers["Accept"] = "application/json"
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
if let export = export {
let queryParameter = URLQueryItem(name: "export", value: "\(export)")
queryParameters.append(queryParameter)
}
if let includeAudit = includeAudit {
let queryParameter = URLQueryItem(name: "include_audit", value: "\(includeAudit)")
queryParameters.append(queryParameter)
}
// construct REST request
let path = "/v1/workspaces/\(workspaceID)/entities/\(entity)/values/\(value)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
failure?(RestError.encodingError)
return
}
let request = RestRequest(
method: "GET",
url: serviceURL + encodedPath,
credentials: credentials,
headerParameters: headers,
queryItems: queryParameters
)
// execute REST request
request.responseObject(responseToError: responseToError) {
(response: RestResponse<ValueExport>) in
switch response.result {
case .success(let retval): success(retval)
case .failure(let error): failure?(error)
}
}
}
/**
Update entity value.
Update an existing entity value with new or modified data. You must provide component objects defining the content
of the updated entity value. This operation is limited to 1000 requests per 30 minutes. For more information,
see **Rate limiting**.
- parameter workspaceID: Unique identifier of the workspace.
- parameter entity: The name of the entity.
- parameter value: The text of the entity value.
- parameter properties: The updated content of the entity value. Any elements included in the new data will completely replace the
equivalent existing elements, including all subelements. (Previously existing subelements are not retained unless
they are also included in the new data.) For example, if you update the synonyms for an entity value, the
previously existing synonyms are discarded and replaced with the new synonyms specified in the update.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func updateValue(
workspaceID: String,
entity: String,
value: String,
properties: UpdateValue,
failure: ((Error) -> Void)? = nil,
success: @escaping (Value) -> Void)
{
// construct body
guard let body = try? JSONEncoder().encode(properties) else {
failure?(RestError.serializationError)
return
}
// construct header parameters
var headers = defaultHeaders
headers["Accept"] = "application/json"
headers["Content-Type"] = "application/json"
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
// construct REST request
let path = "/v1/workspaces/\(workspaceID)/entities/\(entity)/values/\(value)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
failure?(RestError.encodingError)
return
}
let request = RestRequest(
method: "POST",
url: serviceURL + encodedPath,
credentials: credentials,
headerParameters: headers,
queryItems: queryParameters,
messageBody: body
)
// execute REST request
request.responseObject(responseToError: responseToError) {
(response: RestResponse<Value>) in
switch response.result {
case .success(let retval): success(retval)
case .failure(let error): failure?(error)
}
}
}
/**
Delete entity value.
Delete a value from an entity. This operation is limited to 1000 requests per 30 minutes. For more information,
see **Rate limiting**.
- parameter workspaceID: Unique identifier of the workspace.
- parameter entity: The name of the entity.
- parameter value: The text of the entity value.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func deleteValue(
workspaceID: String,
entity: String,
value: String,
failure: ((Error) -> Void)? = nil,
success: @escaping () -> Void)
{
// construct header parameters
var headers = defaultHeaders
headers["Accept"] = "application/json"
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
// construct REST request
let path = "/v1/workspaces/\(workspaceID)/entities/\(entity)/values/\(value)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
failure?(RestError.encodingError)
return
}
let request = RestRequest(
method: "DELETE",
url: serviceURL + encodedPath,
credentials: credentials,
headerParameters: headers,
queryItems: queryParameters
)
// execute REST request
request.responseVoid(responseToError: responseToError) {
(response: RestResponse) in
switch response.result {
case .success: success()
case .failure(let error): failure?(error)
}
}
}
/**
List entity value synonyms.
List the synonyms for an entity value. This operation is limited to 2500 requests per 30 minutes. For more
information, see **Rate limiting**.
- parameter workspaceID: Unique identifier of the workspace.
- parameter entity: The name of the entity.
- parameter value: The text of the entity value.
- parameter pageLimit: The number of records to return in each page of results.
- parameter includeCount: Whether to include information about the number of records returned.
- parameter sort: The attribute by which returned results will be sorted. To reverse the sort order, prefix the value with a minus
sign (`-`). Supported values are `name`, `updated`, and `workspace_id`.
- parameter cursor: A token identifying the page of results to retrieve.
- parameter includeAudit: Whether to include the audit properties (`created` and `updated` timestamps) in the response.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func listSynonyms(
workspaceID: String,
entity: String,
value: String,
pageLimit: Int? = nil,
includeCount: Bool? = nil,
sort: String? = nil,
cursor: String? = nil,
includeAudit: Bool? = nil,
failure: ((Error) -> Void)? = nil,
success: @escaping (SynonymCollection) -> Void)
{
// construct header parameters
var headers = defaultHeaders
headers["Accept"] = "application/json"
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
if let pageLimit = pageLimit {
let queryParameter = URLQueryItem(name: "page_limit", value: "\(pageLimit)")
queryParameters.append(queryParameter)
}
if let includeCount = includeCount {
let queryParameter = URLQueryItem(name: "include_count", value: "\(includeCount)")
queryParameters.append(queryParameter)
}
if let sort = sort {
let queryParameter = URLQueryItem(name: "sort", value: sort)
queryParameters.append(queryParameter)
}
if let cursor = cursor {
let queryParameter = URLQueryItem(name: "cursor", value: cursor)
queryParameters.append(queryParameter)
}
if let includeAudit = includeAudit {
let queryParameter = URLQueryItem(name: "include_audit", value: "\(includeAudit)")
queryParameters.append(queryParameter)
}
// construct REST request
let path = "/v1/workspaces/\(workspaceID)/entities/\(entity)/values/\(value)/synonyms"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
failure?(RestError.encodingError)
return
}
let request = RestRequest(
method: "GET",
url: serviceURL + encodedPath,
credentials: credentials,
headerParameters: headers,
queryItems: queryParameters
)
// execute REST request
request.responseObject(responseToError: responseToError) {
(response: RestResponse<SynonymCollection>) in
switch response.result {
case .success(let retval): success(retval)
case .failure(let error): failure?(error)
}
}
}
/**
Add entity value synonym.
Add a new synonym to an entity value. This operation is limited to 1000 requests per 30 minutes. For more
information, see **Rate limiting**.
- parameter workspaceID: Unique identifier of the workspace.
- parameter entity: The name of the entity.
- parameter value: The text of the entity value.
- parameter synonym: The text of the synonym. This string must conform to the following restrictions: - It cannot contain carriage
return, newline, or tab characters. - It cannot consist of only whitespace characters. - It must be no longer
than 64 characters.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func createSynonym(
workspaceID: String,
entity: String,
value: String,
synonym: String,
failure: ((Error) -> Void)? = nil,
success: @escaping (Synonym) -> Void)
{
// construct body
let createSynonymRequest = CreateSynonym(synonym: synonym)
guard let body = try? JSONEncoder().encode(createSynonymRequest) else {
failure?(RestError.serializationError)
return
}
// construct header parameters
var headers = defaultHeaders
headers["Accept"] = "application/json"
headers["Content-Type"] = "application/json"
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
// construct REST request
let path = "/v1/workspaces/\(workspaceID)/entities/\(entity)/values/\(value)/synonyms"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
failure?(RestError.encodingError)
return
}
let request = RestRequest(
method: "POST",
url: serviceURL + encodedPath,
credentials: credentials,
headerParameters: headers,
queryItems: queryParameters,
messageBody: body
)
// execute REST request
request.responseObject(responseToError: responseToError) {
(response: RestResponse<Synonym>) in
switch response.result {
case .success(let retval): success(retval)
case .failure(let error): failure?(error)
}
}
}
/**
Get entity value synonym.
Get information about a synonym of an entity value. This operation is limited to 6000 requests per 5 minutes.
For more information, see **Rate limiting**.
- parameter workspaceID: Unique identifier of the workspace.
- parameter entity: The name of the entity.
- parameter value: The text of the entity value.
- parameter synonym: The text of the synonym.
- parameter includeAudit: Whether to include the audit properties (`created` and `updated` timestamps) in the response.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func getSynonym(
workspaceID: String,
entity: String,
value: String,
synonym: String,
includeAudit: Bool? = nil,
failure: ((Error) -> Void)? = nil,
success: @escaping (Synonym) -> Void)
{
// construct header parameters
var headers = defaultHeaders
headers["Accept"] = "application/json"
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
if let includeAudit = includeAudit {
let queryParameter = URLQueryItem(name: "include_audit", value: "\(includeAudit)")
queryParameters.append(queryParameter)
}
// construct REST request
let path = "/v1/workspaces/\(workspaceID)/entities/\(entity)/values/\(value)/synonyms/\(synonym)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
failure?(RestError.encodingError)
return
}
let request = RestRequest(
method: "GET",
url: serviceURL + encodedPath,
credentials: credentials,
headerParameters: headers,
queryItems: queryParameters
)
// execute REST request
request.responseObject(responseToError: responseToError) {
(response: RestResponse<Synonym>) in
switch response.result {
case .success(let retval): success(retval)
case .failure(let error): failure?(error)
}
}
}
/**
Update entity value synonym.
Update an existing entity value synonym with new text. This operation is limited to 1000 requests per 30
minutes. For more information, see **Rate limiting**.
- parameter workspaceID: Unique identifier of the workspace.
- parameter entity: The name of the entity.
- parameter value: The text of the entity value.
- parameter synonym: The text of the synonym.
- parameter newSynonym: The text of the synonym. This string must conform to the following restrictions: - It cannot contain carriage
return, newline, or tab characters. - It cannot consist of only whitespace characters. - It must be no longer
than 64 characters.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func updateSynonym(
workspaceID: String,
entity: String,
value: String,
synonym: String,
newSynonym: String? = nil,
failure: ((Error) -> Void)? = nil,
success: @escaping (Synonym) -> Void)
{
// construct body
let updateSynonymRequest = UpdateSynonym(synonym: newSynonym)
guard let body = try? JSONEncoder().encode(updateSynonymRequest) else {
failure?(RestError.serializationError)
return
}
// construct header parameters
var headers = defaultHeaders
headers["Accept"] = "application/json"
headers["Content-Type"] = "application/json"
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
// construct REST request
let path = "/v1/workspaces/\(workspaceID)/entities/\(entity)/values/\(value)/synonyms/\(synonym)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
failure?(RestError.encodingError)
return
}
let request = RestRequest(
method: "POST",
url: serviceURL + encodedPath,
credentials: credentials,
headerParameters: headers,
queryItems: queryParameters,
messageBody: body
)
// execute REST request
request.responseObject(responseToError: responseToError) {
(response: RestResponse<Synonym>) in
switch response.result {
case .success(let retval): success(retval)
case .failure(let error): failure?(error)
}
}
}
/**
Delete entity value synonym.
Delete a synonym from an entity value. This operation is limited to 1000 requests per 30 minutes. For more
information, see **Rate limiting**.
- parameter workspaceID: Unique identifier of the workspace.
- parameter entity: The name of the entity.
- parameter value: The text of the entity value.
- parameter synonym: The text of the synonym.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func deleteSynonym(
workspaceID: String,
entity: String,
value: String,
synonym: String,
failure: ((Error) -> Void)? = nil,
success: @escaping () -> Void)
{
// construct header parameters
var headers = defaultHeaders
headers["Accept"] = "application/json"
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
// construct REST request
let path = "/v1/workspaces/\(workspaceID)/entities/\(entity)/values/\(value)/synonyms/\(synonym)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
failure?(RestError.encodingError)
return
}
let request = RestRequest(
method: "DELETE",
url: serviceURL + encodedPath,
credentials: credentials,
headerParameters: headers,
queryItems: queryParameters
)
// execute REST request
request.responseVoid(responseToError: responseToError) {
(response: RestResponse) in
switch response.result {
case .success: success()
case .failure(let error): failure?(error)
}
}
}
/**
List dialog nodes.
List the dialog nodes for a workspace. This operation is limited to 2500 requests per 30 minutes. For more
information, see **Rate limiting**.
- parameter workspaceID: Unique identifier of the workspace.
- parameter pageLimit: The number of records to return in each page of results.
- parameter includeCount: Whether to include information about the number of records returned.
- parameter sort: The attribute by which returned results will be sorted. To reverse the sort order, prefix the value with a minus
sign (`-`). Supported values are `name`, `updated`, and `workspace_id`.
- parameter cursor: A token identifying the page of results to retrieve.
- parameter includeAudit: Whether to include the audit properties (`created` and `updated` timestamps) in the response.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func listDialogNodes(
workspaceID: String,
pageLimit: Int? = nil,
includeCount: Bool? = nil,
sort: String? = nil,
cursor: String? = nil,
includeAudit: Bool? = nil,
failure: ((Error) -> Void)? = nil,
success: @escaping (DialogNodeCollection) -> Void)
{
// construct header parameters
var headers = defaultHeaders
headers["Accept"] = "application/json"
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
if let pageLimit = pageLimit {
let queryParameter = URLQueryItem(name: "page_limit", value: "\(pageLimit)")
queryParameters.append(queryParameter)
}
if let includeCount = includeCount {
let queryParameter = URLQueryItem(name: "include_count", value: "\(includeCount)")
queryParameters.append(queryParameter)
}
if let sort = sort {
let queryParameter = URLQueryItem(name: "sort", value: sort)
queryParameters.append(queryParameter)
}
if let cursor = cursor {
let queryParameter = URLQueryItem(name: "cursor", value: cursor)
queryParameters.append(queryParameter)
}
if let includeAudit = includeAudit {
let queryParameter = URLQueryItem(name: "include_audit", value: "\(includeAudit)")
queryParameters.append(queryParameter)
}
// construct REST request
let path = "/v1/workspaces/\(workspaceID)/dialog_nodes"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
failure?(RestError.encodingError)
return
}
let request = RestRequest(
method: "GET",
url: serviceURL + encodedPath,
credentials: credentials,
headerParameters: headers,
queryItems: queryParameters
)
// execute REST request
request.responseObject(responseToError: responseToError) {
(response: RestResponse<DialogNodeCollection>) in
switch response.result {
case .success(let retval): success(retval)
case .failure(let error): failure?(error)
}
}
}
/**
Create dialog node.
Create a new dialog node. This operation is limited to 500 requests per 30 minutes. For more information, see
**Rate limiting**.
- parameter workspaceID: Unique identifier of the workspace.
- parameter properties: A CreateDialogNode object defining the content of the new dialog node.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func createDialogNode(
workspaceID: String,
properties: CreateDialogNode,
failure: ((Error) -> Void)? = nil,
success: @escaping (DialogNode) -> Void)
{
// construct body
guard let body = try? JSONEncoder().encode(properties) else {
failure?(RestError.serializationError)
return
}
// construct header parameters
var headers = defaultHeaders
headers["Accept"] = "application/json"
headers["Content-Type"] = "application/json"
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
// construct REST request
let path = "/v1/workspaces/\(workspaceID)/dialog_nodes"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
failure?(RestError.encodingError)
return
}
let request = RestRequest(
method: "POST",
url: serviceURL + encodedPath,
credentials: credentials,
headerParameters: headers,
queryItems: queryParameters,
messageBody: body
)
// execute REST request
request.responseObject(responseToError: responseToError) {
(response: RestResponse<DialogNode>) in
switch response.result {
case .success(let retval): success(retval)
case .failure(let error): failure?(error)
}
}
}
/**
Get dialog node.
Get information about a dialog node. This operation is limited to 6000 requests per 5 minutes. For more
information, see **Rate limiting**.
- parameter workspaceID: Unique identifier of the workspace.
- parameter dialogNode: The dialog node ID (for example, `get_order`).
- parameter includeAudit: Whether to include the audit properties (`created` and `updated` timestamps) in the response.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func getDialogNode(
workspaceID: String,
dialogNode: String,
includeAudit: Bool? = nil,
failure: ((Error) -> Void)? = nil,
success: @escaping (DialogNode) -> Void)
{
// construct header parameters
var headers = defaultHeaders
headers["Accept"] = "application/json"
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
if let includeAudit = includeAudit {
let queryParameter = URLQueryItem(name: "include_audit", value: "\(includeAudit)")
queryParameters.append(queryParameter)
}
// construct REST request
let path = "/v1/workspaces/\(workspaceID)/dialog_nodes/\(dialogNode)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
failure?(RestError.encodingError)
return
}
let request = RestRequest(
method: "GET",
url: serviceURL + encodedPath,
credentials: credentials,
headerParameters: headers,
queryItems: queryParameters
)
// execute REST request
request.responseObject(responseToError: responseToError) {
(response: RestResponse<DialogNode>) in
switch response.result {
case .success(let retval): success(retval)
case .failure(let error): failure?(error)
}
}
}
/**
Update dialog node.
Update an existing dialog node with new or modified data. This operation is limited to 500 requests per 30
minutes. For more information, see **Rate limiting**.
- parameter workspaceID: Unique identifier of the workspace.
- parameter dialogNode: The dialog node ID (for example, `get_order`).
- parameter properties: The updated content of the dialog node. Any elements included in the new data will completely replace the
equivalent existing elements, including all subelements. (Previously existing subelements are not retained unless
they are also included in the new data.) For example, if you update the actions for a dialog node, the previously
existing actions are discarded and replaced with the new actions specified in the update.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func updateDialogNode(
workspaceID: String,
dialogNode: String,
properties: UpdateDialogNode,
failure: ((Error) -> Void)? = nil,
success: @escaping (DialogNode) -> Void)
{
// construct body
guard let body = try? JSONEncoder().encode(properties) else {
failure?(RestError.serializationError)
return
}
// construct header parameters
var headers = defaultHeaders
headers["Accept"] = "application/json"
headers["Content-Type"] = "application/json"
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
// construct REST request
let path = "/v1/workspaces/\(workspaceID)/dialog_nodes/\(dialogNode)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
failure?(RestError.encodingError)
return
}
let request = RestRequest(
method: "POST",
url: serviceURL + encodedPath,
credentials: credentials,
headerParameters: headers,
queryItems: queryParameters,
messageBody: body
)
// execute REST request
request.responseObject(responseToError: responseToError) {
(response: RestResponse<DialogNode>) in
switch response.result {
case .success(let retval): success(retval)
case .failure(let error): failure?(error)
}
}
}
/**
Delete dialog node.
Delete a dialog node from a workspace. This operation is limited to 500 requests per 30 minutes. For more
information, see **Rate limiting**.
- parameter workspaceID: Unique identifier of the workspace.
- parameter dialogNode: The dialog node ID (for example, `get_order`).
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func deleteDialogNode(
workspaceID: String,
dialogNode: String,
failure: ((Error) -> Void)? = nil,
success: @escaping () -> Void)
{
// construct header parameters
var headers = defaultHeaders
headers["Accept"] = "application/json"
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
// construct REST request
let path = "/v1/workspaces/\(workspaceID)/dialog_nodes/\(dialogNode)"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
failure?(RestError.encodingError)
return
}
let request = RestRequest(
method: "DELETE",
url: serviceURL + encodedPath,
credentials: credentials,
headerParameters: headers,
queryItems: queryParameters
)
// execute REST request
request.responseVoid(responseToError: responseToError) {
(response: RestResponse) in
switch response.result {
case .success: success()
case .failure(let error): failure?(error)
}
}
}
/**
List log events in a workspace.
List the events from the log of a specific workspace. If **cursor** is not specified, this operation is limited
to 40 requests per 30 minutes. If **cursor** is specified, the limit is 120 requests per minute. For more
information, see **Rate limiting**.
- parameter workspaceID: Unique identifier of the workspace.
- parameter sort: The attribute by which returned results will be sorted. To reverse the sort order, prefix the value with a minus
sign (`-`). Supported values are `name`, `updated`, and `workspace_id`.
- parameter filter: A cacheable parameter that limits the results to those matching the specified filter. For more information, see the
[documentation](https://console.bluemix.net/docs/services/conversation/filter-reference.html#filter-query-syntax).
- parameter pageLimit: The number of records to return in each page of results.
- parameter cursor: A token identifying the page of results to retrieve.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func listLogs(
workspaceID: String,
sort: String? = nil,
filter: String? = nil,
pageLimit: Int? = nil,
cursor: String? = nil,
failure: ((Error) -> Void)? = nil,
success: @escaping (LogCollection) -> Void)
{
// construct header parameters
var headers = defaultHeaders
headers["Accept"] = "application/json"
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
if let sort = sort {
let queryParameter = URLQueryItem(name: "sort", value: sort)
queryParameters.append(queryParameter)
}
if let filter = filter {
let queryParameter = URLQueryItem(name: "filter", value: filter)
queryParameters.append(queryParameter)
}
if let pageLimit = pageLimit {
let queryParameter = URLQueryItem(name: "page_limit", value: "\(pageLimit)")
queryParameters.append(queryParameter)
}
if let cursor = cursor {
let queryParameter = URLQueryItem(name: "cursor", value: cursor)
queryParameters.append(queryParameter)
}
// construct REST request
let path = "/v1/workspaces/\(workspaceID)/logs"
guard let encodedPath = path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
failure?(RestError.encodingError)
return
}
let request = RestRequest(
method: "GET",
url: serviceURL + encodedPath,
credentials: credentials,
headerParameters: headers,
queryItems: queryParameters
)
// execute REST request
request.responseObject(responseToError: responseToError) {
(response: RestResponse<LogCollection>) in
switch response.result {
case .success(let retval): success(retval)
case .failure(let error): failure?(error)
}
}
}
/**
List log events in all workspaces.
List the events from the logs of all workspaces in the service instance. If **cursor** is not specified, this
operation is limited to 40 requests per 30 minutes. If **cursor** is specified, the limit is 120 requests per
minute. For more information, see **Rate limiting**.
- parameter filter: A cacheable parameter that limits the results to those matching the specified filter. You must specify a filter
query that includes a value for `language`, as well as a value for `workspace_id` or
`request.context.metadata.deployment`. For more information, see the
[documentation](https://console.bluemix.net/docs/services/conversation/filter-reference.html#filter-query-syntax).
- parameter sort: The attribute by which returned results will be sorted. To reverse the sort order, prefix the value with a minus
sign (`-`). Supported values are `name`, `updated`, and `workspace_id`.
- parameter pageLimit: The number of records to return in each page of results.
- parameter cursor: A token identifying the page of results to retrieve.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func listAllLogs(
filter: String,
sort: String? = nil,
pageLimit: Int? = nil,
cursor: String? = nil,
failure: ((Error) -> Void)? = nil,
success: @escaping (LogCollection) -> Void)
{
// construct header parameters
var headers = defaultHeaders
headers["Accept"] = "application/json"
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
queryParameters.append(URLQueryItem(name: "filter", value: filter))
if let sort = sort {
let queryParameter = URLQueryItem(name: "sort", value: sort)
queryParameters.append(queryParameter)
}
if let pageLimit = pageLimit {
let queryParameter = URLQueryItem(name: "page_limit", value: "\(pageLimit)")
queryParameters.append(queryParameter)
}
if let cursor = cursor {
let queryParameter = URLQueryItem(name: "cursor", value: cursor)
queryParameters.append(queryParameter)
}
// construct REST request
let request = RestRequest(
method: "GET",
url: serviceURL + "/v1/logs",
credentials: credentials,
headerParameters: headers,
queryItems: queryParameters
)
// execute REST request
request.responseObject(responseToError: responseToError) {
(response: RestResponse<LogCollection>) in
switch response.result {
case .success(let retval): success(retval)
case .failure(let error): failure?(error)
}
}
}
}
| 40.832382 | 152 | 0.63426 |
e6eec5b22bc7a545829dc3cd8ba81f8f5e59b48d | 1,224 | //
// ShowTrackerUITests.swift
// ShowTrackerUITests
//
// Created by Roman Madyanov on 23/09/2018.
// Copyright © 2018 Roman Madyanov. All rights reserved.
//
import XCTest
class ShowTrackerUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
super.tearDown()
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 34.971429 | 182 | 0.687908 |
d90c6fb6c56078db0ba4d6c67c251028ed9df3b3 | 3,624 | //
// homeViewController.swift
// douyuzhibofang
//
// Created by MacBook on 2018/8/6.
// Copyright © 2018年 douyumeng. All rights reserved.
//
import UIKit
private let titleViewH:CGFloat = 40
class homeViewController: UIViewController {
//MARK:---lazy Load :::
private lazy var pageTitleView:PageTitleView = {[weak self] in
let rect = CGRect(x: 0, y: kStatusBarH+kNavBarH, width:kScreenW, height: titleViewH)
let titles = ["推荐","游戏","娱乐","趣玩"]
let titleView = PageTitleView(frame: rect, titles: titles)
titleView.backgroundColor = UIColor.white
titleView.delegate = self
return titleView
}()
private lazy var pageContentV : PageContentView = {[weak self] in
let pageConY = kStatusBarH+kNavBarH+titleViewH
let pageConFrame = CGRect(x: 0, y: pageConY, width: kScreenW, height: kScreenH-pageConY-kTabbarH)
var vControlls=[UIViewController]()
vControlls.append(RecommendViewController())
for _ in 0..<3 {
let vc = UIViewController()
vc.view.backgroundColor = UIColor(r:CGFloat(arc4random_uniform(225)) , g: CGFloat(arc4random_uniform(225)), b: CGFloat(arc4random_uniform(225)))
vControlls.append(vc)
}
let pageContentV = PageContentView(frame:pageConFrame , childVCs: vControlls, fatherVC: self)
pageContentV.delegate = self
return pageContentV
}()
//MARK: 入口函数
override func viewDidLoad() {
super.viewDidLoad()
//0.不需要设置scrollView 的内边距
automaticallyAdjustsScrollViewInsets = false
setUI()
//添加头部滑动视图
view.addSubview(pageTitleView)
//添加内容视图
view.addSubview(pageContentV)
}
}
//MARK: --- 设置UI界面
extension homeViewController {
private func setUI(){
setNavigationBar()
}
private func setNavigationBar(){
//这也是自己创建的方法,
navigationItem.leftBarButtonItem = UIBarButtonItem(normalImgName:"logo")
let size = CGSize(width: 35, height: 35)
/*
** 这是调用类别的类方法的方法。
let historyItem = UIBarButtonItem.CreateItem(normalImgName: "image_my_history", selectedImgName: "Image_my_history_click", size: size)
let searchItem = UIBarButtonItem.CreateItem(normalImgName: "btn_search", selectedImgName: "btn_search_clicked", size: size)
let qrcodeItem = UIBarButtonItem.CreateItem(normalImgName: "Image_scan", selectedImgName: "Image_scan_click", size: size)
*/
//自己封装的构造函数的方法调用
let historyItem = UIBarButtonItem(normalImgName: "image_my_history", selectedImgName: "Image_my_history_click", size: size)
let searchItem = UIBarButtonItem(normalImgName: "btn_search", selectedImgName: "btn_search_clicked", size: size)
let qrcodeItem = UIBarButtonItem(normalImgName: "Image_scan", selectedImgName: "Image_scan_click", size: size)
navigationItem.rightBarButtonItems = [historyItem,searchItem,qrcodeItem]
}
}
//MARK: -- 实现 PageTitleViewDelegate
extension homeViewController : PageTitleViewDelegate {
func pageTitleViewClickTitle(pageTitleV: PageTitleView, clickIndex: Int) {
pageContentV.setScrollIndexView(index: clickIndex)
}
}
//MARK: -- 实现 PageContentViewDelegate
extension homeViewController : PageContentViewDelegate {
func pageContentViewScrollCollectionEvent(pageContentV: PageContentView, progress: CGFloat, oldIndex: Int, ChangedIndex: Int) {
pageTitleView.titleViewScroll(progress: progress, oldIndex: oldIndex, changedIndex: ChangedIndex)
}
}
| 35.529412 | 156 | 0.683775 |
f8d118f6d7eedfd29370389869931da1d748df30 | 33 | import Foundation
class RPC {
}
| 6.6 | 17 | 0.727273 |
9051c0bef23b11dc4d2871a4eed9312949e778ab | 975 | //
// MoviesListInteractor.swift
// VIP
//
// Created by Ayush Singhi on 27/03/21.
//
import Foundation
class MoviesListInteractor {
private var presenter: MoviesListPresenter
init(presenter: MoviesListPresenter) {
self.presenter = presenter
}
}
// MARK: - Load data
extension MoviesListInteractor {
func getMovies()
{
FileReader.getMovies { result in
guard case var .success(movies) = result
else {
self.presenter.updateViewForNoData()
return
}
movies = self.processMovies(movies: movies)
self.presenter.updateView(withMovies: movies)
}
}
}
// MARK: - Business logic
extension MoviesListInteractor {
///
/// Process movie data according to the requirment.
///
func processMovies(movies: [Movie]) -> [Movie] {
return movies.filter { movie in
movie.imdbRating > 8.0
}
}
}
| 18.396226 | 57 | 0.592821 |
9b5b003af7082b7850d496d413b6a4512afb1449 | 3,321 | import AdventUtilities
import Algorithms
import Foundation
public enum Solution4: Solution {
public static var title = "--- Day 4: Giant Squid ---"
public static func part1(_ input: String) -> String {
let lines = input.newlines
var game = parseGame(lines)
let score = game.winningScore()
return String(describing: score)
}
public static func part2(_ input: String) -> String {
let lines = input.newlines
var game = parseGame(lines)
let score = game.lastWinningScore()
return String(describing: score)
}
}
extension Solution4 {
static func parseGame(_ input: [String]) -> Game {
Game(callSequence: parseCallSequence(input.first ?? ""), boards: parseBoards(Array(input.dropFirst())))
}
static func parseCallSequence(_ line: String) -> [Int] {
line.components(separatedBy: ",").compactMap(Int.init)
}
static func parseBoards(_ lines: [String]) -> [Board] {
lines
.map { $0
.components(separatedBy: .whitespacesAndNewlines)
.compactMap(Int.init) }
.map(Board.init)
}
}
struct Board: Equatable {
var numbers: [Int]
init(_ numbers: [Int]) {
self.numbers = numbers
}
mutating func dab(number: Int) -> Board {
numbers.firstIndex(of: number).map { numbers[$0] = -1 }
return self
}
var hasWon: Bool {
let length = 5
let check = [-1, -1, -1, -1, -1]
var flag = false
var cursor = 0
while !flag && cursor < length {
let subRange = (0 ..< 5)
let row = subRange.map { numbers[cursor*5 + $0] }
let column = (0 ..< 5).map { numbers[cursor + $0*5] }
if row == check || column == check {
flag = true
}
cursor += 1
}
return flag
}
var sumOfUncalledNumbers: Int {
numbers.filter { $0 != -1 }.reduce(0, +)
}
}
extension Board: CustomDebugStringConvertible {
var debugDescription: String {
String(describing: numbers)
}
}
struct Game {
var callSequence: [Int]
var boards: [Board]
var wonBoards: [(Int, Board)] = .init()
mutating func call(number: Int) {
boards = boards.map { board in
var b = board
return b.dab(number: number)
}
}
var winningBoard: Board? {
boards.first(where: \.hasWon)
}
mutating func winningScore() -> Int {
let maxNumberOfCalls = callSequence.count
var cursor = 0
var score: Int? = nil
while cursor < maxNumberOfCalls && score == nil {
let number = callSequence[cursor]
call(number: number)
score = winningBoard.map { $0.sumOfUncalledNumbers * number }
cursor += 1
}
return score ?? 0
}
mutating func lastWinningScore() -> Int {
for number in callSequence {
call(number: number)
let won = boards.filter(\.hasWon).map { (number, $0) }
wonBoards.append(contentsOf: won)
boards = boards.filter { !$0.hasWon }
}
guard let (call, board) = wonBoards.last else { return 0 }
return board.sumOfUncalledNumbers * call
}
}
| 25.159091 | 111 | 0.555556 |
9b10c7d35e7acaeb22bb55b1a8e0be619cc196c1 | 11,841 | import Foundation
import CoreLocation
import WebKit
private struct JSOptions: IJSOptions {
let options: JSOptionsDictionary
func jsKeyValue() -> JSOptionsDictionary {
self.options
}
}
class JSBridge : NSObject {
typealias Completion = (Result<Void, Error>) -> Void
private unowned let executor: JSExecutorProtocol
weak var delegate: JSBridgeDelegate?
init(executor: JSExecutorProtocol) {
self.executor = executor
}
func initializeMap(
options: JSOptionsDictionary,
completion: Completion? = nil
) {
let value = JSOptions(options: options)
let js = "window.initializeMap(\(value.jsValue()));"
self.evaluateJS(js, completion: completion)
}
func invalidateSize(completion: Completion? = nil) {
let js = "window.map.invalidateSize();"
self.evaluateJS(js, completion: completion)
}
func fetchGeographicalBounds(completion: @escaping (Result<GeographicalBounds, Error>) -> Void) {
let js = "window.map.getBounds();"
self.executor.evaluateJavaScript(js) { result, erorr in
if let error = erorr {
completion(.failure(error))
} else {
let dictionary = result as? [String: Any]
if let bounds = GeographicalBounds(dictionary: dictionary) {
completion(.success(bounds))
} else {
completion(.failure(MapGLError(text: "Parsing error")))
}
}
}
}
func fitBounds(_ bounds: GeographicalBounds, options: FitBoundsOptions? = nil, completion: Completion?) {
let js = "window.map.fitBounds(\(bounds.jsValue()), \(options.jsValue()));"
self.evaluateJS(js, completion: completion)
}
func fetchMapCenter(completion: ((Result<CLLocationCoordinate2D, Error>) -> Void)?) {
let js = "window.map.getCenter();"
self.executor.evaluateJavaScript(js) { (result, erorr) in
if let error = erorr {
completion?(.failure(error))
} else if let result = result as? [Double], result.count == 2 {
let lon = result[0]
let lat = result[1]
completion?(.success(CLLocationCoordinate2D(latitude: lat, longitude: lon)))
} else {
completion?(.failure(MapGLError(text: "Parsing error")))
}
}
}
func setMapCenter(_ center: CLLocationCoordinate2D, completion: Completion? = nil) {
let js = "window.map.setCenter(\(center.jsValue()));"
self.evaluateJS(js, completion: completion)
}
func fetchMapZoom(completion: ((Result<Double, Error>) -> Void)?) {
self.fetch(js: "window.map.getZoom();", completion: completion)
}
func fetchMapStyleZoom(completion: ((Result<Double, Error>) -> Void)?) {
self.fetch(js: "window.map.getStyleZoom();", completion: completion)
}
func setMapZoom(
_ zoom: Double,
options: MapGL.AnimationOptions? = nil,
completion: Completion? = nil
) {
let js = "window.map.setZoom(\(zoom), \(options.jsValue()));"
self.evaluateJS(js, completion: completion)
}
func setStyleZoom(_ zoom: Double, options: MapGL.AnimationOptions? = nil) {
let js = "window.map.setStyleZoom(\(zoom), \(options.jsValue()));"
self.evaluateJS(js)
}
func setStyle(by id: String, completion: Completion? = nil) {
let js = #"window.map.setStyleById("\#(id)");"#
self.evaluateJS(js, completion: completion)
}
func setMapMaxZoom(_ maxZoom: Double, completion: Completion? = nil) {
let js = "window.map.setMaxZoom(\(maxZoom));"
self.evaluateJS(js, completion: completion)
}
func setMapMinZoom(_ minZoom: Double, completion: Completion? = nil) {
let js = "window.map.setMinZoom(\(minZoom));"
self.evaluateJS(js, completion: completion)
}
func fetchMapRotation(completion: ((Result<Double, Error>) -> Void)? = nil) {
self.fetch(js: "window.map.getRotation();", completion: completion)
}
func setMapRotation(_ rotation: Double, completion: Completion? = nil) {
let js = "window.map.setRotation(\(rotation));"
self.evaluateJS(js, completion: completion)
}
func fetchMapPitch(completion: ((Result<Double, Error>) -> Void)?) {
self.fetch(js: "window.map.getPitch();", completion: completion)
}
func setMapPitch(_ pitch: Double, completion: Completion? = nil) {
let js = "window.map.setPitch(\(pitch));"
self.evaluateJS(js, completion: completion)
}
func setMapMaxPitch(_ maxPitch: Double, completion: Completion? = nil) {
let js = "window.map.setMaxPitch(\(maxPitch));"
self.evaluateJS(js, completion: completion)
}
func setMapMinPitch(_ minPitch: Double, completion: Completion? = nil) {
let js = "window.map.setMinPitch(\(minPitch));"
self.evaluateJS(js, completion: completion)
}
func add(_ object: IJSMapObject, completion: Completion? = nil) {
let js = object.createJSCode()
self.evaluateJS(js, completion: completion)
}
func destroy(_ object: IJSMapObject, completion: Completion? = nil) {
let js = object.destroyJSCode()
self.evaluateJS(js, completion: completion)
}
func evaluateJS(_ js: String, completion: Completion? = nil) {
self.executor.evaluateJavaScript(js) { (_, error) in
if let error = error {
// Then js returns the map object itself we have an error:
// 'JavaScript execution returned a result of an unsupported type'. Ignore it.
if (error as? WKError)?.code == .javaScriptResultTypeIsUnsupported {
completion?(.success(()))
} else {
completion?(.failure(error))
}
} else {
completion?(.success(()))
}
}
}
func setSelectedObjects(_ objectsIds: [String]) {
let js = """
window.setSelectedObjects(\(objectsIds.jsValue()));
"""
self.evaluateJS(js)
}
func setStyle(style: String) {
let js = """
window.setStyle(\(style.jsValue()));
"""
self.evaluateJS(js)
}
func setStyleState(styleState: [String: Bool]) {
let styleState = styleState.mapValues { $0.jsValue() }.jsValue()
let js = """
window.setStyleState(\(styleState));
"""
self.evaluateJS(js)
}
func patchStyleState(styleState: [String: Bool]) {
let styleState = styleState.mapValues { $0.jsValue() }.jsValue()
let js = """
window.patchStyleState(\(styleState));
"""
self.evaluateJS(js)
}
func setPadding(padding: Padding) {
let js = """
window.setPadding(\(padding.jsValue()));
"""
self.evaluateJS(js)
}
func setLanguage(language: String) {
let js = """
window.setLanguage(\(language.jsValue()));
"""
self.evaluateJS(js)
}
func setFloorPlanLevel(floorPlanId: String, floorLevelIndex: Int) {
let js = """
window.setFloorPlanLevel(\(floorPlanId.jsValue()), \(floorLevelIndex));
"""
self.evaluateJS(js)
}
func project(location: CLLocationCoordinate2D, completion: @escaping (Result<CGPoint, Error>) -> Void) {
let js = "window.map.project(\(location.jsValue()));"
self.executor.evaluateJavaScript(js) { (result, erorr) in
if let error = erorr {
completion(.failure(error))
} else if let result = result as? [CGFloat], result.count >= 2 {
let x = result[0]
let y = result[1]
completion(.success(CGPoint(x: x, y: y)))
} else {
completion(.failure(MapGLError(text: "Parsing error")))
}
}
}
func unproject(point: CGPoint, completion: @escaping (Result<CLLocationCoordinate2D, Error>) -> Void) {
let js = "window.map.unproject(\(point.jsValue()));"
self.executor.evaluateJavaScript(js) { (result, erorr) in
if let error = erorr {
completion(.failure(error))
} else if let result = result as? [Double], result.count == 2 {
let lon = result[0]
let lat = result[1]
completion(.success(CLLocationCoordinate2D(latitude: lat, longitude: lon)))
} else {
completion(.failure(MapGLError(text: "Parsing error")))
}
}
}
private func fetch<T>(js: String, completion: ((Result<T, Error>) -> Void)?) {
self.executor.evaluateJavaScript(js) { (result, erorr) in
if let error = erorr {
completion?(.failure(error))
} else if let result = result as? T {
completion?(.success(result))
} else {
completion?(.failure(MapGLError(text: "Parsing error")))
}
}
}
}
extension JSBridge: WKScriptMessageHandler {
var messageHandlerName: String { "dgsMessage" }
var errorHandlerName: String { "error" }
func userContentController(
_ userContentController: WKUserContentController,
didReceive message: WKScriptMessage
) {
switch message.name {
case self.errorHandlerName:
self.handleError(message: message)
case self.messageHandlerName:
self.handleMessage(message: message)
default:
break
}
}
private func handleError(message: WKScriptMessage) {
}
private func handleMessage(message: WKScriptMessage) {
guard let delegate = self.delegate else { return }
guard let body = message.body as? [String: Any] else { return }
guard let type = body["type"] as? String else { return }
switch type {
case "centerChanged":
let data = body["value"] as? [Double]
if let lat = data?.last, let lon = data?.first {
delegate.js(self, mapCenterDidChange: CLLocationCoordinate2D(latitude: lat, longitude: lon))
}
case "zoomChanged":
if let zoom = body["value"] as? Double {
delegate.js(self, mapZoomDidChange: zoom)
}
case "styleZoomChanged":
if let zoom = body["value"] as? Double {
delegate.js(self, mapStyleZoomChanged: zoom)
}
case "rotationChanged":
if let rotation = body["value"] as? Double {
delegate.js(self, mapRotationDidChange: rotation)
}
case "pitchChanged":
if let pitch = body["value"] as? Double {
delegate.js(self, mapPitchDidChange: pitch)
}
case "mapClick":
if let data = body["value"] as? String, let event = MapClickEvent(string: data) {
delegate.js(self, didClickMapWithEvent: event)
}
case "objectClick":
if let id = body["value"] as? String {
delegate.js(self, didClickObjectWithId: id)
} else {
assertionFailure()
}
case "clusterClick":
guard let clusterId = body["id"] as? String else { assertionFailure(); return }
if let marker = body["value"] as? [String: Any] {
if let id = marker["id"] as? String {
delegate.js(self, didClickClusterWithId: clusterId, markerIds: [id])
} else {
assertionFailure()
}
} else if let cluster = body["value"] as? [[String: Any]] {
let ids = cluster.compactMap { $0["id"] as? String }
assert(cluster.count == ids.count)
delegate.js(self, didClickClusterWithId: clusterId, markerIds: ids)
} else {
assertionFailure()
}
case "carRouteCompletion":
guard let data = body["value"] as? [String: String],
let directionId = data["directionId"],
let completionId = data["completionId"],
let error = data["error"] else {
assertionFailure()
return
}
let mapglError: MapGLError? = error.isEmpty ? nil : MapGLError(text: error)
delegate.js(self, carRouteDidFinishWithId: directionId, completionId: completionId, error: mapglError)
case "floorPlanShow":
guard let data = body["value"] as? [String: Any],
let id = data["floorPlanId"] as? String,
let currentLevelIndex = data["currentFloorLevelIndex"] as? Int,
let levelObjects = data["floorLevels"] as? [[String: Any]] else {
assertionFailure()
return
}
let levels = levelObjects.compactMap({ $0["floorLevelName"] as? String })
delegate.js(self, showFloorPlan: id, currentLevelIndex: currentLevelIndex, floorLevels: levels)
case "floorPlanHide":
guard let data = body["value"] as? [String: Any],
let id = data["floorPlanId"] as? String else {
assertionFailure()
return
}
delegate.js(self, hideFloorPlan: id)
case "supportChanged":
let data = body["value"] as? [String: String]
let notSupportedReason = data?["notSupportedReason"]
let notSupportedWithGoodPerformanceReason = data?["notSupportedWithGoodPerformanceReason"]
delegate.js(
self,
supportedReason: notSupportedReason,
notSupportedWithGoodPerformanceReason: notSupportedWithGoodPerformanceReason
)
default:
assertionFailure()
}
}
}
| 30.835938 | 106 | 0.678237 |
b989274fb8d2261602536dae13848ed3e1aa4c59 | 11,851 | //
// LBSettingViewController.swift
// LittleBlackBear
//
// Created by Apple on 2017/12/19.
// Copyright © 2017年 蘇崢. All rights reserved.
//
import UIKit
class LBSettingViewController: UIViewController {
var loginSuccessHanlder:(()->())?
fileprivate let tableView = UITableView(frame: .zero, style:.grouped)
fileprivate var cellItem:[LBSettingCellType] = [LBSettingCellType]()
fileprivate lazy var userLoginStatus:Bool = LBKeychain.get(ISLOGIN) == LOGIN_TRUE ? true:false
fileprivate var cacheSize = LBCacheManger.cache.showCacheSize()/(1024*1024)
fileprivate var isSetPayPassword:Bool = false
override func viewDidLoad() {
super.viewDidLoad()
querPayPassStatus()
setupUI()
navigationItem.title = "设置"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor:UIColor.white,
NSAttributedStringKey.font:UIFont.boldSystemFont(ofSize: 15.0)]
UIApplication.shared.setStatusBarStyle(.default, animated: true)
navigationController?.navigationBar.setBackgroundImage(UIImage.imageWithColor(COLOR_e60013), for: .default)
UIApplication.shared.setStatusBarStyle(.lightContent, animated: true)
setCellItem()
tableView.reloadData()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
}
private func setupUI() {
view.addSubview(tableView)
automaticallyAdjustsScrollViewInsets = false
tableView.estimatedRowHeight = 0
tableView.estimatedSectionFooterHeight = 0
tableView.estimatedSectionHeaderHeight = 0
tableView.delegate = self
tableView.dataSource = self
tableView.translatesAutoresizingMaskIntoConstraints = false
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[tableView]-0-|",
options: NSLayoutFormatOptions.alignAllCenterY,
metrics: nil,
views: ["tableView": tableView]))
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[tableView]|",
options: NSLayoutFormatOptions.alignAllCenterX,
metrics: nil,
views: ["tableView": tableView]))
tableView.contentInset = UIEdgeInsets(top: 10, left: 0, bottom: 0, right: 0)
LBSettingTableViewCellFactory.registerApplyTableViewCell(tableView)
navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named:"left_arrow_white")?.withRenderingMode(.alwaysOriginal),
style: .plain,
target: self,
action: #selector(popViewController))
}
func popViewController() {
navigationController?.popViewController(animated: true)
}
fileprivate func setCellItem() {
let userStatus = LBKeychain.get(ISATHUENICATION)
cellItem = [
.rightLabel("用户昵称",(LBKeychain.get(LLNickName) != "" ? LBKeychain.get(LLNickName):"未设置"), COLOR_9C9C9C),
.rightLabel("实名认证",(userStatus=="0" ?"已实名":"未实名"), COLOR_9C9C9C),
.comm("提现卡变更"),
.bindAcoountImage("账号绑定",["logo_wechat","call_red_icon"]),
.comm("修改登录密码"),
.comm(isSetPayPassword==true ?"找回支付密码":"设置支付密码"),
.comm("修改支付密码"),
.rightLabel("清除缓存", (cacheSize==0 ?"暂无缓存":"\(cacheSize) M"),COLOR_222222),
.switch("推送设置", true),
.rightLabel("版本信息","V \(VERSION)",COLOR_222222),
.comm("关于公司"),
.comm("隐私条款"),
.comm("帮助与反馈"),
.commitButton((userLoginStatus==true) ?"退出登录":"请登录")
]
}
}
extension LBSettingViewController:UITableViewDelegate,UITableViewDataSource{
func numberOfSections(in tableView: UITableView) -> Int {
return cellItem.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = LBSettingTableViewCellFactory.dequeueReusableCell(withTableView: tableView, cellType: cellItem[indexPath.section])
cell?.selectionStyle = .none
cell?.separatorInset = UIEdgeInsetsMake(0, -20, 0, 0)
return cell!
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
switch cellItem[indexPath.section] {
case .commitButton(_):
return 100
default:
return 45
}
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 10
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0.001
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if userLoginStatus == false {
switch indexPath.section {
case 0,1,2,3,4,5,6:
presentLoginViewController()
default:
break
}
}
switch cellItem[indexPath.section] {
case .commitButton(let text):
if text == "退出登录"{
loginout()
}
if text == "请登录"{
presentLoginViewController()
}
case let .rightLabel(text, rightText, _):
if text == "清除缓存",cacheSize != 0{
remoeCache()
}
if rightText == "未实名"{
let viewController = LBAuthenicationViewController()
viewController.authenicationSuccessHandler = {[weak self] in
guard let strongSelf = self else{return}
strongSelf.setCellItem()
}
navigationController?.pushViewController(viewController, animated: true)
}
if text == "用户昵称"{
navigationController?.pushViewController(ZJModifyNickNameVC(), animated: true)
}
case let.comm(text):
if text == "设置支付密码"{
let viewController = LBSetPayPasswordViewController()
viewController.setPayPasswordSuccessHandler = {[weak self] in
guard let strongSelf = self else{return}
strongSelf.querPayPassStatus()
strongSelf.setCellItem()
}
navigationController?.pushViewController(viewController, animated: true)
}
if text == "修改登录密码"{
navigationController?.pushViewController(LBModifyLoginPassword(), animated: true)
}
if text == "用户基本信息"{
navigationController?.pushViewController(LBUserInfoViewController(), animated: true)
}
if text == "找回支付密码"{
navigationController?.pushViewController(LBFindPayPassswordViewController(), animated: true)
}
if text == "修改支付密码"{
navigationController?.pushViewController(LBModifyPayPasswordViewController(), animated: true)
}
if text == "隐私条款"{
navigationController?.pushViewController(LBPrivatePolicyWebViewController(), animated: true)
}
if text == "关于公司"{
navigationController?.pushViewController(LBAbaotCompanyViewController(), animated: true)
}
if text == "帮助与反馈"{
navigationController?.pushViewController(LBOpinionsWebViewController(), animated: true )
}
if text == "提现卡变更"{
guard LBKeychain.get(ISATHUENICATION) == "0" else{
showAlertView("请先实名认证", "确定",nil)
break
}
navigationController?.pushViewController(LBModifyBankCardViewController(), animated: true)
return
}
case .bindAcoountImage(let text, _):
if text == "账号绑定"{
navigationController?.pushViewController(LBBindAcoountViewController(), animated: true)
}
default:
break
}
}
}
extension LBSettingViewController:LBSettingPresenter{
fileprivate func remoeCache(){
LBCacheManger.cache.clearCache {[weak self] in
guard let strongSelf = self else{return }
strongSelf.cacheSize = 0
strongSelf.setCellItem()
}
URLCache.shared.removeAllCachedResponses()
}
fileprivate func loginout(){
let alertController = UIAlertController(title: "提示", message: "是否退出登录?", preferredStyle: .actionSheet)
let cancle = UIAlertAction(title: "取消", style: .cancel, handler: nil)
let transAccount = UIAlertAction(title: "切换账号", style: .default, handler: { [weak self] (_) in
guard let strongSelf = self else{return}
LBKeychain.removeKeyChain()
strongSelf.userLoginStatus = false
strongSelf.isSetPayPassword = false
strongSelf.remoeCache()
strongSelf.presentLoginViewController()
})
let confirm = UIAlertAction(title: "退出", style: .default, handler:{ [weak self](_) in
guard let strongSelf = self else{return}
LBKeychain.removeKeyChain()
strongSelf.userLoginStatus = false
strongSelf.isSetPayPassword = false
strongSelf.remoeCache()
strongSelf.querPayPassStatus()
strongSelf.tableView.reloadData()
})
alertController.addAction(cancle)
alertController.addAction(confirm)
alertController.addAction(transAccount)
present(alertController, animated: true, completion: nil)
}
fileprivate func presentLoginViewController(){
let viewController = LBLoginViewController()
present(LBNavigationController(rootViewController: viewController), animated: true, completion: nil)
viewController.loginSuccessHanlder = {[weak self] in
guard let strongSelf = self else{return}
viewController.dismiss(animated: true, completion: nil)
guard let action = strongSelf.loginSuccessHanlder else{return}
action()
strongSelf.navigationController?.popToRootViewController(animated: true)
strongSelf.setCellItem()
}
}
fileprivate func querPayPassStatus() {
query_isSetPayPassword {[weak self] in
guard let strongSelf = self else{return}
strongSelf.isSetPayPassword = true
strongSelf.setCellItem()
strongSelf.tableView.reloadData()
}
}
}
| 38.229032 | 136 | 0.570754 |
bf16474cf637f6504464e7d57862e8e2dae2dd9e | 4,029 | // DO NOT EDIT.
// swift-format-ignore-file
//
// Generated by the Swift generator plugin for the protocol buffer compiler.
// Source: request/group/enrollment/query_group_join_questions_request.proto
//
// For information on using the generated types, please see the documentation:
// https://github.com/apple/swift-protobuf/
import Foundation
import SwiftProtobuf
// If the compiler emits an error on this type, it is because this file
// was generated by a version of the `protoc` Swift plug-in that is
// incompatible with the version of SwiftProtobuf to which you are linking.
// Please ensure that you are building against the same version of the API
// that was used to generate this file.
private struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck {
struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {}
typealias Version = _2
}
public struct QueryGroupJoinQuestionsRequest {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
public var groupID: Int64 = 0
public var withAnswers: Bool = false
public var lastUpdatedDate: Int64 {
get { return _lastUpdatedDate ?? 0 }
set { _lastUpdatedDate = newValue }
}
/// Returns true if `lastUpdatedDate` has been explicitly set.
public var hasLastUpdatedDate: Bool { return _lastUpdatedDate != nil }
/// Clears the value of `lastUpdatedDate`. Subsequent reads from it will return its default value.
public mutating func clearLastUpdatedDate() { _lastUpdatedDate = nil }
public var unknownFields = SwiftProtobuf.UnknownStorage()
public init() {}
fileprivate var _lastUpdatedDate: Int64?
}
// MARK: - Code below here is support for the SwiftProtobuf runtime.
private let _protobuf_package = "im.turms.proto"
extension QueryGroupJoinQuestionsRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
public static let protoMessageName: String = _protobuf_package + ".QueryGroupJoinQuestionsRequest"
public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "group_id"),
2: .standard(proto: "with_answers"),
3: .standard(proto: "last_updated_date"),
]
public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try try decoder.decodeSingularInt64Field(value: &groupID)
case 2: try try decoder.decodeSingularBoolField(value: &withAnswers)
case 3: try try decoder.decodeSingularInt64Field(value: &_lastUpdatedDate)
default: break
}
}
}
public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if groupID != 0 {
try visitor.visitSingularInt64Field(value: groupID, fieldNumber: 1)
}
if withAnswers != false {
try visitor.visitSingularBoolField(value: withAnswers, fieldNumber: 2)
}
try { if let v = self._lastUpdatedDate {
try visitor.visitSingularInt64Field(value: v, fieldNumber: 3)
} }()
try unknownFields.traverse(visitor: &visitor)
}
public static func == (lhs: QueryGroupJoinQuestionsRequest, rhs: QueryGroupJoinQuestionsRequest) -> Bool {
if lhs.groupID != rhs.groupID { return false }
if lhs.withAnswers != rhs.withAnswers { return false }
if lhs._lastUpdatedDate != rhs._lastUpdatedDate { return false }
if lhs.unknownFields != rhs.unknownFields { return false }
return true
}
}
| 41.96875 | 142 | 0.70762 |
e67c1d636c45ed0b1a9b75beddcd1fb47568a5b1 | 8,483 | //
// ViewController.swift
// TouchBarEmojis
//
// Created by Gabriel Lorin
//
import Cocoa
@available(OSX 10.12.2, *)
class ViewController: NSViewController, NSTableViewDataSource, NSTableViewDelegate {
// help button:
@IBAction func helpButtonClicked(_ sender: Any) {
openGitHubLink()
}
// button with blue URL to GitHub:
@IBOutlet weak var linkButton: NSButton!
@IBAction func linkButtonClicked(_ sender: Any) {
openGitHubLink()
}
// when update available:
@IBAction func buttonLinkNewVersion(_ sender: Any) {
openGitHubLink()
}
// menu action help:
@IBAction func showHelp(_ sender: Any) {
openGitHubLink()
}
// when update available, view:
@IBOutlet weak var viewUpdateMessage: NSView!
// table:
@IBOutlet weak var appsTable: NSTableView!
// table button remove:
@IBOutlet weak var buttonRemove: NSButton!
// table button remove clicked:
@IBAction func buttonRemove(_ sender: Any) {
buttonRemoveClicked()
}
// table button add clicked:
@IBAction func buttonAdd(_ sender: Any) {
buttonAddClicked()
}
// URL for GitHub:
private let gitHubUrl = "https://github.com/gabriellorin/touch-bar-emojis"
override func viewDidLoad() {
super.viewDidLoad()
// in case we want to reset the preferences settings:
//UserDefaults.standard.removePersistentDomain(forName: Bundle.main.bundleIdentifier!)
// get saved apps list from app's preferences:
if let loadedEmojisForApp = UserDefaults.standard.array(forKey: "SavedAppsForEmojis") as? [[String: String]] {
// set the dic array:
AppDelegate.emojisForApp = loadedEmojisForApp
}
// if no apps in list:
if(AppDelegate.emojisForApp.count == 0) {
// add default list:
for oneApp in AppDelegate.defaultApps {
// (addBundleAtPath will only add apps which exist)
self.addBundleAtPath(path: oneApp)
}
}
// setting up table:
self.appsTable.delegate = self
self.appsTable.dataSource = self
self.appsTable.reloadData()
// check if the app has an update:
checkForUpdate()
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
func tableViewSelectionDidChange(_ notification: Notification) {
// if at least one item is selected:
if(self.appsTable.selectedRow < 0) {
// activate remove button:
buttonRemove.isEnabled = false
} else {
buttonRemove.isEnabled = true
}
}
func addBundleAtPath(path: String) {
// from a path, we get the app's name and bundle id:
if let bundle = Bundle(path: path) {
if let ident = bundle.bundleIdentifier {
if let bundleAppName = NSURL(fileURLWithPath: path).lastPathComponent {
// if the app has bundle id and name, we add it to our list of apps:
AppDelegate.emojisForApp.append(["name":bundleAppName, "bundle":ident])
// store the new list to preferences file:
let defaults = UserDefaults.standard
defaults.set(AppDelegate.emojisForApp, forKey: "SavedAppsForEmojis")
}
} else {
//bundle has no id
}
} else {
// bundle not found
}
}
func buttonRemoveClicked() {
// clicked button to remove from table
// multiple elements can be selected, stating from the end:
for oneRow in self.appsTable.selectedRowIndexes.reversed() {
// if element actually selected:
if(oneRow > -1) {
// removed starting from the end:
AppDelegate.emojisForApp.remove(at: oneRow)
// reload table:
self.appsTable.reloadData()
// store new table:
let defaults = UserDefaults.standard
defaults.set(AppDelegate.emojisForApp, forKey: "SavedAppsForEmojis")
// disable remove button:
buttonRemove.isEnabled = false
}
}
}
func buttonAddClicked() {
// clicked button to add to table
let dialog = NSOpenPanel();
dialog.title = "Choose an app";
dialog.showsResizeIndicator = true;
dialog.directoryURL = NSURL.fileURL(withPath: "/Applications/", isDirectory: true)
dialog.showsHiddenFiles = false;
dialog.canChooseDirectories = true;
dialog.canCreateDirectories = true;
dialog.allowsMultipleSelection = false;
dialog.allowedFileTypes = ["app"];
dialog.beginSheetModal(for: self.view.window!, completionHandler: { num in
if num == NSModalResponseOK {
// get path:
if let path = dialog.url?.path {
// add bundle at path:
self.addBundleAtPath(path: path)
// reload table:
self.appsTable.reloadData()
}
} else {
// user cancelled
}
})
}
func checkForUpdate() {
let url = URL(string: "https://momoji.io/touchmoji/version.html")
if let usableUrl = url {
let request = URLRequest(url: usableUrl)
let task = URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) in
if let data = data {
if let stringData = String(data: data, encoding: String.Encoding.utf8) {
if let strVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String {
if let currentVersion = Float(strVersion) {
if let webVersion = Float(stringData) {
if(currentVersion < webVersion) {
// new version, show update message in main qeue:
DispatchQueue.main.async {
() -> Void in
self.viewUpdateMessage.isHidden = false
}
} else {
// no new version
}
}
}
}
}
}
})
task.resume()
}
}
func numberOfRows(in tableView: NSTableView) -> Int {
return AppDelegate.emojisForApp.count
}
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView?{
var result:NSTableCellView
result = tableView.make(withIdentifier: (tableColumn?.identifier)!, owner: self) as! NSTableCellView
// for each row, get the data:
let rowAppIdentifier = AppDelegate.emojisForApp[row]
// make sure we have a matching name for the app:
if let appsName = rowAppIdentifier["name"] {
// if we have, we display name:
result.textField?.stringValue = appsName
} else if let bundleName = rowAppIdentifier["bundle"] {
// otherwise we display the bundle name
result.textField?.stringValue = bundleName
} else {
// and default:
result.textField?.stringValue = "unknown app name"
}
return result
}
func openGitHubLink() {
let url = URL(string: gitHubUrl)!
NSWorkspace.shared().open(url)
}
}
| 33.932 | 127 | 0.512437 |