repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
55 values
size
stringlengths
2
6
content
stringlengths
55
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
979
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
jwren/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/packages/columns/VersionColumn.kt
2
2624
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns import com.intellij.util.ui.ColumnInfo import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.TargetModules import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.UiPackageModel import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.versions.NormalizedPackageVersion import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.PackagesTableItem import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.editors.PackageVersionTableCellEditor import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.renderers.PackageVersionTableCellRenderer import javax.swing.table.TableCellEditor import javax.swing.table.TableCellRenderer internal class VersionColumn( private val versionSetter: (uiPackageModel: UiPackageModel<*>, newVersion: NormalizedPackageVersion<*>) -> Unit ) : ColumnInfo<PackagesTableItem<*>, UiPackageModel<*>>( PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.columns.versions") ) { private val cellRenderer = PackageVersionTableCellRenderer() private val cellEditor = PackageVersionTableCellEditor() private var onlyStable: Boolean = false private var targetModules: TargetModules = TargetModules.None override fun getRenderer(item: PackagesTableItem<*>): TableCellRenderer = cellRenderer override fun getEditor(item: PackagesTableItem<*>): TableCellEditor = cellEditor override fun isCellEditable(item: PackagesTableItem<*>?) = item?.uiPackageModel?.sortedVersions?.isNotEmpty() ?: false fun updateData(onlyStable: Boolean, targetModules: TargetModules) { this.onlyStable = onlyStable this.targetModules = targetModules cellRenderer.updateData(onlyStable) cellEditor.updateData(onlyStable) } override fun valueOf(item: PackagesTableItem<*>): UiPackageModel<*> = when (item) { is PackagesTableItem.InstalledPackage -> item.uiPackageModel is PackagesTableItem.InstallablePackage -> item.uiPackageModel } override fun setValue(item: PackagesTableItem<*>?, value: UiPackageModel<*>?) { val selectedVersion = value?.selectedVersion if (selectedVersion == null) return if (selectedVersion == item?.uiPackageModel?.selectedVersion) return versionSetter(value, selectedVersion) } }
apache-2.0
07ca1924cce3b7150a8236a6fdcb46e9
48.509434
141
0.785061
5.559322
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/maven/src/org/jetbrains/kotlin/idea/maven/KotlinMavenImporter.kt
1
25249
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.maven import com.intellij.notification.BrowseNotificationAction import com.intellij.notification.Notification import com.intellij.notification.NotificationGroupManager import com.intellij.notification.NotificationType import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.components.StoragePathMacros import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.roots.* import com.intellij.openapi.roots.impl.libraries.LibraryEx import com.intellij.openapi.updateSettings.impl.pluginsAdvertisement.notificationGroup import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.Key import com.intellij.util.PathUtil import org.jdom.Element import org.jdom.Text import org.jetbrains.concurrency.AsyncPromise import org.jetbrains.idea.maven.execution.MavenRunner import org.jetbrains.idea.maven.importing.MavenImporter import org.jetbrains.idea.maven.importing.MavenRootModelAdapter import org.jetbrains.idea.maven.model.MavenPlugin import org.jetbrains.idea.maven.project.* import org.jetbrains.idea.maven.utils.resolved import org.jetbrains.jps.model.java.JavaSourceRootType import org.jetbrains.jps.model.module.JpsModuleSourceRootType import org.jetbrains.kotlin.cli.common.arguments.K2JSCompilerArguments import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments import org.jetbrains.kotlin.cli.common.arguments.parseCommandLineArguments import org.jetbrains.kotlin.compilerRunner.ArgumentUtils import org.jetbrains.kotlin.config.* import org.jetbrains.kotlin.extensions.ProjectExtensionDescriptor import org.jetbrains.kotlin.idea.base.codeInsight.tooling.tooling import org.jetbrains.kotlin.idea.base.platforms.detectLibraryKind import org.jetbrains.kotlin.idea.compiler.configuration.IdeKotlinVersion import org.jetbrains.kotlin.idea.compiler.configuration.KotlinJpsPluginSettings import org.jetbrains.kotlin.idea.compiler.configuration.KotlinPluginLayout import org.jetbrains.kotlin.idea.facet.* import org.jetbrains.kotlin.idea.framework.KotlinSdkType import org.jetbrains.kotlin.idea.maven.configuration.KotlinMavenConfigurator import org.jetbrains.kotlin.platform.IdePlatformKind import org.jetbrains.kotlin.platform.TargetPlatform import org.jetbrains.kotlin.platform.impl.CommonIdePlatformKind import org.jetbrains.kotlin.platform.impl.JsIdePlatformKind import org.jetbrains.kotlin.platform.impl.JvmIdePlatformKind import org.jetbrains.kotlin.platform.impl.isCommon import org.jetbrains.kotlin.platform.isCommon import org.jetbrains.kotlin.utils.SmartList import org.jetbrains.kotlin.utils.addIfNotNull import java.io.File import java.lang.ref.WeakReference import java.util.* interface MavenProjectImportHandler { companion object : ProjectExtensionDescriptor<MavenProjectImportHandler>( "org.jetbrains.kotlin.mavenProjectImportHandler", MavenProjectImportHandler::class.java ) operator fun invoke(facet: KotlinFacet, mavenProject: MavenProject) } class KotlinMavenImporter : MavenImporter(KOTLIN_PLUGIN_GROUP_ID, KOTLIN_PLUGIN_ARTIFACT_ID) { companion object { const val KOTLIN_PLUGIN_GROUP_ID = "org.jetbrains.kotlin" const val KOTLIN_PLUGIN_ARTIFACT_ID = "kotlin-maven-plugin" const val KOTLIN_PLUGIN_SOURCE_DIRS_CONFIG = "sourceDirs" private val KOTLIN_JVM_TARGET_6_NOTIFICATION_DISPLAYED = Key<Boolean>("KOTLIN_JVM_TARGET_6_NOTIFICATION_DISPLAYED") private val KOTLIN_JPS_VERSION_ACCUMULATOR = Key<IdeKotlinVersion>("KOTLIN_JPS_VERSION_ACCUMULATOR") } override fun preProcess( module: Module, mavenProject: MavenProject, changes: MavenProjectChanges, modifiableModelsProvider: IdeModifiableModelsProvider ) { KotlinJpsPluginSettings.getInstance(module.project)?.dropExplicitVersion() module.project.putUserData(KOTLIN_JVM_TARGET_6_NOTIFICATION_DISPLAYED, null) module.project.putUserData(KOTLIN_JPS_VERSION_ACCUMULATOR, null) } override fun process( modifiableModelsProvider: IdeModifiableModelsProvider, module: Module, rootModel: MavenRootModelAdapter, mavenModel: MavenProjectsTree, mavenProject: MavenProject, changes: MavenProjectChanges, mavenProjectToModuleName: MutableMap<MavenProject, String>, postTasks: MutableList<MavenProjectsProcessorTask> ) { if (changes.hasPluginsChanges()) { contributeSourceDirectories(mavenProject, module, rootModel) } val mavenPlugin = mavenProject.findKotlinMavenPlugin() ?: return val currentVersion = mavenPlugin.compilerVersion val accumulatorVersion = module.project.getUserData(KOTLIN_JPS_VERSION_ACCUMULATOR) module.project.putUserData(KOTLIN_JPS_VERSION_ACCUMULATOR, maxOf(accumulatorVersion ?: currentVersion, currentVersion)) } override fun postProcess( module: Module, mavenProject: MavenProject, changes: MavenProjectChanges, modifiableModelsProvider: IdeModifiableModelsProvider ) { super.postProcess(module, mavenProject, changes, modifiableModelsProvider) val project = module.project project.getUserData(KOTLIN_JPS_VERSION_ACCUMULATOR)?.let { version -> KotlinJpsPluginSettings.importKotlinJpsVersionFromExternalBuildSystem( project, version.rawVersion, isDelegatedToExtBuild = MavenRunner.getInstance(project).settings.isDelegateBuildToMaven ) project.putUserData(KOTLIN_JPS_VERSION_ACCUMULATOR, null) } if (changes.hasDependencyChanges()) { scheduleDownloadStdlibSources(mavenProject, module) val targetLibraryKind = detectPlatformByExecutions(mavenProject)?.tooling?.libraryKind if (targetLibraryKind != null) { modifiableModelsProvider.getModifiableRootModel(module).orderEntries().forEachLibrary { library -> if ((library as LibraryEx).kind == null) { val model = modifiableModelsProvider.getModifiableLibraryModel(library) as LibraryEx.ModifiableModelEx detectLibraryKind(library, project)?.let { model.kind = it } } true } } } configureFacet(mavenProject, modifiableModelsProvider, module) } private fun scheduleDownloadStdlibSources(mavenProject: MavenProject, module: Module) { // TODO: here we have to process all kotlin libraries but for now we only handle standard libraries val artifacts = mavenProject.dependencyArtifactIndex.data[KOTLIN_PLUGIN_GROUP_ID]?.values?.flatMap { it.filter { it.resolved() } } ?: emptyList() val libraryNames = mutableSetOf<String?>() OrderEnumerator.orderEntries(module).forEachLibrary { library -> val model = library.modifiableModel try { if (model.getFiles(OrderRootType.SOURCES).isEmpty()) { libraryNames.add(library.name) } } finally { Disposer.dispose(model) } true } val toBeDownloaded = artifacts.filter { it.libraryName in libraryNames } if (toBeDownloaded.isNotEmpty()) { MavenProjectsManager.getInstance(module.project) .scheduleArtifactsDownloading(listOf(mavenProject), toBeDownloaded, true, false, AsyncPromise()) } } private fun configureJSOutputPaths( mavenProject: MavenProject, modifiableRootModel: ModifiableRootModel, facetSettings: KotlinFacetSettings, mavenPlugin: MavenPlugin ) { fun parentPath(path: String): String = File(path).absoluteFile.parentFile.absolutePath val sharedOutputFile = mavenPlugin.configurationElement?.getChild("outputFile")?.text val compilerModuleExtension = modifiableRootModel.getModuleExtension(CompilerModuleExtension::class.java) ?: return val buildDirectory = mavenProject.buildDirectory val executions = mavenPlugin.executions executions.forEach { val explicitOutputFile = it.configurationElement?.getChild("outputFile")?.text ?: sharedOutputFile if (PomFile.KotlinGoals.Js in it.goals) { // see org.jetbrains.kotlin.maven.K2JSCompilerMojo val outputFilePath = PathUtil.toSystemDependentName(explicitOutputFile ?: "$buildDirectory/js/${mavenProject.mavenId.artifactId}.js") compilerModuleExtension.setCompilerOutputPath(parentPath(outputFilePath)) facetSettings.productionOutputPath = outputFilePath } if (PomFile.KotlinGoals.TestJs in it.goals) { // see org.jetbrains.kotlin.maven.KotlinTestJSCompilerMojo val outputFilePath = PathUtil.toSystemDependentName( explicitOutputFile ?: "$buildDirectory/test-js/${mavenProject.mavenId.artifactId}-tests.js" ) compilerModuleExtension.setCompilerOutputPathForTests(parentPath(outputFilePath)) facetSettings.testOutputPath = outputFilePath } } } private data class ImportedArguments(val args: List<String>, val jvmTarget6IsUsed: Boolean) private fun getCompilerArgumentsByConfigurationElement( mavenProject: MavenProject, configuration: Element?, platform: TargetPlatform, project: Project ): ImportedArguments { val arguments = platform.createArguments() var jvmTarget6IsUsed = false arguments.apiVersion = configuration?.getChild("apiVersion")?.text ?: mavenProject.properties["kotlin.compiler.apiVersion"]?.toString() arguments.languageVersion = configuration?.getChild("languageVersion")?.text ?: mavenProject.properties["kotlin.compiler.languageVersion"]?.toString() arguments.multiPlatform = configuration?.getChild("multiPlatform")?.text?.trim()?.toBoolean() ?: false arguments.suppressWarnings = configuration?.getChild("nowarn")?.text?.trim()?.toBoolean() ?: false when (arguments) { is K2JVMCompilerArguments -> { arguments.classpath = configuration?.getChild("classpath")?.text arguments.jdkHome = configuration?.getChild("jdkHome")?.text arguments.javaParameters = configuration?.getChild("javaParameters")?.text?.toBoolean() ?: false val jvmTarget = configuration?.getChild("jvmTarget")?.text ?: mavenProject.properties["kotlin.compiler.jvmTarget"]?.toString() if (jvmTarget == JvmTarget.JVM_1_6.description && KotlinJpsPluginSettings.getInstance(project)?.settings?.version?.isBlank() != false ) { // Load JVM target 1.6 in Maven projects as 1.8, for IDEA platforms <= 222. // The reason is that JVM target 1.6 is no longer supported by the latest Kotlin compiler, yet we'd like JPS projects imported from // Maven to be compilable by IDEA, to avoid breaking local development. // (Since IDEA 222, JPS plugin is unbundled from the Kotlin IDEA plugin, so this change is not needed there in case // when explicit version is specified in kotlinc.xml) arguments.jvmTarget = JvmTarget.JVM_1_8.description jvmTarget6IsUsed = true } else { arguments.jvmTarget = jvmTarget } } is K2JSCompilerArguments -> { arguments.sourceMap = configuration?.getChild("sourceMap")?.text?.trim()?.toBoolean() ?: false arguments.sourceMapPrefix = configuration?.getChild("sourceMapPrefix")?.text?.trim() ?: "" arguments.sourceMapEmbedSources = configuration?.getChild("sourceMapEmbedSources")?.text?.trim() ?: "inlining" arguments.outputFile = configuration?.getChild("outputFile")?.text arguments.metaInfo = configuration?.getChild("metaInfo")?.text?.trim()?.toBoolean() ?: false arguments.moduleKind = configuration?.getChild("moduleKind")?.text arguments.main = configuration?.getChild("main")?.text } } val additionalArgs = SmartList<String>().apply { val argsElement = configuration?.getChild("args") argsElement?.content?.forEach { argElement -> when (argElement) { is Text -> { argElement.text?.let { addAll(splitArgumentString(it)) } } is Element -> { if (argElement.name == "arg") { addIfNotNull(argElement.text) } } } } } parseCommandLineArguments(additionalArgs, arguments) return ImportedArguments(ArgumentUtils.convertArgumentsToStringList(arguments), jvmTarget6IsUsed) } private fun displayJvmTarget6UsageNotification(project: Project) { NotificationGroupManager.getInstance() .getNotificationGroup("Kotlin Maven project import") .createNotification( KotlinMavenBundle.message("configuration.maven.jvm.target.1.6.title"), KotlinMavenBundle.message("configuration.maven.jvm.target.1.6.content"), NotificationType.WARNING, ) .setImportant(true) .notify(project) } private val compilationGoals = listOf( PomFile.KotlinGoals.Compile, PomFile.KotlinGoals.TestCompile, PomFile.KotlinGoals.Js, PomFile.KotlinGoals.TestJs, PomFile.KotlinGoals.MetaData ) private val MavenPlugin.compilerVersion: IdeKotlinVersion get() = version?.let(IdeKotlinVersion::opt) ?: KotlinPluginLayout.standaloneCompilerVersion private fun MavenProject.findKotlinMavenPlugin(): MavenPlugin? = findPlugin( KotlinMavenConfigurator.GROUP_ID, KotlinMavenConfigurator.MAVEN_PLUGIN_ID, ) private var kotlinJsCompilerWarning = WeakReference<Notification>(null) private fun configureFacet(mavenProject: MavenProject, modifiableModelsProvider: IdeModifiableModelsProvider, module: Module) { val mavenPlugin = mavenProject.findKotlinMavenPlugin() ?: return val compilerVersion = mavenPlugin.compilerVersion val kotlinFacet = module.getOrCreateFacet( modifiableModelsProvider, false, ExternalProjectSystemRegistry.MAVEN_EXTERNAL_SOURCE_ID ) // TODO There should be a way to figure out the correct platform version val platform = detectPlatform(mavenProject)?.defaultPlatform kotlinFacet.configureFacet(compilerVersion, platform, modifiableModelsProvider) val facetSettings = kotlinFacet.configuration.settings val configuredPlatform = kotlinFacet.configuration.settings.targetPlatform!! val configuration = mavenPlugin.configurationElement val sharedArguments = getCompilerArgumentsByConfigurationElement(mavenProject, configuration, configuredPlatform, module.project) val executionArguments = mavenPlugin.executions ?.firstOrNull { it.goals.any { s -> s in compilationGoals } } ?.configurationElement?.let { getCompilerArgumentsByConfigurationElement(mavenProject, it, configuredPlatform, module.project) } parseCompilerArgumentsToFacet(sharedArguments.args, emptyList(), kotlinFacet, modifiableModelsProvider) if (executionArguments != null) { parseCompilerArgumentsToFacet(executionArguments.args, emptyList(), kotlinFacet, modifiableModelsProvider) } if (facetSettings.compilerArguments is K2JSCompilerArguments) { configureJSOutputPaths(mavenProject, modifiableModelsProvider.getModifiableRootModel(module), facetSettings, mavenPlugin) deprecatedKotlinJsCompiler(module.project, compilerVersion.kotlinVersion) } MavenProjectImportHandler.getInstances(module.project).forEach { it(kotlinFacet, mavenProject) } setImplementedModuleName(kotlinFacet, mavenProject, module) kotlinFacet.noVersionAutoAdvance() if ((sharedArguments.jvmTarget6IsUsed || executionArguments?.jvmTarget6IsUsed == true) && module.project.getUserData(KOTLIN_JVM_TARGET_6_NOTIFICATION_DISPLAYED) != true ) { module.project.putUserData(KOTLIN_JVM_TARGET_6_NOTIFICATION_DISPLAYED, true) displayJvmTarget6UsageNotification(module.project) } } private fun deprecatedKotlinJsCompiler( project: Project, kotlinVersion: KotlinVersion, ) { if (!kotlinVersion.isAtLeast(1, 7)) return if (kotlinJsCompilerWarning.get() != null) return NotificationGroupManager.getInstance() .getNotificationGroup("Kotlin/JS compiler Maven") .createNotification( KotlinMavenBundle.message("notification.text.kotlin.js.compiler.title"), KotlinMavenBundle.message("notification.text.kotlin.js.compiler.body"), NotificationType.WARNING ) .addAction( BrowseNotificationAction( KotlinMavenBundle.message("notification.text.kotlin.js.compiler.learn.more"), KotlinMavenBundle.message("notification.text.kotlin.js.compiler.link"), ) ) .also { kotlinJsCompilerWarning = WeakReference(it) } .notify(project) } private fun detectPlatform(mavenProject: MavenProject) = detectPlatformByExecutions(mavenProject) ?: detectPlatformByLibraries(mavenProject) private fun detectPlatformByExecutions(mavenProject: MavenProject): IdePlatformKind? { return mavenProject.findPlugin(KOTLIN_PLUGIN_GROUP_ID, KOTLIN_PLUGIN_ARTIFACT_ID)?.executions?.flatMap { it.goals } ?.mapNotNull { goal -> when (goal) { PomFile.KotlinGoals.Compile, PomFile.KotlinGoals.TestCompile -> JvmIdePlatformKind PomFile.KotlinGoals.Js, PomFile.KotlinGoals.TestJs -> JsIdePlatformKind PomFile.KotlinGoals.MetaData -> CommonIdePlatformKind else -> null } }?.distinct()?.singleOrNull() } private fun detectPlatformByLibraries(mavenProject: MavenProject): IdePlatformKind? { for (kind in IdePlatformKind.ALL_KINDS) { val mavenLibraryIds = kind.tooling.mavenLibraryIds if (mavenLibraryIds.any { mavenProject.findDependencies(KOTLIN_PLUGIN_GROUP_ID, it).isNotEmpty() }) { // TODO we could return here the correct version return kind } } return null } // TODO in theory it should work like this but it doesn't as it couldn't unmark source roots that are not roots anymore. // I believe this is something should be done by the underlying maven importer implementation or somewhere else in the IDEA // For now there is a contributeSourceDirectories implementation that deals with the issue // see https://youtrack.jetbrains.com/issue/IDEA-148280 // override fun collectSourceRoots(mavenProject: MavenProject, result: PairConsumer<String, JpsModuleSourceRootType<*>>) { // for ((type, dir) in collectSourceDirectories(mavenProject)) { // val jpsType: JpsModuleSourceRootType<*> = when (type) { // SourceType.PROD -> JavaSourceRootType.SOURCE // SourceType.TEST -> JavaSourceRootType.TEST_SOURCE // } // // result.consume(dir, jpsType) // } // } private fun contributeSourceDirectories(mavenProject: MavenProject, module: Module, rootModel: MavenRootModelAdapter) { val directories = collectSourceDirectories(mavenProject) val toBeAdded = directories.map { it.second }.toSet() val state = module.kotlinImporterComponent val isNonJvmModule = mavenProject .plugins .asSequence() .filter { it.isKotlinPlugin() } .flatMap { it.executions.asSequence() } .flatMap { it.goals.asSequence() } .any { it in PomFile.KotlinGoals.CompileGoals && it !in PomFile.KotlinGoals.JvmGoals } val prodSourceRootType: JpsModuleSourceRootType<*> = if (isNonJvmModule) SourceKotlinRootType else JavaSourceRootType.SOURCE val testSourceRootType: JpsModuleSourceRootType<*> = if (isNonJvmModule) TestSourceKotlinRootType else JavaSourceRootType.TEST_SOURCE for ((type, dir) in directories) { if (rootModel.getSourceFolder(File(dir)) == null) { val jpsType: JpsModuleSourceRootType<*> = when (type) { SourceType.TEST -> testSourceRootType SourceType.PROD -> prodSourceRootType } rootModel.addSourceFolder(dir, jpsType) } } if (isNonJvmModule) { mavenProject.sources.forEach { rootModel.addSourceFolder(it, SourceKotlinRootType) } mavenProject.testSources.forEach { rootModel.addSourceFolder(it, TestSourceKotlinRootType) } mavenProject.resources.forEach { rootModel.addSourceFolder(it.directory, ResourceKotlinRootType) } mavenProject.testResources.forEach { rootModel.addSourceFolder(it.directory, TestResourceKotlinRootType) } KotlinSdkType.setUpIfNeeded() } state.addedSources.filter { it !in toBeAdded }.forEach { rootModel.unregisterAll(it, true, true) state.addedSources.remove(it) } state.addedSources.addAll(toBeAdded) } private fun collectSourceDirectories(mavenProject: MavenProject): List<Pair<SourceType, String>> = mavenProject.plugins.filter { it.isKotlinPlugin() }.flatMap { plugin -> plugin.configurationElement.sourceDirectories().map { SourceType.PROD to it } + plugin.executions.flatMap { execution -> execution.configurationElement.sourceDirectories().map { execution.sourceType() to it } } }.distinct() private fun setImplementedModuleName(kotlinFacet: KotlinFacet, mavenProject: MavenProject, module: Module) { if (kotlinFacet.configuration.settings.targetPlatform.isCommon()) { kotlinFacet.configuration.settings.implementedModuleNames = emptyList() } else { val manager = MavenProjectsManager.getInstance(module.project) val mavenDependencies = mavenProject.dependencies.mapNotNull { manager?.findProject(it) } val implemented = mavenDependencies.filter { detectPlatformByExecutions(it).isCommon } kotlinFacet.configuration.settings.implementedModuleNames = implemented.map { manager.findModule(it)?.name ?: it.displayName } } } } private fun MavenPlugin.isKotlinPlugin() = groupId == KotlinMavenImporter.KOTLIN_PLUGIN_GROUP_ID && artifactId == KotlinMavenImporter.KOTLIN_PLUGIN_ARTIFACT_ID private fun Element?.sourceDirectories(): List<String> = this?.getChildren(KotlinMavenImporter.KOTLIN_PLUGIN_SOURCE_DIRS_CONFIG)?.flatMap { it.children ?: emptyList() }?.map { it.textTrim } ?: emptyList() private fun MavenPlugin.Execution.sourceType() = goals.map { if (isTestGoalName(it)) SourceType.TEST else SourceType.PROD } .distinct() .singleOrNull() ?: SourceType.PROD private fun isTestGoalName(goalName: String) = goalName.startsWith("test-") private enum class SourceType { PROD, TEST } @State( name = "AutoImportedSourceRoots", storages = [(Storage(StoragePathMacros.MODULE_FILE))] ) class KotlinImporterComponent : PersistentStateComponent<KotlinImporterComponent.State> { class State(var directories: List<String> = ArrayList()) val addedSources: MutableSet<String> = Collections.synchronizedSet(HashSet<String>()) override fun loadState(state: State) { addedSources.clear() addedSources.addAll(state.directories) } override fun getState(): State { return State(addedSources.sorted()) } } internal val Module.kotlinImporterComponent: KotlinImporterComponent get() = getService(KotlinImporterComponent::class.java) ?: error("Service ${KotlinImporterComponent::class.java} not found")
apache-2.0
91d642534053de76484567e01519c03f
46.639623
151
0.689295
5.421731
false
true
false
false
holisticon/ranked
backend/views/leaderboard/src/main/kotlin/PlayerRankingBySets.kt
1
4684
@file:Suppress("UNUSED") package de.holisticon.ranked.view.leaderboard import de.holisticon.ranked.model.Team import de.holisticon.ranked.model.TeamColor import de.holisticon.ranked.model.TimedMatchSet import de.holisticon.ranked.model.UserName import de.holisticon.ranked.model.event.MatchCreated import org.axonframework.config.ProcessingGroup import org.axonframework.eventhandling.EventHandler import org.springframework.stereotype.Component import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController import java.time.temporal.ChronoUnit /** * The rest controller provides getters for key figures based on the played sets */ @RestController @RequestMapping(value = ["/view/sets"]) class PlayerRankingBySetsView( private val playerRankingBySets: PlayerRankingBySets ) { @GetMapping(path = ["/player/{userName}"]) fun setStatsByPlayer(@PathVariable("userName") userName: String): PlayerSetStats = playerRankingBySets.getSetStatsForPlayer(userName) } @Component @ProcessingGroup(PROCESSING_GROUP) class PlayerRankingBySets { private val setStats = mutableMapOf<UserName, PlayerSetStats>() @EventHandler fun on(e: MatchCreated) { ensurePlayerStatExists(e.teamBlue); ensurePlayerStatExists(e.teamRed); var lastSetEndTime = e.startTime.toLocalTime(); e.matchSets.forEach { if (it is TimedMatchSet) { val endTime = it.goals.last().second.toLocalTime() val setTime = ChronoUnit.SECONDS.between(lastSetEndTime, endTime) setAvgSetTimeForPlayersOfTeam(e.teamRed, setTime) setAvgSetTimeForPlayersOfTeam(e.teamBlue, setTime) lastSetEndTime = endTime } if (it.winner() === TeamColor.RED) { incWonSetsForPlayersOfTeam(e.teamRed, it.offenseRed) incLostSetsForPlayersOfTeam(e.teamBlue, it.offenseBlue) } else { incWonSetsForPlayersOfTeam(e.teamBlue, it.offenseBlue) incLostSetsForPlayersOfTeam(e.teamRed, it.offenseRed) } } } private fun ensurePlayerStatExists(team: Team) { setStats.putIfAbsent(team.player1, PlayerSetStats(team.player1, 0, 0, 0, 0, 0.0)) setStats.putIfAbsent(team.player2, PlayerSetStats(team.player2, 0, 0, 0, 0, 0.0)) } private fun incWonSetsForPlayersOfTeam(team: Team, offense: UserName) { if (team.player1 == offense) { setStats[team.player1]!!.incWonSetsInOffense() setStats[team.player2]!!.incWonSetsInDefense() } else if (team.player2 == offense) { setStats[team.player1]!!.incWonSetsInDefense() setStats[team.player2]!!.incWonSetsInOffense() } } private fun incLostSetsForPlayersOfTeam(team: Team, offense: UserName) { if (team.player1 == offense) { setStats[team.player1]!!.incLostSetsInOffense() setStats[team.player2]!!.incLostSetsInDefense() } else if (team.player2 == offense) { setStats[team.player1]!!.incLostSetsInDefense() setStats[team.player2]!!.incLostSetsInOffense() } } private fun setAvgSetTimeForPlayersOfTeam(team: Team, setTime: Long) { setAvgSetTimeForPlayer(team.player1, setTime); setAvgSetTimeForPlayer(team.player2, setTime); } private fun setAvgSetTimeForPlayer(player: UserName, setTime: Long) { val stats = setStats[player]!!; val totalSets = stats.lostSets.whenInOffense + stats.lostSets.whenInDefense + stats.wonSets.whenInOffense + stats.wonSets.whenInDefense; stats.averageSetTime = calcAvgSetTime(totalSets, stats.averageSetTime, setTime); } private fun calcAvgSetTime(setCount: Int, averageSetTime: Double, setTime: Long): Double { return (averageSetTime * setCount + setTime) / (setCount + 1); } fun getSetStatsForPlayer(playerName: String) = setStats[UserName(playerName)] ?: PlayerSetStats(UserName(playerName), 0, 0, 0, 0, 0.0) } data class PlayerSetStats(val userName: UserName, val wonSets: InPosition<Int>, val lostSets: InPosition<Int>, var averageSetTime: Double) { constructor(userName: UserName, wonSetsInOffense: Int, wonSetsInDefense: Int, lostSetsInOffense: Int, lostSetsInDefense: Int, averageSetTime: Double) : this(userName, InPosition(wonSetsInOffense, wonSetsInDefense), InPosition(lostSetsInOffense, lostSetsInDefense), averageSetTime) fun incWonSetsInOffense() { wonSets.whenInOffense++ } fun incWonSetsInDefense() { wonSets.whenInDefense++ } fun incLostSetsInOffense() { lostSets.whenInOffense++ } fun incLostSetsInDefense() { lostSets.whenInDefense++ } }
bsd-3-clause
9e39ad7ae1a5abf9a92d91a71b9f5404
35.030769
140
0.741247
3.711569
false
false
false
false
android/compose-samples
Crane/app/src/main/java/androidx/compose/samples/crane/base/BaseUserInput.kt
1
5916
/* * Copyright 2020 The Android Open Source Project * * 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 * * https://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. */ package androidx.compose.samples.crane.base import androidx.annotation.DrawableRes import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.text.BasicTextField import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.Icon import androidx.compose.material.LocalContentColor import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.samples.crane.R import androidx.compose.samples.crane.ui.CraneTheme import androidx.compose.samples.crane.ui.captionTextStyle import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.input.TextFieldValue import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp @Composable fun SimpleUserInput( text: String? = null, caption: String? = null, @DrawableRes vectorImageId: Int? = null ) { CraneUserInput( caption = if (text == null) caption else null, text = text ?: "", vectorImageId = vectorImageId ) } @Composable fun CraneUserInput( text: String, modifier: Modifier = Modifier, onClick: () -> Unit = { }, caption: String? = null, @DrawableRes vectorImageId: Int? = null, tint: Color = LocalContentColor.current ) { CraneBaseUserInput( modifier = modifier, onClick = onClick, caption = caption, vectorImageId = vectorImageId, tintIcon = { text.isNotEmpty() }, tint = tint ) { Text(text = text, style = MaterialTheme.typography.body1.copy(color = tint)) } } @Composable fun CraneEditableUserInput( hint: String, caption: String? = null, @DrawableRes vectorImageId: Int? = null, onInputChanged: (String) -> Unit ) { var textFieldState by remember { mutableStateOf(TextFieldValue()) } CraneBaseUserInput( caption = caption, tintIcon = { textFieldState.text.isNotEmpty() }, showCaption = { textFieldState.text.isNotEmpty() }, vectorImageId = vectorImageId ) { BasicTextField( value = textFieldState, onValueChange = { textFieldState = it onInputChanged(textFieldState.text) }, textStyle = MaterialTheme.typography.body1.copy(color = LocalContentColor.current), cursorBrush = SolidColor(LocalContentColor.current), decorationBox = { innerTextField -> if (hint.isNotEmpty() && textFieldState.text.isEmpty()) { Text( text = hint, style = captionTextStyle.copy(color = LocalContentColor.current) ) } innerTextField() } ) } } @OptIn(ExperimentalMaterialApi::class) @Composable private fun CraneBaseUserInput( modifier: Modifier = Modifier, onClick: () -> Unit = { }, caption: String? = null, @DrawableRes vectorImageId: Int? = null, showCaption: () -> Boolean = { true }, tintIcon: () -> Boolean, tint: Color = LocalContentColor.current, content: @Composable () -> Unit ) { Surface( modifier = modifier, onClick = onClick, color = MaterialTheme.colors.primaryVariant ) { Row(Modifier.padding(all = 12.dp)) { if (vectorImageId != null) { Icon( modifier = Modifier.size(24.dp, 24.dp), painter = painterResource(id = vectorImageId), tint = if (tintIcon()) tint else Color(0x80FFFFFF), contentDescription = null ) Spacer(Modifier.width(8.dp)) } if (caption != null && showCaption()) { Text( modifier = Modifier.align(Alignment.CenterVertically), text = caption, style = (captionTextStyle).copy(color = tint) ) Spacer(Modifier.width(8.dp)) } Row( Modifier .weight(1f) .align(Alignment.CenterVertically) ) { content() } } } } @Preview @Composable fun PreviewInput() { CraneTheme { Surface { CraneBaseUserInput( tintIcon = { true }, vectorImageId = R.drawable.ic_plane, caption = "Caption", showCaption = { true } ) { Text(text = "text", style = MaterialTheme.typography.body1) } } } }
apache-2.0
860f05a9fcece519031bf4773c3c5cb6
31.327869
95
0.62593
4.661939
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/codeInsight/codeVision/InterfaceMethodUsages.kt
12
487
// MODE: usages <# block [ 1 Usage] #> interface SomeInterface { <# block [ 3 Usages] #> fun someFun(): String fun someOtherFun() = someFun() // <== (1): delegation from another interface method val someProperty = someFun() // <== (2): property initializer } fun main() { val instance = object: SomeInterface { <# block [ 1 Usage] #> override fun someFun(): String {} // <== (): used below } instance.someFun() <== (3): call on an instance }
apache-2.0
068a4ae7ad69337b55ffb85e3eead27c
27.705882
87
0.585216
4.092437
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/completion/src/org/jetbrains/kotlin/idea/completion/CompletionBenchmarkSink.kt
5
3409
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.completion import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.Channel.Factory.CONFLATED import kotlinx.coroutines.channels.onClosed import java.lang.System.currentTimeMillis interface CompletionBenchmarkSink { fun onCompletionStarted(completionSession: CompletionSession) fun onCompletionEnded(completionSession: CompletionSession, canceled: Boolean) fun onFlush(completionSession: CompletionSession) companion object { fun enableAndGet(): Impl = Impl().also { _instance = it } fun disable() { _instance.let { (it as? Impl)?.channel?.close() } _instance = Empty } val instance get() = _instance private var _instance: CompletionBenchmarkSink = Empty } private object Empty : CompletionBenchmarkSink { override fun onCompletionStarted(completionSession: CompletionSession) {} override fun onCompletionEnded(completionSession: CompletionSession, canceled: Boolean) {} override fun onFlush(completionSession: CompletionSession) {} } class Impl : CompletionBenchmarkSink { private val pendingSessions = mutableListOf<CompletionSession>() val channel = Channel<CompletionBenchmarkResults>(capacity = CONFLATED) private val perSessionResults = LinkedHashMap<CompletionSession, PerSessionResults>() private var start: Long = 0 override fun onCompletionStarted(completionSession: CompletionSession) = synchronized(this) { if (pendingSessions.isEmpty()) start = currentTimeMillis() pendingSessions += completionSession perSessionResults[completionSession] = PerSessionResults() } override fun onCompletionEnded(completionSession: CompletionSession, canceled: Boolean) = synchronized(this) { pendingSessions -= completionSession perSessionResults[completionSession]?.onEnd(canceled) if (pendingSessions.isEmpty()) { val firstFlush = perSessionResults.values.filterNot { results -> results.canceled }.minOfOrNull { it.firstFlush } ?: 0 val full = perSessionResults.values.maxOfOrNull { it.full } ?: 0 channel.trySend(CompletionBenchmarkResults(firstFlush, full)).onClosed { throw IllegalStateException(it) } reset() } } override fun onFlush(completionSession: CompletionSession) = synchronized(this) { perSessionResults[completionSession]?.onFirstFlush() Unit } fun reset() = synchronized(this) { pendingSessions.clear() perSessionResults.clear() } data class CompletionBenchmarkResults(var firstFlush: Long = 0, var full: Long = 0) private inner class PerSessionResults { var firstFlush = 0L var full = 0L var canceled = false fun onFirstFlush() { firstFlush = currentTimeMillis() - start } fun onEnd(canceled: Boolean) { full = currentTimeMillis() - start this.canceled = canceled } } } }
apache-2.0
18ea5d7e3bbca6f3ec239dc2e3c95ca1
37.303371
158
0.662364
5.351648
false
false
false
false
TimePath/launcher
src/main/kotlin/com/timepath/swing/ObjectBasedTableModel.kt
1
2749
package com.timepath.swing import java.util.ArrayList import java.util.Arrays import javax.swing.table.AbstractTableModel /** * @param <E> */ public abstract class ObjectBasedTableModel<E> protected constructor() : AbstractTableModel() { private val columns = Arrays.asList<String>(*columns()) private var rows: MutableList<E> = ArrayList() public fun getRows(): List<E> { return rows } public fun setRows(rows: MutableList<E>) { fireTableRowsDeleted(0, Math.max(this.rows.size() - 1, 0)) this.rows = rows fireTableRowsInserted(0, Math.max(this.rows.size() - 1, 0)) } /** * Add Object o to the model * * @param o the Object * @return true if added */ public fun add(o: E): Boolean { val idx = rows.indexOf(o) if (idx >= 0) { return false } rows.add(o) fireTableRowsInserted(rows.size() - 1, rows.size() - 1) return true } public abstract fun columns(): Array<String> override fun getColumnName(column: Int): String { if (column < columns.size()) { val name = columns[column] if (name != null) return name } return super.getColumnName(column) } override fun getRowCount(): Int { return rows.size() } override fun getColumnCount(): Int { return columns.size() } override fun getValueAt(rowIndex: Int, columnIndex: Int): Any? { return get(rows[rowIndex], columnIndex) } /** * Gets a property from an Object based on an index * * @param o the Object * @param columnIndex index to Object property * @return the property */ public abstract fun get(o: E, columnIndex: Int): Any? /** * Remove Object o from the model * * @param o the Object * @return true if removed */ public fun remove(o: E): Boolean { val idx = rows.indexOf(o) if (idx < 0) { return false } rows.remove(idx) fireTableRowsDeleted(idx, idx) return true } override fun isCellEditable(rowIndex: Int, columnIndex: Int): Boolean { return isCellEditable(rows[rowIndex], columnIndex) } protected open fun isCellEditable(e: E, columnIndex: Int): Boolean { return false } /** * Fire update for Object o in the model * * @param o the Object * @return true if not updated (because the Object isn't in the model) */ public fun update(o: E): Boolean { val idx = rows.indexOf(o) if (idx < 0) { return false } fireTableRowsUpdated(idx, idx) return true } }
artistic-2.0
8a8c44c43387e7b1ccd5a038f3fade8e
23.765766
95
0.578392
4.165152
false
false
false
false
fkorotkov/k8s-kotlin-dsl
DSLs/kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/kubernetes/autoscaling/v2beta2/ClassBuilders.kt
1
7747
// GENERATE package com.fkorotkov.kubernetes.autoscaling.v2beta2 import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.ContainerResourceMetricSource as v2beta2_ContainerResourceMetricSource import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.ContainerResourceMetricStatus as v2beta2_ContainerResourceMetricStatus import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.CrossVersionObjectReference as v2beta2_CrossVersionObjectReference import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.ExternalMetricSource as v2beta2_ExternalMetricSource import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.ExternalMetricStatus as v2beta2_ExternalMetricStatus import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.HPAScalingPolicy as v2beta2_HPAScalingPolicy import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.HPAScalingRules as v2beta2_HPAScalingRules import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.HorizontalPodAutoscaler as v2beta2_HorizontalPodAutoscaler import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.HorizontalPodAutoscalerBehavior as v2beta2_HorizontalPodAutoscalerBehavior import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.HorizontalPodAutoscalerCondition as v2beta2_HorizontalPodAutoscalerCondition import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.HorizontalPodAutoscalerList as v2beta2_HorizontalPodAutoscalerList import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.HorizontalPodAutoscalerSpec as v2beta2_HorizontalPodAutoscalerSpec import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.HorizontalPodAutoscalerStatus as v2beta2_HorizontalPodAutoscalerStatus import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.MetricIdentifier as v2beta2_MetricIdentifier import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.MetricSpec as v2beta2_MetricSpec import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.MetricStatus as v2beta2_MetricStatus import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.MetricTarget as v2beta2_MetricTarget import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.MetricValueStatus as v2beta2_MetricValueStatus import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.ObjectMetricSource as v2beta2_ObjectMetricSource import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.ObjectMetricStatus as v2beta2_ObjectMetricStatus import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.PodsMetricSource as v2beta2_PodsMetricSource import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.PodsMetricStatus as v2beta2_PodsMetricStatus import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.ResourceMetricSource as v2beta2_ResourceMetricSource import io.fabric8.kubernetes.api.model.autoscaling.v2beta2.ResourceMetricStatus as v2beta2_ResourceMetricStatus fun newContainerResourceMetricSource(block : v2beta2_ContainerResourceMetricSource.() -> Unit = {}): v2beta2_ContainerResourceMetricSource { val instance = v2beta2_ContainerResourceMetricSource() instance.block() return instance } fun newContainerResourceMetricStatus(block : v2beta2_ContainerResourceMetricStatus.() -> Unit = {}): v2beta2_ContainerResourceMetricStatus { val instance = v2beta2_ContainerResourceMetricStatus() instance.block() return instance } fun newCrossVersionObjectReference(block : v2beta2_CrossVersionObjectReference.() -> Unit = {}): v2beta2_CrossVersionObjectReference { val instance = v2beta2_CrossVersionObjectReference() instance.block() return instance } fun newExternalMetricSource(block : v2beta2_ExternalMetricSource.() -> Unit = {}): v2beta2_ExternalMetricSource { val instance = v2beta2_ExternalMetricSource() instance.block() return instance } fun newExternalMetricStatus(block : v2beta2_ExternalMetricStatus.() -> Unit = {}): v2beta2_ExternalMetricStatus { val instance = v2beta2_ExternalMetricStatus() instance.block() return instance } fun newHPAScalingPolicy(block : v2beta2_HPAScalingPolicy.() -> Unit = {}): v2beta2_HPAScalingPolicy { val instance = v2beta2_HPAScalingPolicy() instance.block() return instance } fun newHPAScalingRules(block : v2beta2_HPAScalingRules.() -> Unit = {}): v2beta2_HPAScalingRules { val instance = v2beta2_HPAScalingRules() instance.block() return instance } fun newHorizontalPodAutoscaler(block : v2beta2_HorizontalPodAutoscaler.() -> Unit = {}): v2beta2_HorizontalPodAutoscaler { val instance = v2beta2_HorizontalPodAutoscaler() instance.block() return instance } fun newHorizontalPodAutoscalerBehavior(block : v2beta2_HorizontalPodAutoscalerBehavior.() -> Unit = {}): v2beta2_HorizontalPodAutoscalerBehavior { val instance = v2beta2_HorizontalPodAutoscalerBehavior() instance.block() return instance } fun newHorizontalPodAutoscalerCondition(block : v2beta2_HorizontalPodAutoscalerCondition.() -> Unit = {}): v2beta2_HorizontalPodAutoscalerCondition { val instance = v2beta2_HorizontalPodAutoscalerCondition() instance.block() return instance } fun newHorizontalPodAutoscalerList(block : v2beta2_HorizontalPodAutoscalerList.() -> Unit = {}): v2beta2_HorizontalPodAutoscalerList { val instance = v2beta2_HorizontalPodAutoscalerList() instance.block() return instance } fun newHorizontalPodAutoscalerSpec(block : v2beta2_HorizontalPodAutoscalerSpec.() -> Unit = {}): v2beta2_HorizontalPodAutoscalerSpec { val instance = v2beta2_HorizontalPodAutoscalerSpec() instance.block() return instance } fun newHorizontalPodAutoscalerStatus(block : v2beta2_HorizontalPodAutoscalerStatus.() -> Unit = {}): v2beta2_HorizontalPodAutoscalerStatus { val instance = v2beta2_HorizontalPodAutoscalerStatus() instance.block() return instance } fun newMetricIdentifier(block : v2beta2_MetricIdentifier.() -> Unit = {}): v2beta2_MetricIdentifier { val instance = v2beta2_MetricIdentifier() instance.block() return instance } fun newMetricSpec(block : v2beta2_MetricSpec.() -> Unit = {}): v2beta2_MetricSpec { val instance = v2beta2_MetricSpec() instance.block() return instance } fun newMetricStatus(block : v2beta2_MetricStatus.() -> Unit = {}): v2beta2_MetricStatus { val instance = v2beta2_MetricStatus() instance.block() return instance } fun newMetricTarget(block : v2beta2_MetricTarget.() -> Unit = {}): v2beta2_MetricTarget { val instance = v2beta2_MetricTarget() instance.block() return instance } fun newMetricValueStatus(block : v2beta2_MetricValueStatus.() -> Unit = {}): v2beta2_MetricValueStatus { val instance = v2beta2_MetricValueStatus() instance.block() return instance } fun newObjectMetricSource(block : v2beta2_ObjectMetricSource.() -> Unit = {}): v2beta2_ObjectMetricSource { val instance = v2beta2_ObjectMetricSource() instance.block() return instance } fun newObjectMetricStatus(block : v2beta2_ObjectMetricStatus.() -> Unit = {}): v2beta2_ObjectMetricStatus { val instance = v2beta2_ObjectMetricStatus() instance.block() return instance } fun newPodsMetricSource(block : v2beta2_PodsMetricSource.() -> Unit = {}): v2beta2_PodsMetricSource { val instance = v2beta2_PodsMetricSource() instance.block() return instance } fun newPodsMetricStatus(block : v2beta2_PodsMetricStatus.() -> Unit = {}): v2beta2_PodsMetricStatus { val instance = v2beta2_PodsMetricStatus() instance.block() return instance } fun newResourceMetricSource(block : v2beta2_ResourceMetricSource.() -> Unit = {}): v2beta2_ResourceMetricSource { val instance = v2beta2_ResourceMetricSource() instance.block() return instance } fun newResourceMetricStatus(block : v2beta2_ResourceMetricStatus.() -> Unit = {}): v2beta2_ResourceMetricStatus { val instance = v2beta2_ResourceMetricStatus() instance.block() return instance }
mit
948840ca470bd9c91b752a5fd2671412
38.52551
149
0.809475
3.527778
false
false
false
false
AVnetWS/Hentoid
app/src/main/java/me/devsaki/hentoid/fragments/intro/ImportIntroFragment.kt
1
10818
package me.devsaki.hentoid.fragments.intro import android.content.DialogInterface import android.net.Uri import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ProgressBar import androidx.appcompat.app.AlertDialog import androidx.fragment.app.Fragment import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.snackbar.BaseTransientBottomBar import com.google.android.material.snackbar.Snackbar import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.Disposable import me.devsaki.hentoid.R import me.devsaki.hentoid.activities.IntroActivity import me.devsaki.hentoid.databinding.IncludeImportStepsBinding import me.devsaki.hentoid.databinding.IntroSlide04Binding import me.devsaki.hentoid.events.ProcessEvent import me.devsaki.hentoid.ui.BlinkAnimation import me.devsaki.hentoid.util.FileHelper import me.devsaki.hentoid.util.ImportHelper import me.devsaki.hentoid.util.ImportHelper.setAndScanHentoidFolder import me.devsaki.hentoid.util.Preferences import me.devsaki.hentoid.workers.ImportWorker import org.greenrobot.eventbus.EventBus import org.greenrobot.eventbus.Subscribe import org.greenrobot.eventbus.ThreadMode import timber.log.Timber class ImportIntroFragment : Fragment(R.layout.intro_slide_04) { private var _binding: IntroSlide04Binding? = null private var _mergedBinding: IncludeImportStepsBinding? = null private val binding get() = _binding!! private val mergedBinding get() = _mergedBinding!! private lateinit var importDisposable: Disposable private val pickFolder = registerForActivityResult(ImportHelper.PickFolderContract()) { res -> onFolderPickerResult(res.left, res.right) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) EventBus.getDefault().register(this) } override fun onDestroy() { EventBus.getDefault().unregister(this) super.onDestroy() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = IntroSlide04Binding.inflate(inflater, container, false) // We need to manually bind the merged view - it won't work at runtime with the main view alone _mergedBinding = IncludeImportStepsBinding.bind(binding.root) return binding.root } override fun onDestroyView() { super.onDestroyView() _binding = null } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { mergedBinding.importStep1Button.setOnClickListener { binding.skipBtn.visibility = View.INVISIBLE pickFolder.launch(0) } mergedBinding.importStep1Button.visibility = View.VISIBLE binding.skipBtn.setOnClickListener { askSkip() } } private fun onFolderPickerResult(resultCode: Int, treeUri: Uri?) { when (resultCode) { ImportHelper.PickerResult.OK -> { if (null == treeUri) return binding.waitTxt.visibility = View.VISIBLE val animation = BlinkAnimation(750, 20) binding.waitTxt.startAnimation(animation) importDisposable = io.reactivex.Single.fromCallable { setAndScanHentoidFolder( requireContext(), treeUri, true, null ) } .subscribeOn(io.reactivex.schedulers.Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { result: Int -> run { binding.waitTxt.clearAnimation() binding.waitTxt.visibility = View.GONE onScanHentoidFolderResult(result) } }, { t: Throwable? -> Timber.w(t) } ) } ImportHelper.PickerResult.KO_CANCELED -> { Snackbar.make( binding.root, R.string.import_canceled, BaseTransientBottomBar.LENGTH_LONG ).show() binding.skipBtn.visibility = View.VISIBLE } ImportHelper.PickerResult.KO_OTHER, ImportHelper.PickerResult.KO_NO_URI -> { Snackbar.make( binding.root, R.string.import_other, BaseTransientBottomBar.LENGTH_LONG ).show() binding.skipBtn.visibility = View.VISIBLE } } } private fun onScanHentoidFolderResult(resultCode: Int) { importDisposable.dispose() when (resultCode) { ImportHelper.ProcessFolderResult.OK_EMPTY_FOLDER -> nextStep() ImportHelper.ProcessFolderResult.OK_LIBRARY_DETECTED -> { // Import service is already launched by the Helper; nothing else to do updateOnSelectFolder() return } ImportHelper.ProcessFolderResult.OK_LIBRARY_DETECTED_ASK -> { updateOnSelectFolder() ImportHelper.showExistingLibraryDialog(requireContext()) { onCancelExistingLibraryDialog() } return } ImportHelper.ProcessFolderResult.KO_INVALID_FOLDER -> Snackbar.make( binding.root, R.string.import_invalid, BaseTransientBottomBar.LENGTH_LONG ).show() ImportHelper.ProcessFolderResult.KO_APP_FOLDER -> Snackbar.make( binding.root, R.string.import_invalid, BaseTransientBottomBar.LENGTH_LONG ).show() ImportHelper.ProcessFolderResult.KO_DOWNLOAD_FOLDER -> Snackbar.make( binding.root, R.string.import_download_folder, BaseTransientBottomBar.LENGTH_LONG ).show() ImportHelper.ProcessFolderResult.KO_CREATE_FAIL -> Snackbar.make( binding.root, R.string.import_create_fail, BaseTransientBottomBar.LENGTH_LONG ).show() ImportHelper.ProcessFolderResult.KO_OTHER -> Snackbar.make( binding.root, R.string.import_other, BaseTransientBottomBar.LENGTH_LONG ).show() } binding.skipBtn.visibility = View.VISIBLE } private fun updateOnSelectFolder() { mergedBinding.importStep1Button.visibility = View.INVISIBLE mergedBinding.importStep1Folder.text = FileHelper.getFullPathFromTreeUri( requireContext(), Uri.parse(Preferences.getStorageUri()) ) mergedBinding.importStep1Check.visibility = View.VISIBLE mergedBinding.importStep2.visibility = View.VISIBLE mergedBinding.importStep2Bar.isIndeterminate = true binding.skipBtn.visibility = View.INVISIBLE } private fun onCancelExistingLibraryDialog() { // Revert back to initial state where only the "Select folder" button is visible mergedBinding.importStep1Button.visibility = View.VISIBLE mergedBinding.importStep1Folder.text = "" mergedBinding.importStep1Check.visibility = View.INVISIBLE mergedBinding.importStep2.visibility = View.INVISIBLE binding.skipBtn.visibility = View.VISIBLE } @Subscribe(threadMode = ThreadMode.MAIN) fun onMigrationEvent(event: ProcessEvent) { val progressBar: ProgressBar = when (event.step) { ImportWorker.STEP_2_BOOK_FOLDERS -> mergedBinding.importStep2Bar ImportWorker.STEP_3_BOOKS -> mergedBinding.importStep3Bar else -> mergedBinding.importStep4Bar } if (ProcessEvent.EventType.PROGRESS == event.eventType) { if (event.elementsTotal > -1) { progressBar.isIndeterminate = false progressBar.max = event.elementsTotal progressBar.progress = event.elementsOK + event.elementsKO } else progressBar.isIndeterminate = true if (ImportWorker.STEP_3_BOOKS == event.step) { mergedBinding.importStep2Check.visibility = View.VISIBLE mergedBinding.importStep3.visibility = View.VISIBLE mergedBinding.importStep3Text.text = resources.getString( R.string.api29_migration_step3, event.elementsKO + event.elementsOK, event.elementsTotal ) } else if (ImportWorker.STEP_4_QUEUE_FINAL == event.step) { mergedBinding.importStep3Check.visibility = View.VISIBLE mergedBinding.importStep4.visibility = View.VISIBLE } } else if (ProcessEvent.EventType.COMPLETE == event.eventType) { when { ImportWorker.STEP_2_BOOK_FOLDERS == event.step -> { mergedBinding.importStep2Check.visibility = View.VISIBLE mergedBinding.importStep3.visibility = View.VISIBLE } ImportWorker.STEP_3_BOOKS == event.step -> { mergedBinding.importStep3Text.text = resources.getString( R.string.api29_migration_step3, event.elementsTotal, event.elementsTotal ) mergedBinding.importStep3Check.visibility = View.VISIBLE mergedBinding.importStep4.visibility = View.VISIBLE } ImportWorker.STEP_4_QUEUE_FINAL == event.step -> { mergedBinding.importStep4Check.visibility = View.VISIBLE nextStep() } } } } private fun askSkip() { val materialDialog: AlertDialog = MaterialAlertDialogBuilder(requireContext()) .setTitle(R.string.slide_04_skip_title) .setMessage(R.string.slide_04_skip_msg) .setCancelable(true) .setPositiveButton(android.R.string.ok) { _: DialogInterface, _: Int -> nextStep() } .setNegativeButton(android.R.string.cancel, null) .create() materialDialog.setIcon(R.drawable.ic_warning) materialDialog.show() } private fun nextStep() { val parentActivity = requireActivity() as IntroActivity parentActivity.nextStep() binding.skipBtn.visibility = View.VISIBLE } }
apache-2.0
25eb4e4ac84b23e28149db5ebdf60bcf
40.611538
141
0.618968
5.062237
false
false
false
false
yiyocx/YitLab
app/src/main/kotlin/yiyo/gitlabandroid/mvp/presenters/LoginPresenter.kt
2
2570
package yiyo.gitlabandroid.mvp.presenters import android.text.TextUtils import android.util.Log import yiyo.gitlabandroid.R import yiyo.gitlabandroid.domain.LoginUseCase import yiyo.gitlabandroid.model.entities.Session import yiyo.gitlabandroid.mvp.views.LoginView import yiyo.gitlabandroid.utils.Configuration import yiyo.gitlabandroid.utils.tag /** * Created by yiyo on 11/07/15. */ class LoginPresenter(private val loginView: LoginView) : Presenter { override fun onResume() { // Unused } override fun onPause() { // Unused } fun login(username: String, password: String) { loginView.showProgress() if (valid(username, password)) { LoginUseCase(username, password, loginView.getContext()) .execute() .subscribe( { session: Session -> onSessionReceived(session) }, { error: Throwable -> manageError(error) }, { loginView.hideProgress() } ) } else { loginView.hideProgress() } } fun valid(username: String, password: String): Boolean { var valid = true // Check for a valid password, if the user entered one. if (TextUtils.isEmpty(password)) { loginView.setupPasswordError(loginView.getContext().getString(R.string.error_field_required)) valid = false } else { loginView.setupPasswordError(null) } // Check for a valid username address. if (TextUtils.isEmpty(username)) { loginView.setupUsernameError(loginView.getContext().getString(R.string.error_field_required)) valid = false } else { loginView.setupUsernameError(null) } return valid } fun onSessionReceived(session: Session) { val configuration = Configuration(loginView.getContext()) val sessionCreated = configuration.createSession( session.name, session.username, session.email, session.privateToken, session.id) if (sessionCreated) { loginView.navigateToHome() Log.i(tag(), "The user has successfully logged") } else { Log.e(tag(), "There was a problem creating the session in the SharedPreferences") } } fun manageError(error: Throwable) { loginView.hideProgress() // Log.e(tag(), error.getMessage(), error) // loginView.showConnectionError(error as RetrofitError) } }
gpl-2.0
fd8c48ae92d9934b273ec40f11cd380d
29.595238
105
0.614786
4.622302
false
false
false
false
oversecio/oversec_crypto
crypto/src/main/java/io/oversec/one/crypto/sym/ui/KeyDetailsActivity.kt
1
12074
package io.oversec.one.crypto.sym.ui import android.annotation.SuppressLint import android.app.Activity import android.app.Fragment import android.content.Context import android.content.Intent import android.content.IntentSender import android.graphics.Bitmap import android.os.Bundle import android.util.TypedValue import android.view.Menu import android.view.MenuItem import android.view.View import android.view.WindowManager import com.afollestad.materialdialogs.MaterialDialog import io.oversec.one.common.MainPreferences import io.oversec.one.crypto.Help import io.oversec.one.crypto.R import io.oversec.one.crypto.TemporaryContentProvider import io.oversec.one.crypto.sym.* import io.oversec.one.crypto.symbase.KeyUtil import io.oversec.one.crypto.symbase.OversecKeyCacheListener import io.oversec.one.crypto.ui.NewPasswordInputDialog import io.oversec.one.crypto.ui.NewPasswordInputDialogCallback import io.oversec.one.crypto.ui.SecureBaseActivity import io.oversec.one.crypto.ui.util.Util import kotlinx.android.synthetic.main.sym_activity_key_details.* import kotlinx.android.synthetic.main.sym_content_key_details.* import roboguice.util.Ln import java.text.SimpleDateFormat class KeyDetailsActivity : SecureBaseActivity(), OversecKeyCacheListener { private lateinit var mKeystore:OversecKeystore2 private var mId: Long = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mKeystore = OversecKeystore2.getInstance(this) if (!MainPreferences.isAllowScreenshots(this)) { window.setFlags( WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE ) } mId = intent.getLongExtra(EXTRA_ID, 0) val key = mKeystore.getSymmetricKeyEncrypted(mId) if (key == null) { Ln.w("couldn't find request key with id %s", mId) finish() return } setContentView(R.layout.sym_activity_key_details) setSupportActionBar(toolbar) supportActionBar!!.setDisplayHomeAsUpEnabled(true) btRevealQr.setOnClickListener { showPlainKeyQR() } tv_alias.text = key.name tv_hash.text = SymUtil.longToPrettyHex(key.id) val createdDate = key.createdDate tv_date.text = SimpleDateFormat.getDateTimeInstance().format( createdDate ) setKeyImage(true) fab.setOnClickListener { showConfirmDialog() } refreshConfirm() SymUtil.applyAvatar(tvAvatar, key.name!!) mKeystore.addKeyCacheListener(this) } private fun showPlainKeyQR() { val ok = setKeyImage(false) if (!ok) { UnlockKeyActivity.showForResult(this, mId, RQ_UNLOCK) } else { btRevealQr.visibility = View.GONE } } private fun setKeyImage(blur: Boolean): Boolean { val dimension = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 240f, resources.displayMetrics) .toInt() try { var bm: Bitmap? if (blur) { bm = SymUtil.getQrCode(KeyUtil.getRandomBytes(32), dimension) val bmSmallTmp = Bitmap.createScaledBitmap(bm!!, 25, 25, true) bm = Bitmap.createScaledBitmap(bmSmallTmp, dimension, dimension, true) } else { bm = SymUtil.getQrCode(mKeystore.getPlainKeyAsTransferBytes(mId), dimension) } ivQr.setImageBitmap(bm) return true } catch (ex: KeyNotCachedException) { ex.printStackTrace() } catch (ex: Exception) { ex.printStackTrace() } return false } @SuppressLint("RestrictedApi") private fun refreshConfirm() { val confirmDate = mKeystore.getConfirmDate(mId) fab.visibility = if (confirmDate == null) View.VISIBLE else View.GONE tv_confirmed.text = if (confirmDate == null) getString(R.string.label_key_unconfirmed) else SimpleDateFormat.getDateTimeInstance().format( confirmDate ) ivConfirmed.visibility = if (confirmDate == null) View.GONE else View.VISIBLE ivUnConfirmed.visibility = if (confirmDate == null) View.VISIBLE else View.GONE } private fun showConfirmDialog() { val fp = mId //TODO: make custom dialog. highlight the fingerprint, monospace typeface MaterialDialog.Builder(this) .title(R.string.app_name) .iconRes(R.drawable.ic_warning_black_24dp) .cancelable(true) .content(getString(R.string.dialog_confirm_key_text, SymUtil.longToPrettyHex(fp))) .positiveText(R.string.common_ok) .onPositive { dialog, which -> try { mKeystore.confirmKey(mId) refreshConfirm() } catch (e: Exception) { e.printStackTrace() showError(getString(R.string.common_error_body, e.message), null) } } .negativeText(R.string.common_cancel) .onNegative { dialog, which -> dialog.dismiss() } .show() } private fun showDeleteDialog() { MaterialDialog.Builder(this) .title(R.string.app_name) .iconRes(R.drawable.ic_warning_black_24dp) .cancelable(true) .content(getString(R.string.action_delete_key_confirm)) .positiveText(R.string.common_ok) .onPositive { dialog, which -> try { mKeystore.deleteKey(mId) setResult(Activity.RESULT_FIRST_USER) finish() } catch (e: Exception) { e.printStackTrace() showError(getString(R.string.common_error_body, e.message), null) } } .negativeText(R.string.common_cancel) .onNegative { dialog, which -> dialog.dismiss() } .show() } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.menu_key_details, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { val id = item.itemId when (id) { android.R.id.home -> finish() R.id.action_delete_key -> { showDeleteDialog() return true } R.id.action_send_encrypted -> { share(RQ_SEND_ENCRYPTED) return true } R.id.action_view_encrypted -> { share(RQ_VIEW_ENCRYPTED) return true } R.id.help -> { Help.open(this, Help.ANCHOR.symkey_details) return true } } return super.onOptionsItemSelected(item) } private fun share(rq: Int) { try { val plainKey = mKeystore.getPlainKey(mId) share(plainKey, rq) } catch (e: KeyNotCachedException) { try { startIntentSenderForResult(e.pendingIntent.intentSender, rq, null, 0, 0, 0) } catch (e1: IntentSender.SendIntentException) { e1.printStackTrace() } } } private fun share(plainKey: SymmetricKeyPlain, rq: Int) { val cb = object : NewPasswordInputDialogCallback { override fun positiveAction(pw: CharArray) { share(pw, plainKey, rq) } override fun neutralAction() { } } NewPasswordInputDialog.show(this, NewPasswordInputDialog.MODE.SHARE, cb) } private fun share(pw: CharArray, plainKey: SymmetricKeyPlain, rq: Int) { val d = MaterialDialog.Builder(this) .title(R.string.progress_encrypting) .content(R.string.please_wait_encrypting) .progress(true, 0) .cancelable(false) .show() val t = Thread(Runnable { try { val encKey = mKeystore.encryptSymmetricKey(plainKey, pw) d.dismiss() runOnUiThread { share(encKey, rq) } } catch (e: Exception) { e.printStackTrace() d.dismiss() runOnUiThread { showError( getString( R.string.common_error_body, e.message ), null ) } } finally { KeyUtil.erase(pw) } }) t.start() } private fun share(encKey: SymmetricKeyEncrypted, rq: Int) { try { val uri = TemporaryContentProvider.prepare( this, "image/png", TemporaryContentProvider.TTL_1_HOUR, null ) val bm = SymUtil.getQrCode( OversecKeystore2.getEncryptedKeyAsTransferBytes(encKey), KEYSHARE_BITMAP_WIDTH_PX ) val os = contentResolver.openOutputStream(uri) ?: //damnit return bm!!.compress(Bitmap.CompressFormat.PNG, 100, os) os.close() val intent = Intent() var cid = 0 if (rq == RQ_SEND_ENCRYPTED) { intent.action = Intent.ACTION_SEND intent.putExtra(Intent.EXTRA_STREAM, uri) intent.type = "image/png" cid = R.string.intent_chooser_send_encryptedkey } else if (rq == RQ_VIEW_ENCRYPTED) { intent.action = Intent.ACTION_VIEW intent.setDataAndType(uri, "image/png") cid = R.string.intent_chooser_view_encryptedkey } intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) Util.share(this, intent, null, getString(cid), true, null, false) } catch (ex: Exception) { ex.printStackTrace() } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (RQ_UNLOCK == requestCode) { if (resultCode == Activity.RESULT_OK) { setKeyImage(false) btRevealQr.visibility = View.GONE } } else if (RQ_SEND_ENCRYPTED == requestCode) { if (resultCode == Activity.RESULT_OK) { share(RQ_SEND_ENCRYPTED) } } else if (RQ_VIEW_ENCRYPTED == requestCode) { if (resultCode == Activity.RESULT_OK) { share(RQ_VIEW_ENCRYPTED) } } } override fun onDestroy() { mKeystore.removeKeyCacheListener(this) super.onDestroy() } override fun onFinishedCachingKey(keyId: Long) { if (mId == keyId) { finish() } } override fun onStartedCachingKey(keyId: Long) { } companion object { private const val EXTRA_ID = "id" private const val RQ_UNLOCK = 1008 private const val RQ_SEND_ENCRYPTED = 1009 private const val RQ_VIEW_ENCRYPTED = 1010 private const val KEYSHARE_BITMAP_WIDTH_PX = 480 fun show(ctx: Context, keyId: Long?) { val i = Intent() i.setClass(ctx, KeyDetailsActivity::class.java) if (ctx !is Activity) { i.flags = Intent.FLAG_ACTIVITY_NEW_TASK } i.putExtra(EXTRA_ID, keyId) ctx.startActivity(i) } fun showForResult(f: Fragment, rq: Int, id: Long) { val i = Intent() i.setClass(f.activity, KeyDetailsActivity::class.java) i.putExtra(EXTRA_ID, id) f.startActivityForResult(i, rq) } } }
gpl-3.0
193dde07110bd46e680c4aa541d12553
30.941799
98
0.569985
4.578688
false
false
false
false
ibinti/intellij-community
java/java-tests/testSrc/com/intellij/java/codeInsight/daemon/inlays/JavaParameterNameHintsTest.kt
1
20000
/* * Copyright 2000-2017 JetBrains s.r.o. * * 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. */ package com.intellij.java.codeInsight.daemon.inlays import com.intellij.codeInsight.daemon.impl.ParameterHintsPresentationManager import com.intellij.codeInsight.hints.JavaInlayParameterHintsProvider import com.intellij.codeInsight.hints.settings.ParameterNameHintsSettings import com.intellij.ide.highlighter.JavaFileType import com.intellij.lang.java.JavaLanguage import com.intellij.openapi.editor.Inlay import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase import org.assertj.core.api.Assertions.assertThat class JavaInlayParameterHintsTest : LightCodeInsightFixtureTestCase() { override fun tearDown() { val default = ParameterNameHintsSettings() ParameterNameHintsSettings.getInstance().loadState(default.state) super.tearDown() } fun check(text: String) { myFixture.configureByText("A.java", text) myFixture.testInlays() } fun `test insert literal arguments`() { check(""" class Groo { public void test(File file) { boolean testNow = System.currentTimeMillis() > 34000; int times = 1; float pi = 4; String title = "Testing..."; char ch = 'q'; configure(<hint text="testNow:"/>true, <hint text="times:"/>555, <hint text="pii:"/>3.141f, <hint text="title:"/>"Huge Title", <hint text="terminate:"/>'c', <hint text="file:"/>null); configure(testNow, shouldIgnoreRoots(), fourteen, pi, title, c, file); } public void configure(boolean testNow, int times, float pii, String title, char terminate, File file) { System.out.println(); System.out.println(); } }""") } fun `test do not show for Exceptions`() { check(""" class Fooo { public void test() { Throwable t = new IllegalStateException("crime"); } } """) } fun `test show hint for single string literal if there is multiple string params`() { check("""class Groo { public void test() { String message = "sdfsdfdsf"; assertEquals(<hint text="expected:"/>"fooo", message); String title = "TT"; show(title, <hint text="message:"/>"Hi"); } public void assertEquals(String expected, String actual) {} public void show(String title, String message) {} }""") } fun `test no hints for generic builders`() { check(""" class Foo { void test() { new IntStream().skip(10); new Stream<Integer>().skip(10); } } class IntStream { public IntStream skip(int n) {} } class Stream<T> { public Stream<T> skip(int n) {} } """) JavaInlayParameterHintsProvider.getInstance().isDoNotShowForBuilderLikeMethods.set(false) check(""" class Foo { void test() { new IntStream().skip(<hint text="n:"/>10); new Stream<Integer>().skip(<hint text="n:"/>10); } } class IntStream { public IntStream skip(int n) {} } class Stream<T> { public Stream<T> skip(int n) {} } """) } fun `test do not show hints on setters`() { check("""class Groo { public void test() { setTestNow(false); System.out.println(""); } public void setTestNow(boolean testNow) { System.out.println(""); System.out.println(""); } }""") } fun `test single varargs hint`() { check(""" public class VarArgTest { public void main() { System.out.println("AAA"); testBooleanVarargs(<hint text="test:"/>13, <hint text="...booleans:"/>false); } public boolean testBooleanVarargs(int test, Boolean... booleans) { int temp = test; return false; } } """) } fun `test no hint if varargs null`() { check(""" public class VarArgTest { public void main() { System.out.println("AAA"); testBooleanVarargs(<hint text="test:"/>13); } public boolean testBooleanVarargs(int test, Boolean... booleans) { int temp = test; return false; } } """) } fun `test multiple vararg hint`() { check(""" public class VarArgTest { public void main() { System.out.println("AAA"); testBooleanVarargs(<hint text="test:"/>13, <hint text="...booleans:"/>false, true, false); } public boolean testBooleanVarargs(int test, Boolean... booleans) { int temp = test; return false; } } """) } fun `test do not inline known subsequent parameter names`() { check(""" public class Test { public void main() { test1(1, 2); test2(1, 2); test3(1, 2); doTest("first", "second"); } public void test1(int first, int second) { int start = first; int end = second; } public void test2(int key, int value) { int start = key; int end = value; } public void test3(int key, int value) { int start = key; int end = value; } } """) } fun `test show if can be assigned`() { check(""" public class CharSymbol { public void main() { Object obj = new Object(); count(<hint text="test:"/>100, <hint text="boo:"/>false, <hint text="seq:"/>"Hi!"); } public void count(Integer test, Boolean boo, CharSequence seq) { int a = test; Object obj = new Object(); } } """) } fun `test inline positive and negative numbers`() { check(""" public class CharSymbol { public void main() { Object obj = new Object(); count(<hint text="test:"/>-1, obj); count(<hint text="test:"/>+1, obj); } public void count(int test, Object obj) { Object tmp = obj; boolean isFast = false; } } """) } fun `test inline literal arguments with crazy settings`() { check(""" public class Test { public void main(boolean isActive, boolean requestFocus, int xoo) { System.out.println("AAA"); main(<hint text="isActive:"/>true,<hint text="requestFocus:"/>false, /*comment*/<hint text="xoo:"/>2); } } """) } fun `test ignored methods`() { check(""" public class Test { List<String> list = new ArrayList<>(); StringBuilder builder = new StringBuilder(); public void main() { System.out.println("A"); System.out.print("A"); list.add("sss"); list.get(1); list.set(1, "sss"); setNewIndex(10); "sss".contains("s"); builder.append("sdfsdf"); "sfsdf".startWith("s"); "sss".charAt(3); clearStatus(<hint text="updatedRecently:"/>false); } void print(String s) {} void println(String s) {} void get(int index) {} void set(int index, Object object) {} void append(String s) {} void clearStatus(boolean updatedRecently) {} } """) } fun `test hints for generic arguments`() { check(""" class QList<E> { void add(int query, E obj) {} } class QCmp<E> { void cmpre(E o1, E o2) {} } public class Test { public void main(QCmp<Integer> c, QList<String> l) { c.cmpre(<hint text="o1:"/>0, /** ddd */<hint text="o2:"/>3); l.add(<hint text="query:"/>1, <hint text="obj:"/>"uuu"); } } """) } fun `test inline constructor literal arguments names`() { check(""" public class Test { public void main() { System.out.println("AAA"); Checker r = new Checker(<hint text="isActive:"/>true, <hint text="requestFocus:"/>false) { @Override void test() { } }; } abstract class Checker { Checker(boolean isActive, boolean requestFocus) {} abstract void test(); } } """) } fun `test inline anonymous class constructor parameters`() { check(""" public class Test { Test(int counter, boolean shouldTest) { System.out.println(); System.out.println(); } public static void main() { System.out.println(); Test t = new Test(<hint text="counter:"/>10, <hint text="shouldTest:"/>false); } } """) } fun `test inline if one of vararg params is literal`() { check(""" public class VarArgTest { public void main() { System.out.println("AAA"); int test = 13; boolean isCheck = false; boolean isOk = true; testBooleanVarargs(test, <hint text="...booleans:"/>isCheck, true, isOk); } public boolean testBooleanVarargs(int test, Boolean... booleans) { int temp = test; return false; } } """) } fun `test if any param matches inline all`() { check(""" public class VarArgTest { public void main() { check(<hint text="x:"/>10, <hint text="paramNameLength:"/>1000); } public void check(int x, int paramNameLength) { } } """) } fun `test inline common name pair if more that 2 args`() { check(""" public class VarArgTest { public void main() { String s = "su"; check(<hint text="beginIndex:"/>10, <hint text="endIndex:"/>1000, s); } public void check(int beginIndex, int endIndex, String params) { } } """) } fun `test ignore String methods`() { check(""" class Test { public void main() { String.format("line", "eee", "www"); } } """) } fun `test inline common name pair if more that 2 args xxx`() { check(""" public class VarArgTest { public void main() { check(<hint text="beginIndex:"/>10, <hint text="endIndex:"/>1000, <hint text="x:"/>"su"); } public void check(int beginIndex, int endIndex, String x) { } } """) } fun `test inline this`() { check(""" public class VarArgTest { public void main() { check(<hint text="test:"/>this, <hint text="endIndex:"/>1000); } public void check(VarArgTest test, int endIndex) { } } """) } fun `test inline strange methods`() { check(""" public class Test { void main() { createContent(<hint text="manager:"/>null); createNewContent(<hint text="test:"/>this); } Content createContent(DockManager manager) {} Content createNewContent(Test test) {} } interface DockManager {} interface Content {} """) } fun `test do not inline builder pattern`() { check(""" class Builder { void await(boolean value) {} Builder bwait(boolean xvalue) {} Builder timeWait(int time) {} } class Test { public void test() { Builder builder = new Builder(); builder.await(<hint text="value:"/>true); builder.bwait(false).timeWait(100); } } """) JavaInlayParameterHintsProvider.getInstance().isDoNotShowForBuilderLikeMethods.set(false) check(""" class Builder { void await(boolean value) {} Builder bwait(boolean xvalue) {} Builder timeWait(int millis) {} } class Test { public void test() { Builder builder = new Builder(); builder.await(<hint text="value:"/>true); builder.bwait(<hint text="xvalue:"/>false).timeWait(<hint text="millis:"/>100); } } """) } fun `test builder method only method with one param`() { check(""" class Builder { Builder qwit(boolean value, String sValue) {} Builder trew(boolean value) {} } class Test { public void test() { Builder builder = new Builder(); builder .trew(false) .qwit(<hint text="value:"/>true, <hint text="sValue:"/>"value"); } } """) JavaInlayParameterHintsProvider.getInstance().isDoNotShowForBuilderLikeMethods.set(false) check(""" class Builder { Builder qwit(boolean value, String sValue) {} Builder trew(boolean value) {} } class Test { public void test() { Builder builder = new Builder(); builder .trew(<hint text="value:"/>false) .qwit(<hint text="value:"/>true, <hint text="sValue:"/>"value"); } } """) } fun `test do not show single parameter hint if it is string literal`() { check(""" public class Test { public void test() { debug("Error message"); info("Error message", new Object()); } void debug(String message) {} void info(String message, Object error) {} } """) } fun `test show single`() { check(""" class Test { void main() { blah(<hint text="a:"/>1, <hint text="b:"/>2); int z = 2; draw(<hint text="x:"/>10, <hint text="y:"/>20, z); int x = 10; int y = 12; drawRect(x, y, <hint text="w:"/>10, <hint text="h:"/>12); } void blah(int a, int b) {} void draw(int x, int y, int z) {} void drawRect(int x, int y, int w, int h) {} } """) } fun `test do not show for setters`() { check(""" class Test { void main() { set(10); setWindow(100); setWindow(<hint text="height:"/>100, <hint text="weight:">); } void set(int newValue) {} void setWindow(int newValue) {} void setWindow(int height, int weight) {} } """) } fun `test do not show for equals and min`() { check(""" class Test { void test() { "xxx".equals(name); Math.min(10, 20); } } """) } fun `test more blacklisted items`() { check(""" class Test { void test() { System.getProperty("aaa"); System.setProperty("aaa", "bbb"); new Key().create(10); } } class Key { void create(int a) {} } """) } fun `test poly and binary expressions`() { check(""" class Test { void test() { xxx(<hint text="followTheSum:"/>100); check(<hint text="isShow:"/>1 + 1); check(<hint text="isShow:"/>1 + 1 + 1); yyy(<hint text="followTheSum:"/>200); } void check(int isShow) {} void xxx(int followTheSum) {} void yyy(int followTheSum) {} } """) } fun `test incorrect pattern`() { ParameterNameHintsSettings.getInstance().addIgnorePattern(JavaLanguage.INSTANCE, "") check(""" class Test { void test() { check(<hint text="isShow:"/>1000); } void check(int isShow) {} } """) } fun `test do not show hint for name contained in method`() { JavaInlayParameterHintsProvider.getInstance().isDoNotShowIfMethodNameContainsParameterName.set(true) check(""" class Test { void main() { timeoutExecution(1000); createSpace(true); } void timeoutExecution(int timeout) {} void createSpace(boolean space) {} } """) } fun `test show if multiple params but name contained`() { JavaInlayParameterHintsProvider.getInstance().isDoNotShowIfMethodNameContainsParameterName.set(true) check(""" class Test { void main() { timeoutExecution(<hint text="timeout:"/>1000, <hint text="message:"/>"xxx"); createSpace(<hint text="space:"/>true, <hint text="a:"/>10); } void timeoutExecution(int timeout, String message) {} void createSpace(boolean space, int a) {} } """) } fun `test show same params`() { JavaInlayParameterHintsProvider.getInstance().isShowForParamsWithSameType.set(true) check(""" class Test { void main() { String c = "c"; String d = "d"; test(<hint text="parent:"/>c, <hint text="child:"/>d); } void test(String parent, String child) { } } """) } fun `test show triple`() { JavaInlayParameterHintsProvider.getInstance().isShowForParamsWithSameType.set(true) check(""" class Test { void main() { String c = "c"; test(<hint text="parent:"/>c, <hint text="child:"/>c, <hint text="grandParent:"/>c); } void test(String parent, String child, String grandParent) { } } """) } fun `test show couple of doubles`() { JavaInlayParameterHintsProvider.getInstance().isShowForParamsWithSameType.set(true) check(""" class Test { void main() { String c = "c"; String d = "d"; int v = 10; test(<hint text="parent:"/>c, <hint text="child:"/>d, <hint text="vx:"/>v, <hint text="vy:"/>v); } void test(String parent, String child, int vx, int vy) { } } """) } fun `test show ambigous`() { myFixture.configureByText(JavaFileType.INSTANCE, """ class Test { void main() { test(10<selection>, 100</selection>); } void test(int a, String bS) {} void test(int a, int bI) {} } """) myFixture.doHighlighting() val hints = getHints() assertThat(hints.size).isEqualTo(2) assertThat(hints[0]).isEqualTo("a:") assertThat(hints[1]).isEqualTo("bI:") myFixture.type('\b') myFixture.doHighlighting() assertSingleInlayWithText("a:") } fun `test show ambiguous constructor`() { myFixture.configureByText(JavaFileType.INSTANCE, """ class Test { void main() { new X(10<selection>, 100</selection>); } } class X { X(int a, int bI) {} X(int a, String bS) {} } """) myFixture.doHighlighting() val hints = getHints() assertThat(hints.size).isEqualTo(2) assertThat(hints[0]).isEqualTo("a:") assertThat(hints[1]).isEqualTo("bI:") myFixture.type('\b') myFixture.doHighlighting() assertSingleInlayWithText("a:") } fun `test preserved inlays`() { myFixture.configureByText(JavaFileType.INSTANCE, """ class Test { void main() { test(<caret>); } void test(int fooo) {} } """) myFixture.type("100") myFixture.doHighlighting() assertSingleInlayWithText("fooo:") myFixture.type("\b\b\b") myFixture.doHighlighting() assertSingleInlayWithText("fooo:") myFixture.type("yyy") myFixture.doHighlighting() assertSingleInlayWithText("fooo:") myFixture.checkResult( """ class Test { void main() { test(yyy); } void test(int fooo) {} } """) } fun `test do not show hints if method is unknown and one of them or both are blacklisted`() { ParameterNameHintsSettings.getInstance().addIgnorePattern(JavaLanguage.INSTANCE, "*kee") myFixture.configureByText(JavaFileType.INSTANCE, """ class Test { void main() { kee(100<caret>) } void kee(int a) {} void kee(String a) {} } """) myFixture.doHighlighting() var hints = getHints() assertThat(hints).hasSize(0) myFixture.type('+') myFixture.doHighlighting() hints = getHints() assertThat(hints).hasSize(0) } fun `test multiple hints on same offset lives without exception`() { myFixture.configureByText(JavaFileType.INSTANCE, """ class Test { void main() { check(<selection>0, </selection>200); } void check(int qas, int b) { } } """) myFixture.doHighlighting() var inlays = getHints() assert(inlays.size == 2) myFixture.type('\b') myFixture.doHighlighting() inlays = getHints() assert(inlays.size == 1 && inlays.first() == "qas:", { "Real inlays ${inlays.size}" }) } fun `test params with same type`() { JavaInlayParameterHintsProvider.getInstance().isShowForParamsWithSameType.set(true) check(""" class Test { void test() { String parent, child, element; check(<hint text="a:"/>10, parent, child); check(<hint text="a:"/>10, <hint text="parent:">element, child); } void check(int a, String parent, String child) {} } """) } fun `test if resolved but no hints just return no hints`() { myFixture.configureByText(JavaFileType.INSTANCE, """ public class Test { public void main() { foo(1<caret>); } void foo(int a) {} void foo() {} } """) myFixture.doHighlighting() var inlays = getHints() assert(inlays.size == 1) myFixture.type('\b') myFixture.performEditorAction("EditorLeft") myFixture.doHighlighting() inlays = getHints() assert(inlays.isEmpty()) } fun getHints(): List<String> { val document = myFixture.getDocument(myFixture.file) val manager = ParameterHintsPresentationManager.getInstance() return myFixture.editor .inlayModel .getInlineElementsInRange(0, document.textLength) .mapNotNull { manager.getHintText(it) } } fun assertSingleInlayWithText(expectedText: String) { val inlays = myFixture.editor.inlayModel.getInlineElementsInRange(0, editor.document.textLength) assertThat(inlays).hasSize(1) val realText = getHintText(inlays[0]) assertThat(realText).isEqualTo(expectedText) } fun getHintText(inlay: Inlay): String { return ParameterHintsPresentationManager.getInstance().getHintText(inlay) } }
apache-2.0
5592042587977867087673d59baa6b29
20.12038
185
0.63035
3.788596
false
true
false
false
savoirfairelinux/ring-client-android
ring-android/app/src/main/java/cx/ring/fragments/QRCodeFragment.kt
1
5173
/* * Copyright (C) 2004-2021 Savoir-faire Linux Inc. * * Authors: AmirHossein Naghshzan <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package cx.ring.fragments import android.app.Dialog import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.annotation.StringRes import androidx.coordinatorlayout.widget.CoordinatorLayout import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentPagerAdapter import com.google.android.material.bottomsheet.BottomSheetBehavior import com.google.android.material.bottomsheet.BottomSheetDialogFragment import cx.ring.R import cx.ring.databinding.FragQrcodeBinding import cx.ring.share.ScanFragment import cx.ring.share.ShareFragment import cx.ring.utils.DeviceUtils.isTablet class QRCodeFragment : BottomSheetDialogFragment() { private var mBinding: FragQrcodeBinding? = null private var mStartPageIndex = 0 override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { super.onCreateView(inflater, container, savedInstanceState) val args = requireArguments() mStartPageIndex = args.getInt(ARG_START_PAGE_INDEX, 0) return FragQrcodeBinding.inflate(inflater, container, false).apply { viewPager.adapter = SectionsPagerAdapter(root.context, childFragmentManager) tabs.setupWithViewPager(viewPager) mBinding = this }.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) if (mStartPageIndex != 0) { mBinding?.tabs?.getTabAt(mStartPageIndex)?.select() } } override fun onDestroyView() { mBinding = null super.onDestroyView() } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val dialog = super.onCreateDialog(savedInstanceState) dialog.setOnShowListener { if (isTablet(requireContext())) { dialog.window?.setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT) } } return dialog } internal class SectionsPagerAdapter(private val mContext: Context, fm: FragmentManager) : FragmentPagerAdapter(fm) { @StringRes private val TAB_TITLES = intArrayOf(R.string.tab_code, R.string.tab_scan) override fun getItem(position: Int): Fragment { return when (position) { 0 -> ShareFragment() 1 -> ScanFragment() else -> throw IllegalArgumentException() } } override fun getPageTitle(position: Int): CharSequence { return mContext.resources.getString(TAB_TITLES[position]) } override fun getCount(): Int { return TAB_TITLES.size } } override fun onResume() { super.onResume() addGlobalLayoutListener(requireView()) } private fun addGlobalLayoutListener(view: View) { view.addOnLayoutChangeListener(object : View.OnLayoutChangeListener { override fun onLayoutChange(v: View, left: Int, top: Int, right: Int, bottom: Int, oldLeft: Int, oldTop: Int, oldRight: Int, oldBottom: Int) { setPeekHeight(v.measuredHeight) v.removeOnLayoutChangeListener(this) } }) } fun setPeekHeight(peekHeight: Int) { bottomSheetBehaviour?.peekHeight = peekHeight } private val bottomSheetBehaviour: BottomSheetBehavior<*>? get() { val layoutParams = (requireView().parent as View).layoutParams as CoordinatorLayout.LayoutParams val behavior = layoutParams.behavior return if (behavior is BottomSheetBehavior<*>) { behavior } else null } companion object { val TAG = QRCodeFragment::class.simpleName!! const val ARG_START_PAGE_INDEX = "start_page" const val INDEX_CODE = 0 const val INDEX_SCAN = 1 fun newInstance(startPage: Int): QRCodeFragment { val fragment = QRCodeFragment() val args = Bundle() args.putInt(ARG_START_PAGE_INDEX, startPage) fragment.arguments = args return fragment } } }
gpl-3.0
785c3da3e0659f5965ffb8faffdfa303
35.695035
154
0.68065
4.912631
false
false
false
false
bubelov/coins-android
app/src/main/java/com/bubelov/coins/logs/LogsFragment.kt
1
2135
package com.bubelov.coins.logs import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.WindowManager import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.LinearLayoutManager import com.bubelov.coins.R import kotlinx.android.synthetic.main.fragment_logs.* import kotlinx.coroutines.flow.collect import org.koin.android.viewmodel.ext.android.viewModel class LogsFragment : Fragment() { private val model: LogsViewModel by viewModel() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_logs, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) toolbar.setNavigationOnClickListener { findNavController().popBackStack() } list.layoutManager = LinearLayoutManager(requireContext()) val adapter = LogsAdapter() list.adapter = adapter lifecycleScope.launchWhenResumed { model.getAll().collect { adapter.swapItems(it) } } } override fun onResume() { super.onResume() requireActivity().window.apply { clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) statusBarColor = ContextCompat.getColor(requireContext(), R.color.search_status_bar) } } override fun onPause() { requireActivity().window.apply { clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) statusBarColor = ContextCompat.getColor(requireContext(), R.color.primary_dark) } super.onPause() } }
unlicense
94eb6cba9567f1e138564019156772e1
31.861538
96
0.713349
5.035377
false
false
false
false
tonyofrancis/Fetch
fetch2core/src/main/java/com/tonyodev/fetch2core/FetchCoreDefaults.kt
1
319
@file:JvmName("FetchCoreDefaults") package com.tonyodev.fetch2core const val DEFAULT_TAG = "fetch2" const val DEFAULT_LOGGING_ENABLED = false const val DEFAULT_PROGRESS_REPORTING_INTERVAL_IN_MILLISECONDS = 2_000L const val DEFAULT_BUFFER_SIZE = 8 * 1024 const val DEFAULT_PERSISTENT_TIME_OUT_IN_MILLISECONDS = 600000L
apache-2.0
a73f8a11b249a5bee608129d87129caf
34.555556
70
0.802508
3.505495
false
false
false
false
slimaku/kondorcet
src/main/kotlin/kondorcet/model/DefaultBallot.kt
1
1152
package kondorcet.model import kondorcet.Ballot /** * Vote ballot * * Contains all the candidates ordered by preferences. * * @property orderedCandidates Each element of this list is a set of candidate who are ex aequo. */ class DefaultBallot<out T : Any>(orderedCandidates: List<Set<T>> = emptyList()) : Ballot<T> { override val orderedCandidates by lazy { var winners = emptySet<T>() orderedCandidates .map { set -> set.filterNot { it in winners }.toSet().also { winners += it } } .filterNot(Set<T>::isEmpty) } override val candidates by lazy { super.candidates } override val winners by lazy { super.winners } override val winner by lazy { super.winner } constructor(vararg candidates: T) : this(candidates.map { setOf(it) }) constructor(vararg candidates: Collection<T>) : this(candidates.map { it.toSet() }) override fun equals(other: Any?) = other is Ballot<*> && other.orderedCandidates == orderedCandidates override fun hashCode() = orderedCandidates.hashCode() override fun toString() = "DefaultBallot(orderedCandidates=$orderedCandidates)" }
lgpl-3.0
2723ec01b9f7957f93557e79d06cf9b3
35.03125
105
0.684028
4.20438
false
false
false
false
VerifAPS/verifaps-lib
geteta/src/test/kotlin/edu/kit/iti/formal/automation/testtables/monitor/monitor.kt
1
734
package edu.kit.iti.formal.automation.testtables.monitor import edu.kit.iti.formal.automation.testtables.GetetaFacade import org.junit.jupiter.api.Assumptions import org.junit.jupiter.api.Test import java.io.File /** * * @author Alexander Weigl * @version 1 (14.07.19) */ class MonitorTests { @Test fun testSimple() { val file = File("examples/constantprogram/constantprogram.gtt") Assumptions.assumeTrue(file.exists()) val gtt = GetetaFacade.parseTableDSL(file).first() gtt.programRuns += "" gtt.generateSmvExpression() val automaton = GetetaFacade.constructTable(gtt).automaton val mon = CppMonitorGenerator.generate(gtt, automaton) println(mon) } }
gpl-3.0
f99ea34b003c21c419657e33ba23e3ae
28.4
71
0.701635
3.598039
false
true
false
false
industrial-data-space/trusted-connector
ids-api/src/main/java/de/fhg/aisec/ids/api/router/CounterExample.kt
1
1150
/*- * ========================LICENSE_START================================= * ids-api * %% * Copyright (C) 2019 Fraunhofer AISEC * %% * 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. * =========================LICENSE_END================================== */ package de.fhg.aisec.ids.api.router abstract class CounterExample { var explanation: String? = null protected set var steps: List<String>? = null protected set override fun toString(): String { return """ Explanation: $explanation ${java.lang.String.join("\n|-- ", steps)} """.trimIndent() } }
apache-2.0
65a3d1b2436b04da5978c151dcd9de37
32.823529
75
0.596522
4.581673
false
false
false
false
cketti/k-9
app/ui/legacy/src/main/java/com/fsck/k9/ui/messageview/MessageViewContainerFragment.kt
1
11026
package com.fsck.k9.ui.messageview import android.content.Context import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.recyclerview.widget.DiffUtil import androidx.viewpager2.adapter.FragmentStateAdapter import androidx.viewpager2.widget.MarginPageTransformer import androidx.viewpager2.widget.ViewPager2 import com.fsck.k9.controller.MessageReference import com.fsck.k9.ui.R import com.fsck.k9.ui.messagelist.MessageListItem import com.fsck.k9.ui.messagelist.MessageListViewModel import com.fsck.k9.ui.withArguments /** * A fragment that uses [ViewPager2] to allow the user to swipe between messages. * * Individual messages are displayed using a [MessageViewFragment]. */ class MessageViewContainerFragment : Fragment() { var isActive: Boolean = false set(value) { field = value setMenuVisibility(value) } lateinit var messageReference: MessageReference private set private var activeMessageReference: MessageReference? = null var lastDirection: Direction? = null private set private lateinit var fragmentListener: MessageViewContainerListener private lateinit var viewPager: ViewPager2 private lateinit var adapter: MessageViewContainerAdapter private var currentPosition: Int? = null private val messageViewFragment: MessageViewFragment get() { check(isResumed) return findMessageViewFragment() } private fun findMessageViewFragment(): MessageViewFragment { val itemId = adapter.getItemId(messageReference) // ViewPager2/FragmentStateAdapter don't provide an easy way to get hold of the Fragment for the active // page. So we're using an implementation detail (the fragment tag) to find the fragment. return childFragmentManager.findFragmentByTag("f$itemId") as MessageViewFragment } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) if (savedInstanceState == null) { messageReference = MessageReference.parse(arguments?.getString(ARG_REFERENCE)) ?: error("Missing argument $ARG_REFERENCE") } else { messageReference = MessageReference.parse(savedInstanceState.getString(STATE_MESSAGE_REFERENCE)) ?: error("Missing state $STATE_MESSAGE_REFERENCE") lastDirection = savedInstanceState.getSerializable(STATE_LAST_DIRECTION) as Direction? } adapter = MessageViewContainerAdapter(this) } override fun onAttach(context: Context) { super.onAttach(context) fragmentListener = try { context as MessageViewContainerListener } catch (e: ClassCastException) { throw ClassCastException("This fragment must be attached to a MessageViewContainerListener") } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.message_view_container, container, false) val resources = inflater.context.resources val pageMargin = resources.getDimension(R.dimen.message_view_pager_page_margin).toInt() viewPager = view.findViewById(R.id.message_viewpager) viewPager.isUserInputEnabled = true viewPager.offscreenPageLimit = ViewPager2.OFFSCREEN_PAGE_LIMIT_DEFAULT viewPager.setPageTransformer(MarginPageTransformer(pageMargin)) viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() { // The message list is updated each time the active message is changed. To avoid message list updates // during the animation, we only set the active message after the animation has finished. override fun onPageScrollStateChanged(state: Int) { if (state == ViewPager2.SCROLL_STATE_IDLE) { setActiveMessage(viewPager.currentItem) } } override fun onPageSelected(position: Int) { if (viewPager.scrollState == ViewPager2.SCROLL_STATE_IDLE) { setActiveMessage(position) } } }) return view } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putString(STATE_MESSAGE_REFERENCE, messageReference.toIdentityString()) outState.putSerializable(STATE_LAST_DIRECTION, lastDirection) } fun setViewModel(viewModel: MessageListViewModel) { viewModel.getMessageListLiveData().observe(this) { messageListInfo -> updateMessageList(messageListInfo.messageListItems) } } private fun updateMessageList(messageListItems: List<MessageListItem>) { if (messageListItems.isEmpty() || messageListItems.none { it.messageReference == messageReference }) { fragmentListener.closeMessageView() return } adapter.messageList = messageListItems // We only set the adapter on ViewPager2 after the message list has been loaded. This way ViewPager2 can // restore its saved state after a configuration change. if (viewPager.adapter == null) { viewPager.adapter = adapter } val position = adapter.getPosition(messageReference) viewPager.setCurrentItem(position, false) } private fun setActiveMessage(position: Int) { // If the position of current message changes (e.g. because messages were added or removed from the list), we // keep track of the new position but otherwise ignore the event. val newMessageReference = adapter.getMessageReference(position) if (newMessageReference == activeMessageReference) { currentPosition = position return } rememberNavigationDirection(position) messageReference = adapter.getMessageReference(position) activeMessageReference = messageReference fragmentListener.setActiveMessage(messageReference) } private fun rememberNavigationDirection(newPosition: Int) { currentPosition?.let { currentPosition -> lastDirection = if (newPosition < currentPosition) Direction.PREVIOUS else Direction.NEXT } currentPosition = newPosition } fun showPreviousMessage(): Boolean { val newPosition = viewPager.currentItem - 1 return if (newPosition >= 0) { setActiveMessage(newPosition) val smoothScroll = true viewPager.setCurrentItem(newPosition, smoothScroll) true } else { false } } fun showNextMessage(): Boolean { val newPosition = viewPager.currentItem + 1 return if (newPosition < adapter.itemCount) { setActiveMessage(newPosition) val smoothScroll = true viewPager.setCurrentItem(newPosition, smoothScroll) true } else { false } } fun onToggleFlagged() { messageViewFragment.onToggleFlagged() } fun onMove() { messageViewFragment.onMove() } fun onArchive() { messageViewFragment.onArchive() } fun onCopy() { messageViewFragment.onCopy() } fun onToggleRead() { messageViewFragment.onToggleRead() } fun onForward() { messageViewFragment.onForward() } fun onReplyAll() { messageViewFragment.onReplyAll() } fun onReply() { messageViewFragment.onReply() } fun onDelete() { messageViewFragment.onDelete() } fun onPendingIntentResult(requestCode: Int, resultCode: Int, data: Intent?) { findMessageViewFragment().onPendingIntentResult(requestCode, resultCode, data) } private class MessageViewContainerAdapter(fragment: Fragment) : FragmentStateAdapter(fragment) { var messageList: List<MessageListItem> = emptyList() set(value) { val diffResult = DiffUtil.calculateDiff( MessageListDiffCallback(oldMessageList = messageList, newMessageList = value) ) field = value diffResult.dispatchUpdatesTo(this) } override fun getItemCount(): Int { return messageList.size } override fun getItemId(position: Int): Long { return messageList[position].uniqueId } override fun containsItem(itemId: Long): Boolean { return messageList.any { it.uniqueId == itemId } } override fun createFragment(position: Int): Fragment { check(position in messageList.indices) val messageReference = messageList[position].messageReference return MessageViewFragment.newInstance(messageReference) } fun getMessageReference(position: Int): MessageReference { check(position in messageList.indices) return messageList[position].messageReference } fun getPosition(messageReference: MessageReference): Int { return messageList.indexOfFirst { it.messageReference == messageReference } } fun getItemId(messageReference: MessageReference): Long { return messageList.first { it.messageReference == messageReference }.uniqueId } } private class MessageListDiffCallback( private val oldMessageList: List<MessageListItem>, private val newMessageList: List<MessageListItem> ) : DiffUtil.Callback() { override fun getOldListSize(): Int = oldMessageList.size override fun getNewListSize(): Int = newMessageList.size override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return oldMessageList[oldItemPosition].uniqueId == newMessageList[newItemPosition].uniqueId } override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { // Let MessageViewFragment deal with content changes return areItemsTheSame(oldItemPosition, newItemPosition) } } interface MessageViewContainerListener { fun closeMessageView() fun setActiveMessage(messageReference: MessageReference) } companion object { private const val ARG_REFERENCE = "reference" private const val STATE_MESSAGE_REFERENCE = "messageReference" private const val STATE_LAST_DIRECTION = "lastDirection" fun newInstance(reference: MessageReference): MessageViewContainerFragment { return MessageViewContainerFragment().withArguments( ARG_REFERENCE to reference.toIdentityString() ) } } }
apache-2.0
33a3283037f22f55b2b7d10d4482221e
33.672956
117
0.672773
5.447628
false
false
false
false
ethauvin/kobalt
modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/misc/Topological.kt
2
1558
package com.beust.kobalt.misc import com.beust.kobalt.KobaltException import com.google.common.collect.ArrayListMultimap import com.google.common.collect.HashMultimap import java.util.* /** * Sort items topologically. These items need to have overridden hashCode() and equals(). */ class Topological<T> { private val dependingOn = ArrayListMultimap.create<T, T>() private val nodes = hashSetOf<T>() fun addNode(t: T) = nodes.add(t) fun addEdge(t: T, other: T) { addNode(t) addNode(other) dependingOn.put(t, other) } /** * @return the Ts sorted topologically. */ fun sort() : List<T> { val all = ArrayList<T>(nodes) val result = arrayListOf<T>() var dependMap = HashMultimap.create<T, T>() dependingOn.keySet().forEach { dependMap.putAll(it, dependingOn.get(it))} nodes.forEach { dependMap.putAll(it, emptyList())} while (all.size > 0) { val freeNodes = all.filter { dependMap.get(it).isEmpty() } if (freeNodes.isEmpty()) { throw KobaltException("The dependency graph has a cycle: $all") } result.addAll(freeNodes) all.removeAll(freeNodes) val newMap = HashMultimap.create<T, T>() dependMap.keySet().forEach { val l = dependingOn.get(it) l.removeAll(freeNodes) newMap.putAll(it, l) } dependMap = newMap } return result } }
apache-2.0
4b6648dc4bd0740e8d4b83806665ea9f
29.568627
89
0.579589
4.121693
false
false
false
false
googlesamples/arcore-ml-sample
app/src/main/java/com/google/ar/core/examples/java/ml/MainActivityView.kt
1
2386
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.ar.core.examples.java.ml import android.opengl.GLSurfaceView import android.view.View import androidx.appcompat.widget.AppCompatButton import androidx.appcompat.widget.SwitchCompat import androidx.lifecycle.DefaultLifecycleObserver import androidx.lifecycle.LifecycleOwner import com.google.ar.core.examples.java.common.helpers.SnackbarHelper import com.google.ar.core.examples.java.common.samplerender.SampleRender /** * Wraps [R.layout.activity_main] and controls lifecycle operations for [GLSurfaceView]. */ class MainActivityView(val activity: MainActivity, renderer: AppRenderer) : DefaultLifecycleObserver { val root = View.inflate(activity, R.layout.activity_main, null) val surfaceView = root.findViewById<GLSurfaceView>(R.id.surfaceview).apply { SampleRender(this, renderer, activity.assets) } val useCloudMlSwitch = root.findViewById<SwitchCompat>(R.id.useCloudMlSwitch) val scanButton = root.findViewById<AppCompatButton>(R.id.scanButton) val resetButton = root.findViewById<AppCompatButton>(R.id.clearButton) val snackbarHelper = SnackbarHelper().apply { setParentView(root.findViewById(R.id.coordinatorLayout)) setMaxLines(6) } override fun onResume(owner: LifecycleOwner) { surfaceView.onResume() } override fun onPause(owner: LifecycleOwner) { surfaceView.onPause() } fun post(action: Runnable) = root.post(action) /** * Toggles the scan button depending on if scanning is in progress. */ fun setScanningActive(active: Boolean) = when(active) { true -> { scanButton.isEnabled = false scanButton.setText(activity.getString(R.string.scan_busy)) } false -> { scanButton.isEnabled = true scanButton.setText(activity.getString(R.string.scan_available)) } } }
apache-2.0
0dd42b435d1f62b849320ba50e918aca
34.626866
102
0.756915
4.128028
false
false
false
false
jabbink/PokemonGoBot
src/main/kotlin/ink/abb/pogo/scraper/controllers/BotController.kt
2
16388
/** * Pokemon Go Bot Copyright (C) 2016 PokemonGoBot-authors (see authors.md for more information) * This program comes with ABSOLUTELY NO WARRANTY; * This is free software, and you are welcome to redistribute it under certain conditions. * * For more information, refer to the LICENSE file in this repositories root directory */ package ink.abb.pogo.scraper.controllers import POGOProtos.Data.PokedexEntryOuterClass import POGOProtos.Enums.PokemonIdOuterClass import POGOProtos.Inventory.Item.ItemIdOuterClass import POGOProtos.Networking.Responses.SetFavoritePokemonResponseOuterClass import POGOProtos.Networking.Responses.UpgradePokemonResponseOuterClass import com.google.common.geometry.S2LatLng import ink.abb.pogo.api.cache.BagPokemon import ink.abb.pogo.api.request.* import ink.abb.pogo.scraper.Context import ink.abb.pogo.scraper.Settings import ink.abb.pogo.scraper.services.BotService import ink.abb.pogo.scraper.util.ApiAuthProvider import ink.abb.pogo.scraper.util.Log import ink.abb.pogo.scraper.util.credentials.GoogleAutoCredentials import ink.abb.pogo.scraper.util.data.* import ink.abb.pogo.scraper.util.pokemon.candyCostsForPowerup import ink.abb.pogo.scraper.util.pokemon.getStatsFormatted import ink.abb.pogo.scraper.util.pokemon.meta import ink.abb.pogo.scraper.util.pokemon.stardustCostsForPowerup import org.springframework.beans.factory.annotation.Autowired import org.springframework.web.bind.annotation.* import java.util.concurrent.atomic.AtomicInteger import javax.servlet.http.HttpServletResponse @RestController @CrossOrigin @RequestMapping("/api") class BotController { @Autowired lateinit var service: BotService @Autowired lateinit var authProvider: ApiAuthProvider @RequestMapping("/bots") fun bots(): List<Settings> { return service.getAllBotSettings() } @RequestMapping(value = "/bot/{name}/auth", method = arrayOf(RequestMethod.POST)) fun auth( @PathVariable name: String, @RequestBody pass: String, httpResponse: HttpServletResponse ): String { val ctx = service.getBotContext(name) if (ctx.restApiPassword.equals("")) { Log.red("REST API: There is no REST API password set in the configuration for bot $name, generating one now...") authProvider.generateRestPassword(name) return "REST API password generated for bot $name, check your console output!" } authProvider.generateAuthToken(name) if (!pass.equals(ctx.restApiPassword)) { httpResponse.status = HttpServletResponse.SC_UNAUTHORIZED return "Your authentication request ($pass) does not match the REST API password from the bot $name configuration!" } return ctx.restApiToken } @RequestMapping(value = "/bot/{name}/load", method = arrayOf(RequestMethod.POST)) fun loadBot(@PathVariable name: String): Settings { Log.magenta("REST API: Load bot $name") return service.submitBot(name) } @RequestMapping(value = "/bot/{name}/unload", method = arrayOf(RequestMethod.POST)) fun unloadBot(@PathVariable name: String): String { Log.magenta("REST API: Unload bot $name") return service.doWithBot(name) { it.stop() service.removeBot(it) }.toString() } @RequestMapping(value = "/bot/{name}/reload", method = arrayOf(RequestMethod.POST)) fun reloadBot(@PathVariable name: String): Settings { Log.magenta("REST API: Reload bot $name") if (unloadBot(name).equals("false")) // return default settings return Settings( credentials = GoogleAutoCredentials(), latitude = 0.0, longitude = 0.0 ) return loadBot(name) } @RequestMapping(value = "/bot/{name}/start", method = arrayOf(RequestMethod.POST)) fun startBot(@PathVariable name: String): String { Log.magenta("REST API: Starting bot $name") return service.doWithBot(name) { it.start() }.toString() } @RequestMapping(value = "/bot/{name}/stop", method = arrayOf(RequestMethod.POST)) fun stopBot(@PathVariable name: String): String { Log.magenta("REST API: Stopping bot $name") return service.doWithBot(name) { it.stop() }.toString() } @RequestMapping(value = "/bot/{name}/pokemons", method = arrayOf(RequestMethod.GET)) fun listPokemons(@PathVariable name: String): List<PokemonData> { return service.getBotContext(name).api.inventory.pokemon.map { PokemonData().buildFromPokemon(it.value) } } @RequestMapping(value = "/bot/{name}/pokemon/{id}/transfer", method = arrayOf(RequestMethod.POST)) fun transferPokemon( @PathVariable name: String, @PathVariable id: Long ): String { val pokemon: BagPokemon? = getPokemonById(service.getBotContext(name), id) val release = ReleasePokemon().withPokemonId(pokemon!!.pokemonData.id) Log.magenta("REST API: Transferring pokemon ${pokemon.pokemonData.pokemonId.name} with stats (${pokemon.pokemonData.getStatsFormatted()} CP: ${pokemon.pokemonData.cp})") val result = service.getBotContext(name).api.queueRequest(release).toBlocking().first().response // Update GUI service.getBotContext(name).server.sendPokebank() return result.result.toString() } @RequestMapping(value = "/bot/{name}/pokemon/{id}/evolve", method = arrayOf(RequestMethod.POST)) fun evolvePokemon( @PathVariable name: String, @PathVariable id: Long, httpResponse: HttpServletResponse ): String { val result: String val pokemon: BagPokemon? = getPokemonById(service.getBotContext(name), id) val requiredCandy = pokemon!!.pokemonData.meta.candyToEvolve val candy = service.getBotContext(name).api.inventory.candies.getOrPut(pokemon.pokemonData.meta.family, { AtomicInteger(0) }).get() if (requiredCandy > candy) { httpResponse.status = HttpServletResponse.SC_BAD_REQUEST result = "Not enough candies to evolve: ${candy}/${requiredCandy}" } else { val evolve = EvolvePokemon().withPokemonId(pokemon.pokemonData.id) val evolutionResult = service.getBotContext(name).api.queueRequest(evolve).toBlocking().first().response val evolved = evolutionResult.evolvedPokemonData Log.magenta("REST API: Evolved pokemon ${pokemon.pokemonData.pokemonId.name} with stats (${pokemon.pokemonData.getStatsFormatted()} CP: ${pokemon.pokemonData.cp})" + " to pokemon ${evolved.pokemonId.name} with stats (${evolved.getStatsFormatted()} CP: ${evolved.cp})") result = evolutionResult.result.toString() } // Update GUI service.getBotContext(name).server.sendPokebank() return result } @RequestMapping(value = "/bot/{name}/pokemon/{id}/powerup", method = arrayOf(RequestMethod.POST)) fun powerUpPokemon( @PathVariable name: String, @PathVariable id: Long, httpResponse: HttpServletResponse ): String { val pokemon = getPokemonById(service.getBotContext(name), id) val candy = service.getBotContext(name).api.inventory.candies.getOrPut(pokemon!!.pokemonData.meta.family, { AtomicInteger(0) }).get() val stardust = service.getBotContext(name).api.inventory.currencies.getOrPut("STARDUST", { AtomicInteger(0) }).get() val result = if (pokemon.pokemonData.candyCostsForPowerup > candy) { httpResponse.status = HttpServletResponse.SC_BAD_REQUEST "Not enough candies to powerup: ${candy}/${pokemon.pokemonData.candyCostsForPowerup}" } else if (pokemon.pokemonData.stardustCostsForPowerup > stardust) { httpResponse.status = HttpServletResponse.SC_BAD_REQUEST "Not enough stardust to powerup: ${stardust}/${pokemon.pokemonData.stardustCostsForPowerup}" } else { Log.magenta("REST API: Powering up pokemon ${pokemon.pokemonData.pokemonId.name} with stats (${pokemon.pokemonData.getStatsFormatted()} CP: ${pokemon.pokemonData.cp})") val upgrade = UpgradePokemon().withPokemonId(pokemon.pokemonData.id) Log.magenta("REST API : pokemon new CP " + pokemon.pokemonData.cp) val response = service.getBotContext(name).api.queueRequest(upgrade).toBlocking().first() if (response.response.result == UpgradePokemonResponseOuterClass.UpgradePokemonResponse.Result.SUCCESS) { Log.magenta("REST API: Pokemon new CP ${response.response.upgradedPokemon.cp}") } response!!.response.result.toString() } // Update GUI service.getBotContext(name).server.sendPokebank() return result } @RequestMapping(value = "/bot/{name}/pokemon/{id}/favorite", method = arrayOf(RequestMethod.POST)) fun togglePokemonFavorite( @PathVariable name: String, @PathVariable id: Long ): String { val pokemon = getPokemonById(service.getBotContext(name), id) val setFav = SetFavoritePokemon().withIsFavorite(pokemon!!.pokemonData.favorite == 0).withPokemonId(pokemon.pokemonData.id) val result = service.getBotContext(name).api.queueRequest(setFav).toBlocking().first().response.result if (result == SetFavoritePokemonResponseOuterClass.SetFavoritePokemonResponse.Result.SUCCESS) { when (pokemon.pokemonData.favorite > 0) { false -> Log.magenta("REST API: Pokemon ${pokemon.pokemonData.pokemonId.name} with stats (${pokemon.pokemonData.getStatsFormatted()} CP: ${pokemon.pokemonData.cp}) is favorited") true -> Log.magenta("REST API: Pokemon ${pokemon.pokemonData.pokemonId.name} with stats (${pokemon.pokemonData.getStatsFormatted()} CP: ${pokemon.pokemonData.cp}) is now unfavorited") } } // Update GUI service.getBotContext(name).server.sendPokebank() return result.toString() } @RequestMapping(value = "/bot/{name}/pokemon/{id}/rename", method = arrayOf(RequestMethod.POST)) fun renamePokemon( @PathVariable name: String, @PathVariable id: Long, @RequestBody newName: String ): String { val pokemon = getPokemonById(service.getBotContext(name), id) val rename = NicknamePokemon().withNickname(newName).withPokemonId(pokemon!!.pokemonData.id) val result = service.getBotContext(name).api.queueRequest(rename).toBlocking().first().response.result.toString() Log.magenta("REST API: Renamed pokemon ${pokemon.pokemonData.pokemonId.name} with stats (${pokemon.pokemonData.getStatsFormatted()} CP: ${pokemon.pokemonData.cp}) to $newName") return result } @RequestMapping("/bot/{name}/items") fun listItems(@PathVariable name: String): List<ItemData> { return service.getBotContext(name).api.inventory.items.map { ItemData().buildFromItem(it.key, it.value.get()) } } @RequestMapping(value = "/bot/{name}/item/{id}/drop/{quantity}", method = arrayOf(RequestMethod.DELETE)) fun dropItem( @PathVariable name: String, @PathVariable id: Int, @PathVariable quantity: Int, httpResponse: HttpServletResponse ): String { val itemBag = service.getBotContext(name).api.inventory.items val itemId = ItemIdOuterClass.ItemId.forNumber(id) val item = itemBag.getOrPut(itemId, { AtomicInteger(0) }) if (quantity > item.get()) { httpResponse.status = HttpServletResponse.SC_BAD_REQUEST return "Not enough items to drop ${item.get()}" } else { Log.magenta("REST API: Dropping ${quantity} ${itemId.name}") val recycle = RecycleInventoryItem().withCount(quantity).withItemId(itemId) val result = service.getBotContext(name).api.queueRequest(recycle).toBlocking().first().response.result.toString() return result } } @RequestMapping(value = "/bot/{name}/useIncense", method = arrayOf(RequestMethod.POST)) fun useIncense( @PathVariable name: String, httpResponse: HttpServletResponse ): String { val itemBag = service.getBotContext(name).api.inventory.items val count = itemBag.getOrPut(ItemIdOuterClass.ItemId.ITEM_INCENSE_ORDINARY, { AtomicInteger(0) }).get() if (count == 0) { httpResponse.status = HttpServletResponse.SC_BAD_REQUEST return "Not enough incenses" } else { val useIncense = UseIncense().withIncenseType(ItemIdOuterClass.ItemId.ITEM_INCENSE_ORDINARY) val result = service.getBotContext(name).api.queueRequest(useIncense).toBlocking().first().response.result.toString() Log.magenta("REST API: Used incense") return result } } @RequestMapping(value = "/bot/{name}/useLuckyEgg", method = arrayOf(RequestMethod.POST)) fun useLuckyEgg( @PathVariable name: String, httpResponse: HttpServletResponse ): String { val itemBag = service.getBotContext(name).api.inventory.items val count = itemBag.getOrPut(ItemIdOuterClass.ItemId.ITEM_LUCKY_EGG, { AtomicInteger(0) }).get() if (count == 0) { httpResponse.status = HttpServletResponse.SC_BAD_REQUEST return "Not enough lucky eggs" } else { val useEgg = UseItemXpBoost().withItemId(ItemIdOuterClass.ItemId.ITEM_LUCKY_EGG) val result = service.getBotContext(name).api.queueRequest(useEgg).toBlocking().first().response.result.toString() Log.magenta("REST API: Used lucky egg") return result } } @RequestMapping(value = "/bot/{name}/location", method = arrayOf(RequestMethod.GET)) fun getLocation(@PathVariable name: String): LocationData { return LocationData( service.getBotContext(name).api.latitude, service.getBotContext(name).api.longitude ) } @RequestMapping(value = "/bot/{name}/location/{latitude}/{longitude}", method = arrayOf(RequestMethod.POST)) fun changeLocation( @PathVariable name: String, @PathVariable latitude: Double, @PathVariable longitude: Double, httpResponse: HttpServletResponse ): String { val ctx: Context = service.getBotContext(name) if (!latitude.isNaN() && !longitude.isNaN()) { ctx.server.coordinatesToGoTo.add(S2LatLng.fromDegrees(latitude, longitude)) Log.magenta("REST API: Added ToGoTo coordinates $latitude $longitude") return "SUCCESS" } else { httpResponse.status = HttpServletResponse.SC_BAD_REQUEST return "FAIL" } } @RequestMapping(value = "/bot/{name}/profile", method = arrayOf(RequestMethod.GET)) fun getProfile(@PathVariable name: String): ProfileData { return ProfileData().buildFromApi(service.getBotContext(name).api) } @RequestMapping(value = "/bot/{name}/pokedex", method = arrayOf(RequestMethod.GET)) fun getPokedex(@PathVariable name: String): List<PokedexEntry> { val pokedex = mutableListOf<PokedexEntry>() val api = service.getBotContext(name).api for (i in 0..151) { val entry: PokedexEntryOuterClass.PokedexEntry? = api.inventory.pokedex.get(PokemonIdOuterClass.PokemonId.forNumber(i)) entry ?: continue pokedex.add(PokedexEntry().buildFromEntry(entry)) } return pokedex } @RequestMapping(value = "/bot/{name}/eggs", method = arrayOf(RequestMethod.GET)) fun getEggs(@PathVariable name: String): List<EggData> { //service.getBotContext(name).api.inventories.updateInventories(true) return service.getBotContext(name).api.inventory.eggs.map { EggData().buildFromEggPokemon(it.value) } } // FIXME! currently, the IDs returned by the API are not unique. It seems that only the last 6 digits change so we remove them fun getPokemonById(ctx: Context, id: Long): BagPokemon? { return ctx.api.inventory.pokemon[id] } }
gpl-3.0
964592811b97a33f45efa16784d48909
41.128535
199
0.672138
4.576375
false
false
false
false
quarck/CalendarNotification
app/src/main/java/com/github/quarck/calnotify/calendareditor/CalendarChangeRequest.kt
1
2024
// // Calendar Notifications Plus // Copyright (C) 2017 Sergey Parshin ([email protected]) // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // package com.github.quarck.calnotify.calendareditor import com.github.quarck.calnotify.calendar.CalendarEventDetails enum class EventChangeStatus(val code: Int) { Dirty(0), Synced(1), Failed(1000); companion object { @JvmStatic fun fromInt(v: Int) = values()[v] } } enum class EventChangeRequestType(val code: Int) { AddNewEvent(0), MoveExistingEvent(1), EditExistingEvent(2); companion object { @JvmStatic fun fromInt(v: Int) = values()[v] } } data class CalendarChangeRequest( var id: Long, var type: EventChangeRequestType, var eventId: Long, val calendarId: Long, val calendarOwnerAccount: String, val details: CalendarEventDetails, val oldDetails: CalendarEventDetails, var status: EventChangeStatus = EventChangeStatus.Dirty, var lastStatusUpdate: Long = 0, var numRetries: Int = 0, var lastRetryTime: Long = 0 ) { fun onValidated(success: Boolean) { lastStatusUpdate = System.currentTimeMillis() status = if (success) EventChangeStatus.Synced else EventChangeStatus.Dirty } }
gpl-3.0
8506208504a382d6449e038a23fa925e
28.333333
83
0.684783
4.156057
false
false
false
false
android/user-interface-samples
People/app/src/main/java/com/example/android/people/MainActivity.kt
1
4633
/* * Copyright (C) 2019 The Android Open Source Project * 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. */ package com.example.android.people import android.content.Intent import android.net.Uri import android.os.Bundle import android.transition.Transition import android.transition.TransitionInflater import android.transition.TransitionManager import android.view.View import android.widget.ImageView import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.FragmentManager import androidx.fragment.app.commit import androidx.fragment.app.commitNow import com.example.android.people.data.Contact import com.example.android.people.databinding.MainActivityBinding import com.example.android.people.ui.chat.ChatFragment import com.example.android.people.ui.main.MainFragment import com.example.android.people.ui.photo.PhotoFragment import com.example.android.people.ui.viewBindings /** * Entry point of the app when it is launched as a full app. */ class MainActivity : AppCompatActivity(R.layout.main_activity), NavigationController { companion object { private const val FRAGMENT_CHAT = "chat" } private val binding by viewBindings(MainActivityBinding::bind) private lateinit var transition: Transition override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setSupportActionBar(binding.toolbar) transition = TransitionInflater.from(this).inflateTransition(R.transition.app_bar) if (savedInstanceState == null) { supportFragmentManager.commitNow { replace(R.id.container, MainFragment()) } intent?.let(::handleIntent) } } override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) if (intent != null) { handleIntent(intent) } } private fun handleIntent(intent: Intent) { when (intent.action) { // Invoked when a dynamic shortcut is clicked. Intent.ACTION_VIEW -> { val id = intent.data?.lastPathSegment?.toLongOrNull() if (id != null) { openChat(id, null) } } // Invoked when a text is shared through Direct Share. Intent.ACTION_SEND -> { val shortcutId = intent.getStringExtra(Intent.EXTRA_SHORTCUT_ID) val text = intent.getStringExtra(Intent.EXTRA_TEXT) val contact = Contact.CONTACTS.find { it.shortcutId == shortcutId } if (contact != null) { openChat(contact.id, text) } } } } override fun updateAppBar( showContact: Boolean, hidden: Boolean, body: (name: TextView, icon: ImageView) -> Unit ) { if (hidden) { binding.appBar.visibility = View.GONE } else { binding.appBar.visibility = View.VISIBLE TransitionManager.beginDelayedTransition(binding.appBar, transition) if (showContact) { supportActionBar?.setDisplayShowTitleEnabled(false) binding.name.visibility = View.VISIBLE binding.icon.visibility = View.VISIBLE } else { supportActionBar?.setDisplayShowTitleEnabled(true) binding.name.visibility = View.GONE binding.icon.visibility = View.GONE } } body(binding.name, binding.icon) } override fun openChat(id: Long, prepopulateText: String?) { supportFragmentManager.popBackStack(FRAGMENT_CHAT, FragmentManager.POP_BACK_STACK_INCLUSIVE) supportFragmentManager.commit { addToBackStack(FRAGMENT_CHAT) replace(R.id.container, ChatFragment.newInstance(id, true, prepopulateText)) } } override fun openPhoto(photo: Uri) { supportFragmentManager.commit { addToBackStack(null) replace(R.id.container, PhotoFragment.newInstance(photo)) } } }
apache-2.0
4325e9e9eaa3e4aae48a220f3d4d2fb0
35.195313
100
0.659832
4.84117
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/utils/correios/EncomendaResponse.kt
1
360
package net.perfectdreams.loritta.morenitta.utils.correios class EncomendaResponse { var date = "???" var time = "???" var state = "???" var error = "???" var locations: List<PackageUpdate> = listOf() class PackageUpdate { var state = "???" var reason = "???" var location = "???" var receiver = "???" var date = "???" var time = "???" } }
agpl-3.0
e957532b6641f1830cba00b1a111a41e
19.055556
58
0.583333
3.428571
false
false
false
false
Quireg/AnotherMovieApp
app/src/main/java/com/anothermovieapp/view/DetailsActivity.kt
1
9040
/* * Created by Arcturus Mengsk * 2021. */ package com.anothermovieapp.view import android.animation.ObjectAnimator import android.graphics.Bitmap import android.graphics.Color import android.net.Uri import android.os.Bundle import android.os.Handler import android.os.Looper import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.ImageView import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import androidx.palette.graphics.Palette import com.anothermovieapp.R import com.anothermovieapp.common.Constants import com.anothermovieapp.viewmodel.ViewModelFavoriteMovies import com.anothermovieapp.repository.EntityDBMovie import com.bumptech.glide.Glide import com.bumptech.glide.load.DataSource import com.bumptech.glide.load.engine.GlideException import com.bumptech.glide.request.RequestListener import com.bumptech.glide.request.target.Target import com.google.android.material.appbar.AppBarLayout import com.google.android.material.appbar.CollapsingToolbarLayout import dagger.hilt.android.AndroidEntryPoint import javax.inject.Inject @AndroidEntryPoint class DetailsActivity : AppCompatActivity(), OnFragmentInteractionListener { private var mDetailsFragment: DetailsFragment? = null private var mMovie: EntityDBMovie? = null private lateinit var mToolbarLayout: CollapsingToolbarLayout @Inject lateinit var viewModel: ViewModelFavoriteMovies override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mMovie = intent.extras?.getSerializable(Constants.MOVIE) as EntityDBMovie setContentView(R.layout.activity_movie_details_mine) val toolbar = findViewById<Toolbar>(R.id.toolbar) setSupportActionBar(toolbar) supportActionBar!!.setDisplayHomeAsUpEnabled(true) val appBarLayout = findViewById<AppBarLayout>(R.id.appbar) mToolbarLayout = appBarLayout.findViewById(R.id.collapsing_toolbar) mDetailsFragment = DetailsFragment() mDetailsFragment!!.arguments = intent.extras supportFragmentManager.beginTransaction() .replace(R.id.container, mDetailsFragment!!, DetailsFragment.TAG) .commit() if (mMovie?.title != null) { val collapsingTBL = findViewById<CollapsingToolbarLayout>(R.id.collapsing_toolbar) collapsingTBL.title = mMovie?.title } if (mMovie?.backdropPath != null) { loadBackdropImage(mMovie?.backdropPath) } appBarLayout.setBackgroundColor(Color.parseColor("#8C000000")) appBarLayout.setOnApplyWindowInsetsListener { v, insets -> toolbar.setPadding( v.paddingLeft, insets.systemWindowInsetTop, v.paddingRight, v.paddingBottom ) findViewById<View>(R.id.container).setPadding( v.paddingLeft, v.paddingTop, v.paddingRight, insets.systemWindowInsetBottom ) val a = obtainStyledAttributes(intArrayOf(R.attr.actionBarSize)) val actionBarSize = a.getDimensionPixelSize(0, -1) a.recycle() mToolbarLayout.setScrimVisibleHeightTrigger( insets.systemWindowInsetTop + actionBarSize + 1 ) insets } } var heartMenu : MenuItem? = null override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.movie_menu, menu) heartMenu = menu.findItem(R.id.favorite) heartMenu?.icon = getDrawable(R.drawable.ic_favorite_black_24dp) viewModel.isFavorite(mMovie!!.id).observe(this) { heartMenu?.icon = if (it) { getDrawable(R.drawable.ic_favorite_red_24dp) } else { getDrawable(R.drawable.ic_favorite_black_24dp) } } return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == R.id.favorite) { viewModel.addOrRemove(mMovie!!.id) return true } else if (item.itemId == android.R.id.home) { onBackPressed() } return super.onOptionsItemSelected(item) } override fun onFragmentMessage(tag: String?, data: Any?) { } private fun loadBackdropImage(path: String?) { val imageUri = Uri.Builder() .scheme("https") .authority("image.tmdb.org") .appendPath("t") .appendPath("p") .appendPath(Constants.IMAGE_SIZE_ORIGINAL) .appendPath(path) .build() .normalizeScheme(); val headerImage = findViewById<ImageView>(R.id.toolbar_image) Glide.with(this) .asBitmap() .load(imageUri) .addListener(object : RequestListener<Bitmap?> { override fun onLoadFailed( e: GlideException?, model: Any, target: Target<Bitmap?>, isFirstResource: Boolean ): Boolean { Handler(Looper.getMainLooper()).post { if (mDetailsFragment != null) { mDetailsFragment!!.readyShowContent() } } return false } override fun onResourceReady( resource: Bitmap?, model: Any, target: Target<Bitmap?>, dataSource: DataSource, isFirstResource: Boolean ): Boolean { Handler(Looper.getMainLooper()).post { if (mDetailsFragment != null) { mDetailsFragment!!.readyShowContent() } headerImage.setImageBitmap(resource) val animator = ObjectAnimator.ofFloat( headerImage, View.ALPHA, headerImage.alpha, 1f ) animator.duration = 300 animator.start() } return true } }) .submit() } private fun playWithPalette( resource: Bitmap, collapsingTBL: CollapsingToolbarLayout, headerImage: ImageView ) { Palette.from(Bitmap.createBitmap(resource)) .generate { palette -> // FloatingActionButton fab = findViewById(R.id.fab); // Drawable drawable = getResources() // .getDrawable(R.drawable.ic_action_star, getTheme()); // // drawable.setTintMode(PorterDuff.Mode.SRC_IN); // drawable.setTintList(new ColorStateList( // new int[][]{ // new int[]{android.R.attr.state_selected}, // new int[]{-android.R.attr.state_selected} // }, // new int[]{ // Color.RED, // Color.WHITE // } // )); // fab.setImageDrawable(drawable); // fab.setBackgroundTintList(ColorStateList.valueOf( // palette.getMutedColor(R.attr.colorSecondary))); // fab.setRippleColor(ColorStateList.valueOf( // palette.getDarkMutedColor(R.attr.colorSecondary))); if (palette!!.dominantSwatch != null) { collapsingTBL.setExpandedTitleColor( palette.dominantSwatch!!.titleTextColor ) } if (palette.vibrantSwatch != null) { collapsingTBL.setCollapsedTitleTextColor( palette.vibrantSwatch!!.titleTextColor ) collapsingTBL.setContentScrimColor( palette.vibrantSwatch!!.rgb ) } val toolbar = findViewById<Toolbar>(R.id.toolbar) if (toolbar.navigationIcon != null) { toolbar.navigationIcon!!.setTint( palette.getLightVibrantColor(R.attr.editTextColor) ) } collapsingTBL.setContentScrimColor( palette.getMutedColor(R.attr.colorPrimary) ) collapsingTBL.setStatusBarScrimColor( palette.getDarkMutedColor(R.attr.colorPrimaryDark) ) headerImage.setImageBitmap(resource) headerImage.visibility = View.VISIBLE } } }
mit
86bf43a5d4b86792d431bafac8d8b3fc
38.828194
111
0.561836
5.48211
false
false
false
false
Konstie/SightsGuru
app/src/main/java/com/sightsguru/app/sections/base/BaseActivity.kt
1
2589
package com.sightsguru.app.sections.base import android.os.Build import android.os.Handler import android.support.v7.app.AppCompatActivity abstract class BaseActivity : AppCompatActivity() { protected var handler: Handler? = null protected var handlerThread: android.os.HandlerThread? = null @Synchronized protected fun runInBackground(r: Runnable) { if (handler != null) { handler!!.post(r) } } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<String>, grantResults: IntArray) { when (requestCode) { PERMISSIONS_REQUEST -> { if (grantResults.isNotEmpty() && grantResults[0] == android.content.pm.PackageManager.PERMISSION_GRANTED && grantResults[1] == android.content.pm.PackageManager.PERMISSION_GRANTED) { onPermissionGranted() } else { requestPermission() } } } } protected abstract fun onPermissionGranted() protected fun allPermissionsGranted(): Boolean { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { return checkSelfPermission(PERMISSION_CAMERA) == android.content.pm.PackageManager.PERMISSION_GRANTED && checkSelfPermission(PERMISSION_STORAGE) == android.content.pm.PackageManager.PERMISSION_GRANTED && checkSelfPermission(PERMISSION_LOCATION) == android.content.pm.PackageManager.PERMISSION_GRANTED } else { return true } } protected fun requestPermission() { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) { if (shouldShowRequestPermissionRationale(PERMISSION_CAMERA) || shouldShowRequestPermissionRationale(PERMISSION_STORAGE) || shouldShowRequestPermissionRationale(PERMISSION_LOCATION)) { android.widget.Toast.makeText(this@BaseActivity, "Camera AND storage permission are required for this demo", android.widget.Toast.LENGTH_LONG).show() } requestPermissions(arrayOf(PERMISSION_CAMERA, PERMISSION_STORAGE, PERMISSION_LOCATION), PERMISSIONS_REQUEST) } } companion object { private val PERMISSIONS_REQUEST = 1 private val PERMISSION_CAMERA = android.Manifest.permission.CAMERA private val PERMISSION_STORAGE = android.Manifest.permission.WRITE_EXTERNAL_STORAGE private val PERMISSION_LOCATION = android.Manifest.permission.ACCESS_FINE_LOCATION } }
apache-2.0
4c195b19054592dc7c10eeef4dfe051d
42.166667
195
0.66319
5.262195
false
false
false
false
luiqn2007/miaowo
app/src/main/java/org/miaowo/miaowo/ui/FloatView.kt
1
7201
package org.miaowo.miaowo.ui import android.app.Activity import android.content.Context import android.graphics.PixelFormat import android.graphics.Point import android.os.IBinder import android.support.annotation.LayoutRes import android.util.AttributeSet import android.view.* import android.widget.FrameLayout import android.widget.LinearLayout import android.widget.TextView import org.miaowo.miaowo.R import org.miaowo.miaowo.App import org.miaowo.miaowo.base.ListHolder import org.miaowo.miaowo.util.FormatUtil import kotlin.collections.ArrayList import kotlin.properties.Delegates /** * 悬浮窗 * Created by luqin on 17-1-21. */ class FloatView : LinearLayout { private var mEndX = 0f private var mEndY = 0f private var mStartX = 0f private var mStartY = 0f private var mChangeX = 0f private var mChangeY = 0f private val mScreenSize = FormatUtil.screenSize private var mGravity = Gravity.CENTER private var mManager = App.i.getSystemService(Context.WINDOW_SERVICE) as WindowManager private var mPosition = Point(0, 0) private var mToken: IBinder? = null // View.applicationWindowToken private var mSlop = ViewConfiguration.get(App.i).scaledTouchSlop private var isShowing = false var view by Delegates.notNull<View>() var title: String? = null var positionSave: ((position: Point, gravity: Int) -> Unit) = { _, _ -> } constructor(title: String, @LayoutRes layout: Int, viewToken: IBinder) : super(App.i) { init() reset(title, layout, viewToken) } constructor(context: Context) : super(context) { init() } constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { init() } constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { init() } fun show(gravity: Int, position: Point): FloatView { mPosition = position mGravity = gravity return show() } fun show(gravity: Int, xPos: Int, yPos: Int): FloatView { mPosition.set(xPos, yPos) mGravity = gravity return show() } fun show(): FloatView { if (isShowing) { val index = shownWindows.indexOf(this) if (index > 0) { val bfViews = shownWindows.subList(0, index - 1) shownWindows[0] = this (0 until index).forEach { shownWindows[it + 1] = bfViews[it] } } return this } val params = buildLayoutParams() shownWindows.add(this) isShowing = true mManager.addView(this, params) return this } fun dismiss(clear: Boolean): FloatView { if (isShowing) { mManager.removeView(this) shownWindows.remove(this) isShowing = false positionSave(mPosition, mGravity) } if (clear) { findViewById<FrameLayout>(R.id.container).removeAllViews() mPosition.set(0, 0) mGravity = Gravity.CENTER mToken = null title = "" } return this } fun reset(title: String, @LayoutRes layout: Int, viewToken: IBinder) { dismiss(true) this.title = title mToken = viewToken setLayout(layout) } private fun buildLayoutParams(): WindowManager.LayoutParams { return WindowManager.LayoutParams().apply { gravity = mGravity x = mPosition.x y = mPosition.y width = WindowManager.LayoutParams.WRAP_CONTENT height = WindowManager.LayoutParams.WRAP_CONTENT token = mToken // 外部可点击 tag = // WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or // 变暗 WindowManager.LayoutParams.FLAG_DIM_BEHIND or // 保持常亮 WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON or // 无视其他修饰物 WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN or WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR or // 允许屏幕之外 WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS or // 防止脸误触 WindowManager.LayoutParams.FLAG_IGNORE_CHEEK_PRESSES type = WindowManager.LayoutParams.TYPE_APPLICATION_PANEL format = PixelFormat.RGBA_8888 } } private fun init() = LayoutInflater.from(context).inflate(R.layout.ui_window_normal, this) private fun setLayout(@LayoutRes layout: Int) { val container = findViewById<FrameLayout>(R.id.container) view = LayoutInflater.from(context).inflate(layout, container) } override fun onTouchEvent(event: MotionEvent): Boolean { when (event.action) { MotionEvent.ACTION_DOWN -> { mStartX = event.x mStartY = event.y } MotionEvent.ACTION_MOVE -> { mEndX = event.x mEndY = event.y mChangeX = mEndX - mStartX mChangeY = mEndY - mStartY if (mChangeX * mChangeX + mChangeY * mChangeY >= mSlop * mSlop) { val params = layoutParams as WindowManager.LayoutParams val limitXR = mScreenSize.x + params.width / 5 * 4 val limitXL = -params.width / 5 val limitYB = mScreenSize.y + params.height / 5 * 4 val limitYT = -params.height / 5 val pX = params.x + mChangeX.toInt() val pY = params.y - mChangeY.toInt() when { pX > limitXR -> params.x = limitXR pX < limitXL -> params.x = limitXL else -> params.x = pX } when { pY > limitYB -> params.y = limitYB pY < limitYT -> params.y = limitYT else -> params.y = pY } mPosition.set(params.x, params.y) mManager.updateViewLayout(this, params) } } MotionEvent.ACTION_UP -> { positionSave(mPosition, mGravity) } } return true } fun defaultBar(): FloatView { val holder = ListHolder(this) holder.find(R.id.iv_close)?.setOnClickListener { dismiss(false) } holder.find(R.id.pb_loading)?.visibility = View.GONE holder.find<TextView>(R.id.tv_page)?.text = title ?: "" return this } companion object { var shownWindows = ArrayList<FloatView>(5) fun setDimAmount(activity: Activity, dimAmount: Float) { val window = activity.window val lp = window.attributes lp.dimAmount = dimAmount window.attributes = lp } fun dismissFirst() = shownWindows.firstOrNull()?.dismiss(true) } }
apache-2.0
e7fe58885e43d3ebdae1784828cafae0
33.317308
113
0.570548
4.446729
false
false
false
false
nidi3/emoji-art
src/main/kotlin/guru/nidi/emojiart/Eyer.kt
1
2297
/* * Copyright © 2017 Stefan Niederhauser ([email protected]) * * 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. */ package guru.nidi.emojiart class Eyer { @Volatile private var running = false fun start() { if (!running) { running = true Thread { while (running) { eyes("(o)(o)", 800, 1200) val r = Math.random() when { r < .2 -> bigEyes() r < .4 -> oneEye() else -> blink() } } }.apply { isDaemon = true start() } } } fun stop() { running = false } private fun bigEyes() { eyes("(O)(O)", 300, 500) eyes("(o)(o)", 100, 200) eyes("(O)(O)", 300, 500) } private fun oneEye() { val r = Math.random() val s = when { r < .5 -> "(-)(o)(_)(O)" else -> "(o)(-)(O)(_)" } eyes(s.substring(0, 6), 50, 150) eyes(s.substring(6, 12), 500, 800) } private fun blink() { val r = Math.random() val s = when { r < .33 -> "(-)(-)(_)(_)" r < .66 -> "(-)(o)(_)(o)" else -> "(o)(-)(o)(_)" } eyes(s.substring(0, 6), 20, 50) eyes(s.substring(6, 12), 20, 50) } private fun eyes(s: String, min: Int, max: Int) { print(s + "\u001b[6D") System.out.flush() sleep(min, max) } private fun sleep(min: Int, max: Int) { try { Thread.sleep((Math.random() * (max - min) + min).toLong()) } catch (e: InterruptedException) { //ignore } } }
apache-2.0
558ad806aff3058a3328edd4850924ba
26.023529
75
0.465592
3.839465
false
false
false
false
shyiko/ktlint
ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/SpacingAroundKeywordRule.kt
1
4126
package com.pinterest.ktlint.ruleset.standard import com.pinterest.ktlint.core.Rule import com.pinterest.ktlint.core.ast.ElementType.CATCH_KEYWORD import com.pinterest.ktlint.core.ast.ElementType.DO_KEYWORD import com.pinterest.ktlint.core.ast.ElementType.ELSE_KEYWORD import com.pinterest.ktlint.core.ast.ElementType.FINALLY_KEYWORD import com.pinterest.ktlint.core.ast.ElementType.FOR_KEYWORD import com.pinterest.ktlint.core.ast.ElementType.GET_KEYWORD import com.pinterest.ktlint.core.ast.ElementType.IF_KEYWORD import com.pinterest.ktlint.core.ast.ElementType.RBRACE import com.pinterest.ktlint.core.ast.ElementType.SET_KEYWORD import com.pinterest.ktlint.core.ast.ElementType.TRY_KEYWORD import com.pinterest.ktlint.core.ast.ElementType.WHEN_KEYWORD import com.pinterest.ktlint.core.ast.ElementType.WHILE_KEYWORD import com.pinterest.ktlint.core.ast.ElementType.WHITE_SPACE import com.pinterest.ktlint.core.ast.nextLeaf import com.pinterest.ktlint.core.ast.prevLeaf import com.pinterest.ktlint.core.ast.upsertWhitespaceAfterMe import org.jetbrains.kotlin.com.intellij.lang.ASTNode import org.jetbrains.kotlin.com.intellij.psi.PsiWhiteSpace import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.LeafElement import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.LeafPsiElement import org.jetbrains.kotlin.com.intellij.psi.tree.TokenSet.create import org.jetbrains.kotlin.kdoc.psi.impl.KDocName import org.jetbrains.kotlin.psi.KtBlockExpression import org.jetbrains.kotlin.psi.KtPropertyAccessor import org.jetbrains.kotlin.psi.KtWhenEntry class SpacingAroundKeywordRule : Rule("keyword-spacing") { private val noLFBeforeSet = create(ELSE_KEYWORD, CATCH_KEYWORD, FINALLY_KEYWORD) private val tokenSet = create( FOR_KEYWORD, IF_KEYWORD, ELSE_KEYWORD, WHILE_KEYWORD, DO_KEYWORD, TRY_KEYWORD, CATCH_KEYWORD, FINALLY_KEYWORD, WHEN_KEYWORD ) private val keywordsWithoutSpaces = create(GET_KEYWORD, SET_KEYWORD) override fun visit( node: ASTNode, autoCorrect: Boolean, emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit ) { if (node is LeafPsiElement) { if (tokenSet.contains(node.elementType) && node.parent !is KDocName && node.nextLeaf() !is PsiWhiteSpace) { emit(node.startOffset + node.text.length, "Missing spacing after \"${node.text}\"", true) if (autoCorrect) { node.upsertWhitespaceAfterMe(" ") } } else if (keywordsWithoutSpaces.contains(node.elementType) && node.nextLeaf() is PsiWhiteSpace) { val parent = node.parent val nextLeaf = node.nextLeaf() if (parent is KtPropertyAccessor && parent.hasBody() && nextLeaf != null) { emit(node.startOffset, "Unexpected spacing after \"${node.text}\"", true) if (autoCorrect) { nextLeaf.treeParent.removeChild(nextLeaf) } } } if (noLFBeforeSet.contains(node.elementType)) { val prevLeaf = node.prevLeaf() val isElseKeyword = node.elementType == ELSE_KEYWORD if ( prevLeaf?.elementType == WHITE_SPACE && prevLeaf.textContains('\n') && (!isElseKeyword || node.parent !is KtWhenEntry) ) { val rBrace = prevLeaf.prevLeaf()?.takeIf { it.elementType == RBRACE } val parentOfRBrace = rBrace?.treeParent if ( parentOfRBrace is KtBlockExpression && (!isElseKeyword || parentOfRBrace.treeParent?.treeParent == node.treeParent) ) { emit(node.startOffset, "Unexpected newline before \"${node.text}\"", true) if (autoCorrect) { (prevLeaf as LeafElement).rawReplaceWithText(" ") } } } } } } }
mit
07f88d96b046cd39059d52d47b765104
48.119048
119
0.651963
4.524123
false
false
false
false
JayNewstrom/Concrete
concrete-sample/src/main/java/com/jaynewstrom/concretesample/details/DetailsListAdapter.kt
1
713
package com.jaynewstrom.concretesample.details import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter internal class DetailsListAdapter : BaseAdapter() { override fun getCount(): Int = 50 override fun getItem(position: Int) = position override fun getItemId(position: Int): Long = position.toLong() override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { val listItemView: DetailsListItemView = if (convertView == null) { DetailsListItemView(parent.context) } else { convertView as DetailsListItemView } listItemView.setPosition(position) return listItemView } }
apache-2.0
e42d8eb18d5997b7e92b226bfc01e26f
30
86
0.704067
4.817568
false
false
false
false
eugeis/ee
ee-system/src-gen/main/kotlin/ee/system/SharedApiBase.kt
1
18314
package ee.system import ee.lang.Composite import java.nio.file.Path import java.nio.file.Paths enum class PackageState(var order: Int = 0) { UNKNOWN(0), RESOLVED(1), PREPARED(2), INSTALLED(3), UNINSTALLED(-1); fun isUnknown(): Boolean = this == UNKNOWN fun isResolved(): Boolean = this == RESOLVED fun isPrepared(): Boolean = this == PREPARED fun isInstalled(): Boolean = this == INSTALLED fun isUninstalled(): Boolean = this == UNINSTALLED } fun String?.toPackageState(): PackageState { return if (this != null) { PackageState.valueOf(this) } else { PackageState.UNKNOWN } } data class PackageCoordinate(var classifier: String = "", var version: String = "", var group: String = "", var artifact: String = "", var type: String = "", var packaging: String = "") { companion object { val EMPTY = PackageCoordinate() } } fun PackageCoordinate?.orEmpty(): PackageCoordinate { return if (this != null) this else PackageCoordinate.EMPTY } data class PackagePaths(var resolved: Path = Paths.get(""), var prepared: Path = Paths.get(""), var installed: Path = Paths.get("")) { companion object { val EMPTY = PackagePaths() } } fun PackagePaths?.orEmpty(): PackagePaths { return if (this != null) this else PackagePaths.EMPTY } abstract class SystemBase : Composite { constructor(elName: String = "") : super({ name(elName) }) { } } open class System : SystemBase { companion object { val EMPTY = System() } var machines: MutableList<Machine> = arrayListOf() constructor(elName: String = "", machines: MutableList<Machine> = arrayListOf()) : super(elName) { this.machines = machines } } fun System?.orEmpty(): System { return if (this != null) this else System.EMPTY } open class Machine : SystemBase { companion object { val EMPTY = Machine() } var workspaces: MutableList<Workspace> = arrayListOf() constructor(elName: String = "", workspaces: MutableList<Workspace> = arrayListOf()) : super(elName) { this.workspaces = workspaces } } fun Machine?.orEmpty(): Machine { return if (this != null) this else Machine.EMPTY } open class Workspace : SystemBase { companion object { val EMPTY = Workspace() } var home: Path = Paths.get("") var meta: Path = Paths.get("") var prepared: Path = Paths.get("") var services: MutableList<Service> = arrayListOf() var tools: MutableList<Tool> = arrayListOf() var packages: MutableList<Package> = arrayListOf() constructor(elName: String = "", home: Path = Paths.get(""), meta: Path = Paths.get(""), prepared: Path = Paths.get(""), services: MutableList<Service> = arrayListOf(), tools: MutableList<Tool> = arrayListOf(), packages: MutableList<Package> = arrayListOf()) : super(elName) { this.home = home this.meta = meta this.prepared = prepared this.services = services this.tools = tools this.packages = packages } } fun Workspace?.orEmpty(): Workspace { return if (this != null) this else Workspace.EMPTY } open class Service : SystemBase { companion object { val EMPTY = Service() } var category: String = "" var dependsOn: MutableList<Service> = arrayListOf() var dependsOnMe: MutableList<Service> = arrayListOf() constructor(elName: String = "", category: String = "", dependsOn: MutableList<Service> = arrayListOf(), dependsOnMe: MutableList<Service> = arrayListOf()) : super(elName) { this.category = category this.dependsOn = dependsOn this.dependsOnMe = dependsOnMe } } fun Service?.orEmpty(): Service { return if (this != null) this else Service.EMPTY } abstract class SocketServiceBase : Service { companion object { val EMPTY = SocketService() } var host: String = "" var port: Int = 0 constructor(elName: String = "", category: String = "", dependsOn: MutableList<Service> = arrayListOf(), dependsOnMe: MutableList<Service> = arrayListOf(), host: String = "", port: Int = 0) : super(elName, category, dependsOn, dependsOnMe) { this.host = host this.port = port } } fun SocketServiceBase?.orEmpty(): SocketService { return if (this != null) this as SocketService else SocketServiceBase.EMPTY } open class JmxService : SocketService { companion object { val EMPTY = JmxService() } constructor(elName: String = "", category: String = "", dependsOn: MutableList<Service> = arrayListOf(), dependsOnMe: MutableList<Service> = arrayListOf(), host: String = "", port: Int = 0) : super(elName, category, dependsOn, dependsOnMe, host, port) { } } fun JmxService?.orEmpty(): JmxService { return if (this != null) this else JmxService.EMPTY } open class JavaService : SocketService { companion object { val EMPTY = JavaService() } var home: Path = Paths.get("") var logs: Path = Paths.get("") var configs: Path = Paths.get("") var command: String = "" constructor(elName: String = "", category: String = "", dependsOn: MutableList<Service> = arrayListOf(), dependsOnMe: MutableList<Service> = arrayListOf(), host: String = "", port: Int = 0, home: Path = Paths.get(""), logs: Path = Paths.get(""), configs: Path = Paths.get(""), command: String = "") : super(elName, category, dependsOn, dependsOnMe, host, port) { this.home = home this.logs = logs this.configs = configs this.command = command } } fun JavaService?.orEmpty(): JavaService { return if (this != null) this else JavaService.EMPTY } open class Package : SystemBase { companion object { val EMPTY = Package() } var category: String = "" var coordinate: PackageCoordinate = PackageCoordinate.EMPTY var state: PackageState = PackageState.UNKNOWN var dependsOn: MutableList<Package> = arrayListOf() var dependsOnMe: MutableList<Package> = arrayListOf() var paths: PackagePaths = PackagePaths.EMPTY constructor(elName: String = "", category: String = "", coordinate: PackageCoordinate = PackageCoordinate.EMPTY, state: PackageState = PackageState.UNKNOWN, dependsOn: MutableList<Package> = arrayListOf(), dependsOnMe: MutableList<Package> = arrayListOf(), paths: PackagePaths = PackagePaths.EMPTY) : super(elName) { this.category = category this.coordinate = coordinate this.state = state this.dependsOn = dependsOn this.dependsOnMe = dependsOnMe this.paths = paths } } fun Package?.orEmpty(): Package { return if (this != null) this else Package.EMPTY } open class ContentPackage : Package { companion object { val EMPTY = ContentPackage() } var targetCoordinate: PackageCoordinate = PackageCoordinate.EMPTY constructor(elName: String = "", category: String = "", coordinate: PackageCoordinate = PackageCoordinate.EMPTY, state: PackageState = PackageState.UNKNOWN, dependsOn: MutableList<Package> = arrayListOf(), dependsOnMe: MutableList<Package> = arrayListOf(), paths: PackagePaths = PackagePaths.EMPTY, targetCoordinate: PackageCoordinate = PackageCoordinate.EMPTY) : super(elName, category, coordinate, state, dependsOn, dependsOnMe, paths) { this.targetCoordinate = targetCoordinate } } fun ContentPackage?.orEmpty(): ContentPackage { return if (this != null) this else ContentPackage.EMPTY } open class MetaPackage : Package { companion object { val EMPTY = MetaPackage() } var targetCoordinate: PackageCoordinate = PackageCoordinate.EMPTY constructor(elName: String = "", category: String = "", coordinate: PackageCoordinate = PackageCoordinate.EMPTY, state: PackageState = PackageState.UNKNOWN, dependsOn: MutableList<Package> = arrayListOf(), dependsOnMe: MutableList<Package> = arrayListOf(), paths: PackagePaths = PackagePaths.EMPTY, targetCoordinate: PackageCoordinate = PackageCoordinate.EMPTY) : super(elName, category, coordinate, state, dependsOn, dependsOnMe, paths) { this.targetCoordinate = targetCoordinate } } fun MetaPackage?.orEmpty(): MetaPackage { return if (this != null) this else MetaPackage.EMPTY } open class AddonPackage : MetaPackage { companion object { val EMPTY = AddonPackage() } var extract: Boolean = false var includes: String = "" var excludes: String = "" var target: Path = Paths.get("") constructor(elName: String = "", category: String = "", coordinate: PackageCoordinate = PackageCoordinate.EMPTY, state: PackageState = PackageState.UNKNOWN, dependsOn: MutableList<Package> = arrayListOf(), dependsOnMe: MutableList<Package> = arrayListOf(), paths: PackagePaths = PackagePaths.EMPTY, targetCoordinate: PackageCoordinate = PackageCoordinate.EMPTY, extract: Boolean = false, includes: String = "", excludes: String = "", target: Path = Paths.get("")) : super(elName, category, coordinate, state, dependsOn, dependsOnMe, paths, targetCoordinate) { this.extract = extract this.includes = includes this.excludes = excludes this.target = target } } fun AddonPackage?.orEmpty(): AddonPackage { return if (this != null) this else AddonPackage.EMPTY } abstract class ToolBase : SystemBase { companion object { val EMPTY = Tool() } var home: Path = Paths.get("") constructor(elName: String = "", home: Path = Paths.get("")) : super(elName) { this.home = home } } fun ToolBase?.orEmpty(): Tool { return if (this != null) this as Tool else ToolBase.EMPTY } abstract class ServiceControllerBase<T : Service> { companion object { val EMPTY = ServiceController<Service>(Service.EMPTY) } var item: T constructor(item: T) { this.item = item } abstract fun start() abstract fun stop() abstract fun ping(): Boolean abstract fun copyLogs(target: Path = Paths.get("")) abstract fun copyConfigs(target: Path = Paths.get("")) abstract fun deleteLogs() abstract fun deleteOpsData() } fun ServiceControllerBase<*>?.orEmpty(): ServiceController<*> { return if (this != null) this as ServiceController<*> else ServiceControllerBase.EMPTY } abstract class ServiceQueriesBase<T : Service> { companion object { val EMPTY = ServiceQueries<Service>() } constructor() { } } fun ServiceQueriesBase<*>?.orEmpty(): ServiceQueries<*> { return if (this != null) this as ServiceQueries<*> else ServiceQueriesBase.EMPTY } abstract class ServiceCommandsBase<T : Service> { companion object { val EMPTY = ServiceCommands<Service>(Service.EMPTY) } var item: T constructor(item: T) { this.item = item } } fun ServiceCommandsBase<*>?.orEmpty(): ServiceCommands<*> { return if (this != null) this as ServiceCommands<*> else ServiceCommandsBase.EMPTY } abstract class SocketServiceControllerBase<T : SocketService> : ServiceController<T> { companion object { val EMPTY = SocketServiceController<SocketService>(SocketService.EMPTY) } constructor(item: T) : super(item) { } } fun SocketServiceControllerBase<*>?.orEmpty(): SocketServiceController<*> { return if (this != null) this as SocketServiceController<*> else SocketServiceControllerBase.EMPTY } abstract class SocketServiceQueriesBase<T : SocketService> : ServiceQueries<T> { companion object { val EMPTY = SocketServiceQueries<SocketService>() } constructor() : super() { } } fun SocketServiceQueriesBase<*>?.orEmpty(): SocketServiceQueries<*> { return if (this != null) this as SocketServiceQueries<*> else SocketServiceQueriesBase.EMPTY } abstract class SocketServiceCommandsBase<T : SocketService> : ServiceCommands<T> { companion object { val EMPTY = SocketServiceCommands<SocketService>(SocketService.EMPTY) } constructor(item: T) : super(item) { } } fun SocketServiceCommandsBase<*>?.orEmpty(): SocketServiceCommands<*> { return if (this != null) this as SocketServiceCommands<*> else SocketServiceCommandsBase.EMPTY } abstract class JmxServiceControllerBase<T : JmxService> : SocketServiceController<T> { companion object { val EMPTY = JmxServiceController<JmxService>(JmxService.EMPTY) } constructor(item: T) : super(item) { } } fun JmxServiceControllerBase<*>?.orEmpty(): JmxServiceController<*> { return if (this != null) this as JmxServiceController<*> else JmxServiceControllerBase.EMPTY } abstract class JmxServiceQueriesBase<T : JmxService> : SocketServiceQueries<T> { companion object { val EMPTY = JmxServiceQueries<JmxService>() } constructor() : super() { } } fun JmxServiceQueriesBase<*>?.orEmpty(): JmxServiceQueries<*> { return if (this != null) this as JmxServiceQueries<*> else JmxServiceQueriesBase.EMPTY } abstract class JmxServiceCommandsBase<T : JmxService> : SocketServiceCommands<T> { companion object { val EMPTY = JmxServiceCommands<JmxService>(JmxService.EMPTY) } constructor(item: T) : super(item) { } } fun JmxServiceCommandsBase<*>?.orEmpty(): JmxServiceCommands<*> { return if (this != null) this as JmxServiceCommands<*> else JmxServiceCommandsBase.EMPTY } abstract class JavaServiceControllerBase<T : JavaService> : SocketServiceController<T> { companion object { val EMPTY = JavaServiceController<JavaService>(JavaService.EMPTY) } constructor(item: T) : super(item) { } } fun JavaServiceControllerBase<*>?.orEmpty(): JavaServiceController<*> { return if (this != null) this as JavaServiceController<*> else JavaServiceControllerBase.EMPTY } abstract class JavaServiceQueriesBase<T : JavaService> : SocketServiceQueries<T> { companion object { val EMPTY = JavaServiceQueries<JavaService>() } constructor() : super() { } } fun JavaServiceQueriesBase<*>?.orEmpty(): JavaServiceQueries<*> { return if (this != null) this as JavaServiceQueries<*> else JavaServiceQueriesBase.EMPTY } abstract class JavaServiceCommandsBase<T : JavaService> : SocketServiceCommands<T> { companion object { val EMPTY = JavaServiceCommands<JavaService>(JavaService.EMPTY) } constructor(item: T) : super(item) { } } fun JavaServiceCommandsBase<*>?.orEmpty(): JavaServiceCommands<*> { return if (this != null) this as JavaServiceCommands<*> else JavaServiceCommandsBase.EMPTY } abstract class PackageControllerBase<T : Package> { companion object { val EMPTY = PackageController<Package>(Package.EMPTY) } var item: T constructor(item: T) { this.item = item } abstract fun prepare(params: Map<String, String> = hashMapOf()) abstract fun configure(params: Map<String, String> = hashMapOf()) abstract fun install(params: Map<String, String> = hashMapOf()) abstract fun uninstall() } fun PackageControllerBase<*>?.orEmpty(): PackageController<*> { return if (this != null) this as PackageController<*> else PackageControllerBase.EMPTY } abstract class PackageCommandsBase<T : Package> { companion object { val EMPTY = PackageCommands<Package>(Package.EMPTY) } var item: T constructor(item: T) { this.item = item } } fun PackageCommandsBase<*>?.orEmpty(): PackageCommands<*> { return if (this != null) this as PackageCommands<*> else PackageCommandsBase.EMPTY } abstract class ContentPackageControllerBase<T : ContentPackage> : PackageController<T> { companion object { val EMPTY = ContentPackageController<ContentPackage>(ContentPackage.EMPTY) } constructor(item: T) : super(item) { } } fun ContentPackageControllerBase<*>?.orEmpty(): ContentPackageController<*> { return if (this != null) this as ContentPackageController<*> else ContentPackageControllerBase.EMPTY } abstract class ContentPackageCommandsBase<T : ContentPackage> : PackageCommands<T> { companion object { val EMPTY = ContentPackageCommands<ContentPackage>(ContentPackage.EMPTY) } constructor(item: T) : super(item) { } } fun ContentPackageCommandsBase<*>?.orEmpty(): ContentPackageCommands<*> { return if (this != null) this as ContentPackageCommands<*> else ContentPackageCommandsBase.EMPTY } abstract class MetaPackageControllerBase<T : MetaPackage> : PackageController<T> { companion object { val EMPTY = MetaPackageController<MetaPackage>(MetaPackage.EMPTY) } constructor(item: T) : super(item) { } } fun MetaPackageControllerBase<*>?.orEmpty(): MetaPackageController<*> { return if (this != null) this as MetaPackageController<*> else MetaPackageControllerBase.EMPTY } abstract class MetaPackageCommandsBase<T : MetaPackage> : PackageCommands<T> { companion object { val EMPTY = MetaPackageCommands<MetaPackage>(MetaPackage.EMPTY) } constructor(item: T) : super(item) { } } fun MetaPackageCommandsBase<*>?.orEmpty(): MetaPackageCommands<*> { return if (this != null) this as MetaPackageCommands<*> else MetaPackageCommandsBase.EMPTY } abstract class AddonPackageControllerBase<T : AddonPackage> : MetaPackageController<T> { companion object { val EMPTY = AddonPackageController<AddonPackage>(AddonPackage.EMPTY) } constructor(item: T) : super(item) { } } fun AddonPackageControllerBase<*>?.orEmpty(): AddonPackageController<*> { return if (this != null) this as AddonPackageController<*> else AddonPackageControllerBase.EMPTY } abstract class AddonPackageCommandsBase<T : AddonPackage> : MetaPackageCommands<T> { companion object { val EMPTY = AddonPackageCommands<AddonPackage>(AddonPackage.EMPTY) } constructor(item: T) : super(item) { } } fun AddonPackageCommandsBase<*>?.orEmpty(): AddonPackageCommands<*> { return if (this != null) this as AddonPackageCommands<*> else AddonPackageCommandsBase.EMPTY }
apache-2.0
fd7285c77952bb58f0d637c77cd61090
25.503618
120
0.676204
4.255112
false
false
false
false
MeilCli/KLinq
src/main/kotlin/net/meilcli/klinq/internal/Lookup.kt
1
1742
package net.meilcli.klinq.internal import net.meilcli.klinq.* import java.util.* internal class Lookup<TSource, TKey, TElement> : ILookup<TKey, TElement> { private val enumerator: IEnumerator<IGrouping<TKey, TElement>> private var list = ArrayList<IGrouping<TKey, TElement>>() private var comparer: IEqualityComparer<TKey> override var count: Int constructor( source: IEnumerable<TSource>, keySelector: (TSource) -> TKey, elementSelector: (TSource) -> TElement, comparer: IEqualityComparer<TKey>) { this.comparer = comparer var map = HashMap<TKey, ArrayList<TElement>>() var enumerator: IEnumerator<TSource> = source.getEnumerator() while (enumerator.moveNext()) { var key: TKey = keySelector(enumerator.current) if (map.keys.toEnumerable().contains(key, comparer)) { map[key]!!.add(elementSelector(enumerator.current)) } else { map.put(key, ArrayList<TElement>()) map[key]!!.add(elementSelector(enumerator.current)) } } enumerator.reset() for (key in map.keys) { list.add(Grouping<TKey, TElement>(key, map[key]!!)) } count = list.count() this.enumerator = list.toEnumerable().getEnumerator() } override fun contains(key: TKey): Boolean { return list.toEnumerable().any { x -> comparer.equals(x.key, key) } } override fun get(key: TKey): IEnumerable<TElement> { return list.toEnumerable().single { x -> comparer.equals(x.key, key) } } override fun getEnumerator(): IEnumerator<IGrouping<TKey, TElement>> { return enumerator } }
mit
f95df5c7b7ee3a0358fb25328a45f1bb
34.571429
78
0.616533
4.1875
false
false
false
false
danrien/projectBlue
projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/playback/file/exoplayer/GivenAPlayingFile/WhenANormalProtocolExceptionOccurs.kt
2
2426
package com.lasthopesoftware.bluewater.client.playback.file.exoplayer.GivenAPlayingFile import com.google.android.exoplayer2.ExoPlaybackException import com.google.android.exoplayer2.PlaybackException import com.google.android.exoplayer2.Player import com.lasthopesoftware.bluewater.client.playback.exoplayer.PromisingExoPlayer import com.lasthopesoftware.bluewater.client.playback.file.exoplayer.ExoPlayerPlaybackHandler import com.lasthopesoftware.bluewater.client.playback.file.exoplayer.error.ExoPlayerException import com.lasthopesoftware.bluewater.shared.promises.extensions.toFuture import com.lasthopesoftware.bluewater.shared.promises.extensions.toPromise import io.mockk.every import io.mockk.mockk import org.assertj.core.api.AssertionsForClassTypes import org.junit.BeforeClass import org.junit.Test import java.net.ProtocolException import java.util.* import java.util.concurrent.ExecutionException import java.util.concurrent.TimeUnit class WhenANormalProtocolExceptionOccurs { companion object { private var exoPlayerException: ExoPlayerException? = null private val eventListener: MutableList<Player.Listener> = ArrayList() @JvmStatic @BeforeClass fun context() { val mockExoPlayer = mockk<PromisingExoPlayer>(relaxed = true) every { mockExoPlayer.setPlayWhenReady(any()) } returns mockExoPlayer.toPromise() every { mockExoPlayer.getPlayWhenReady() } returns true.toPromise() every { mockExoPlayer.getCurrentPosition() } returns 50L.toPromise() every { mockExoPlayer.getDuration() } returns 100L.toPromise() every { mockExoPlayer.addListener(any()) } answers { eventListener.add(firstArg()) mockExoPlayer.toPromise() } val exoPlayerPlaybackHandlerPlayerPlaybackHandler = ExoPlayerPlaybackHandler(mockExoPlayer) val futurePlayedFile = exoPlayerPlaybackHandlerPlayerPlaybackHandler.promisePlayback() .eventually { obj -> obj.promisePlayedFile() } .toFuture() eventListener.forEach { e -> e.onPlayerError(ExoPlaybackException.createForSource( ProtocolException(), PlaybackException.ERROR_CODE_IO_UNSPECIFIED)) } try { futurePlayedFile[1, TimeUnit.SECONDS] } catch (e: ExecutionException) { exoPlayerException = e.cause as? ExoPlayerException } } } @Test fun thenThePlaybackErrorIsCorrect() { AssertionsForClassTypes.assertThat(exoPlayerException!!.cause).isInstanceOf(ExoPlaybackException::class.java) } }
lgpl-3.0
a8e68b9bf1f2a397154c04e54c50804f
37.507937
111
0.805853
4.427007
false
false
false
false
android/app-bundle-samples
PlayCoreKtx/app/src/main/java/com/google/android/samples/dynamicfeatures/ui/MainFragment.kt
1
13747
/* * Copyright 2020 The Android Open Source Project * * 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. */ package com.google.android.samples.dynamicfeatures.ui import android.content.Context import android.graphics.drawable.AnimatedVectorDrawable import android.os.Bundle import android.util.Log import android.view.View import android.widget.Toast import androidx.annotation.Keep import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.fragment.app.viewModels import androidx.lifecycle.Observer import androidx.lifecycle.lifecycleScope import androidx.lifecycle.viewModelScope import com.google.android.material.snackbar.Snackbar import com.google.android.play.core.appupdate.AppUpdateManager import com.google.android.play.core.appupdate.AppUpdateManagerFactory import com.google.android.play.core.install.model.AppUpdateType import com.google.android.play.core.ktx.AppUpdateResult import com.google.android.play.core.ktx.AppUpdateResult.Available import com.google.android.play.core.ktx.AppUpdateResult.Downloaded import com.google.android.play.core.ktx.AppUpdateResult.InProgress import com.google.android.play.core.ktx.AppUpdateResult.NotAvailable import com.google.android.play.core.ktx.bytesDownloaded import com.google.android.play.core.ktx.launchReview import com.google.android.play.core.ktx.startConfirmationDialogForResult import com.google.android.play.core.ktx.startUpdateFlowForResult import com.google.android.play.core.ktx.totalBytesToDownload import com.google.android.play.core.review.ReviewManager import com.google.android.play.core.review.ReviewManagerFactory import com.google.android.play.core.splitcompat.SplitCompat import com.google.android.play.core.splitinstall.SplitInstallManager import com.google.android.play.core.splitinstall.SplitInstallManagerFactory import com.google.android.samples.dynamicfeatures.R import com.google.android.samples.dynamicfeatures.databinding.FragmentMainBinding import com.google.android.samples.dynamicfeatures.state.ColorViewModel import com.google.android.samples.dynamicfeatures.state.Event import com.google.android.samples.dynamicfeatures.state.InstallViewModel import com.google.android.samples.dynamicfeatures.state.InstallViewModelProviderFactory import com.google.android.samples.dynamicfeatures.state.ModuleStatus import com.google.android.samples.dynamicfeatures.state.ReviewViewModel import com.google.android.samples.dynamicfeatures.state.ReviewViewModelProviderFactory import com.google.android.samples.dynamicfeatures.state.UpdateViewModel import com.google.android.samples.dynamicfeatures.state.UpdateViewModelProviderFactory import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.drop import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.launch @OptIn(ExperimentalCoroutinesApi::class) @Keep class MainFragment : Fragment(R.layout.fragment_main) { private var bindings: FragmentMainBinding? = null private lateinit var splitInstallManager: SplitInstallManager private val installViewModel by viewModels<InstallViewModel> { InstallViewModelProviderFactory(splitInstallManager) } private var startModuleWhenReady: Boolean = false private lateinit var appUpdateManager: AppUpdateManager private val updateViewModel by viewModels<UpdateViewModel> { UpdateViewModelProviderFactory(appUpdateManager) } private lateinit var reviewManager: ReviewManager private val reviewViewModel by activityViewModels<ReviewViewModel> { ReviewViewModelProviderFactory(reviewManager) } private val colorViewModel by activityViewModels<ColorViewModel>() private lateinit var snackbar: Snackbar override fun onAttach(context: Context) { super.onAttach(context) splitInstallManager = SplitInstallManagerFactory.create(context) appUpdateManager = AppUpdateManagerFactory.create(context) reviewManager = ReviewManagerFactory.create(context) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { bindings = FragmentMainBinding.bind(view).apply { btnInvokePalette.setOnClickListener { startModuleWhenReady = true installViewModel.invokePictureSelection() } btnToggleLight.setOnClickListener { startModuleWhenReady = false colorViewModel.lightsOn.value = !colorViewModel.lightsOn.value } val colorBackgroundOff = ContextCompat.getColor(requireContext(), R.color.background) val drawable = btnToggleLight.drawable as AnimatedVectorDrawable viewLifecycleOwner.lifecycleScope.launchWhenResumed { colorViewModel.lightsOn .onEach { lightsOn: Boolean -> if (lightsOn) { // The user has turned on the flashlight. drawable.start() view.setBackgroundColor(colorViewModel.backgroundColor.value) } else { // The user has turned off the flashlight. Reset the icon and color: drawable.reset() view.setBackgroundColor(colorBackgroundOff) } } .drop(1) // for launching the review ignore the starting value .collect { lightsOn -> // Check if the color was picked from a photo, // and launch a review if yes: if (!lightsOn && colorViewModel.colorWasPicked) { colorViewModel.notifyPickedColorConsumed() val reviewInfo = reviewViewModel.obtainReviewInfo() if (reviewInfo != null) { reviewManager.launchReview(requireActivity(), reviewInfo) reviewViewModel.notifyAskedForReview() } } } } } snackbar = Snackbar.make(view, R.string.update_available, Snackbar.LENGTH_INDEFINITE) addInstallViewModelObservers() addUpdateViewModelObservers() } private fun addInstallViewModelObservers() { with(installViewModel) { events.onEach { event -> when (event) { is Event.ToastEvent -> toastAndLog(event.message) is Event.NavigationEvent -> { navigateToFragment(event.fragmentClass) } is Event.InstallConfirmationEvent -> splitInstallManager.startConfirmationDialogForResult( event.status, this@MainFragment, INSTALL_CONFIRMATION_REQ_CODE ) else -> throw IllegalStateException("Event type not handled: $event") } }.launchIn(viewLifecycleOwner.lifecycleScope) pictureModuleStatus.observe(viewLifecycleOwner, Observer { status -> bindings?.let { updateModuleButton(status) } }) } } private fun navigateToFragment(fragmentClass: String) { val fragment = parentFragmentManager.fragmentFactory.instantiate( ClassLoader.getSystemClassLoader(), fragmentClass) parentFragmentManager.beginTransaction() .replace(R.id.mycontainer, fragment) .addToBackStack(null) .commit() } private fun addUpdateViewModelObservers() { with(updateViewModel) { updateStatus.observe( viewLifecycleOwner, { updateResult: AppUpdateResult -> updateUpdateButton(updateResult) // If it's an immediate update, launch it immediately and finish Activity // to prevent the user from using the app until they update. if (updateResult is Available) { if (shouldLaunchImmediateUpdate(updateResult.updateInfo)) { if (appUpdateManager.startUpdateFlowForResult( updateResult.updateInfo, AppUpdateType.IMMEDIATE, this@MainFragment, UPDATE_CONFIRMATION_REQ_CODE )) { // only exit if update flow really started requireActivity().finish() } } } } ) events.onEach { event -> when (event) { is Event.ToastEvent -> toastAndLog(event.message) is Event.StartUpdateEvent -> { val updateType = if (event.immediate) AppUpdateType.IMMEDIATE else AppUpdateType.FLEXIBLE appUpdateManager.startUpdateFlowForResult( event.updateInfo, updateType, this@MainFragment, UPDATE_CONFIRMATION_REQ_CODE ) } else -> throw IllegalStateException("Event type not handled: $event") } }.launchIn(viewLifecycleOwner.lifecycleScope) } } private fun updateModuleButton(status: ModuleStatus) { bindings?.btnInvokePalette?.apply { isEnabled = status !is ModuleStatus.Unavailable when (status) { ModuleStatus.Available -> { text = getString(R.string.install) shrink() } is ModuleStatus.Installing -> { text = getString( R.string.installing, (status.progress * 100).toInt() ) extend() } ModuleStatus.Unavailable -> { text = getString(R.string.feature_not_available) shrink() } ModuleStatus.Installed -> { SplitCompat.installActivity(requireActivity()) shrink() if (startModuleWhenReady) { startModuleWhenReady = false installViewModel.invokePictureSelection() } } is ModuleStatus.NeedsConfirmation -> { splitInstallManager.startConfirmationDialogForResult( status.state, this@MainFragment, UPDATE_CONFIRMATION_REQ_CODE ) } } } } private fun updateUpdateButton(updateResult: AppUpdateResult) { when (updateResult) { NotAvailable -> { Log.d(TAG, "No update available") snackbar.dismiss() } is Available -> with(snackbar) { setText(R.string.update_available_snackbar) setAction(R.string.update_now) { updateViewModel.invokeUpdate() } show() } is InProgress -> { with(snackbar) { val updateProgress: Int = if (updateResult.installState.totalBytesToDownload == 0L) { 0 } else { (updateResult.installState.bytesDownloaded * 100 / updateResult.installState.totalBytesToDownload).toInt() } setText(context.getString(R.string.downloading_update, updateProgress)) setAction(null) {} show() } } is Downloaded -> { with(snackbar) { setText(R.string.update_downloaded) setAction(R.string.complete_update) { updateViewModel.invokeUpdate() } show() } } } } override fun onDestroyView() { bindings = null super.onDestroyView() } } fun MainFragment.toastAndLog(text: String) { Toast.makeText(requireContext(), text, Toast.LENGTH_LONG).show() Log.d(TAG, text) } private const val TAG = "DynamicFeatures" const val INSTALL_CONFIRMATION_REQ_CODE = 1 const val UPDATE_CONFIRMATION_REQ_CODE = 2
apache-2.0
1da3476a46c3d598601ff2c18e4488c8
42.365931
113
0.594821
5.732694
false
false
false
false
looker-open-source/sdk-codegen
kotlin/src/main/com/looker/sdk/4.0/streams.kt
1
384725
/** MIT License Copyright (c) 2021 Looker Data Sciences, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * 459 API methods */ // NOTE: Do not edit this file generated by Looker SDK Codegen for API 4.0 package com.looker.sdk import com.looker.rtl.* import java.util.* class LookerSDKStream(authSession: AuthSession) : APIMethods(authSession) { //region Alert: Alert /** * Follow an alert. * * @param {String} alert_id ID of an alert * * POST /alerts/{alert_id}/follow -> ByteArray */ fun follow_alert( alert_id: String ) : SDKResponse { val path_alert_id = encodeParam(alert_id) return this.post<ByteArray>("/alerts/${path_alert_id}/follow", mapOf()) } /** * Unfollow an alert. * * @param {String} alert_id ID of an alert * * DELETE /alerts/{alert_id}/follow -> ByteArray */ fun unfollow_alert( alert_id: String ) : SDKResponse { val path_alert_id = encodeParam(alert_id) return this.delete<ByteArray>("/alerts/${path_alert_id}/follow", mapOf()) } /** * ### Search Alerts * * @param {Long} limit (Optional) Number of results to return (used with `offset`). * @param {Long} offset (Optional) Number of results to skip before returning any (used with `limit`). * @param {String} group_by (Optional) Dimension by which to order the results(`dashboard` | `owner`) * @param {String} fields (Optional) Requested fields. * @param {Boolean} disabled (Optional) Filter on returning only enabled or disabled alerts. * @param {String} frequency (Optional) Filter on alert frequency, such as: monthly, weekly, daily, hourly, minutes * @param {Boolean} condition_met (Optional) Filter on whether the alert has met its condition when it last executed * @param {String} last_run_start (Optional) Filter on the start range of the last time the alerts were run. Example: 2021-01-01T01:01:01-08:00. * @param {String} last_run_end (Optional) Filter on the start range of the last time the alerts were run. Example: 2021-01-01T01:01:01-08:00. * @param {Boolean} all_owners (Admin only) (Optional) Filter for all owners. * * GET /alerts/search -> ByteArray */ @JvmOverloads fun search_alerts( limit: Long? = null, offset: Long? = null, group_by: String? = null, fields: String? = null, disabled: Boolean? = null, frequency: String? = null, condition_met: Boolean? = null, last_run_start: String? = null, last_run_end: String? = null, all_owners: Boolean? = null ) : SDKResponse { return this.get<ByteArray>("/alerts/search", mapOf("limit" to limit, "offset" to offset, "group_by" to group_by, "fields" to fields, "disabled" to disabled, "frequency" to frequency, "condition_met" to condition_met, "last_run_start" to last_run_start, "last_run_end" to last_run_end, "all_owners" to all_owners)) } /** * ### Get an alert by a given alert ID * * @param {String} alert_id ID of an alert * * GET /alerts/{alert_id} -> ByteArray */ fun get_alert( alert_id: String ) : SDKResponse { val path_alert_id = encodeParam(alert_id) return this.get<ByteArray>("/alerts/${path_alert_id}", mapOf()) } /** * ### Update an alert * # Required fields: `owner_id`, `field`, `destinations`, `comparison_type`, `threshold`, `cron` * # * * @param {String} alert_id ID of an alert * @param {WriteAlert} body * * PUT /alerts/{alert_id} -> ByteArray */ fun update_alert( alert_id: String, body: WriteAlert ) : SDKResponse { val path_alert_id = encodeParam(alert_id) return this.put<ByteArray>("/alerts/${path_alert_id}", mapOf(), body) } /** * ### Update select alert fields * # Available fields: `owner_id`, `is_disabled`, `disabled_reason`, `is_public`, `threshold` * # * * @param {String} alert_id ID of an alert * @param {AlertPatch} body * * PATCH /alerts/{alert_id} -> ByteArray */ fun update_alert_field( alert_id: String, body: AlertPatch ) : SDKResponse { val path_alert_id = encodeParam(alert_id) return this.patch<ByteArray>("/alerts/${path_alert_id}", mapOf(), body) } /** * ### Delete an alert by a given alert ID * * @param {String} alert_id ID of an alert * * DELETE /alerts/{alert_id} -> ByteArray */ fun delete_alert( alert_id: String ) : SDKResponse { val path_alert_id = encodeParam(alert_id) return this.delete<ByteArray>("/alerts/${path_alert_id}", mapOf()) } /** * ### Create a new alert and return details of the newly created object * * Required fields: `field`, `destinations`, `comparison_type`, `threshold`, `cron` * * Example Request: * Run alert on dashboard element '103' at 5am every day. Send an email to '[email protected]' if inventory for Los Angeles (using dashboard filter `Warehouse Name`) is lower than 1,000 * ``` * { * "cron": "0 5 * * *", * "custom_title": "Alert when LA inventory is low", * "dashboard_element_id": 103, * "applied_dashboard_filters": [ * { * "filter_title": "Warehouse Name", * "field_name": "distribution_centers.name", * "filter_value": "Los Angeles CA", * "filter_description": "is Los Angeles CA" * } * ], * "comparison_type": "LESS_THAN", * "destinations": [ * { * "destination_type": "EMAIL", * "email_address": "[email protected]" * } * ], * "field": { * "title": "Number on Hand", * "name": "inventory_items.number_on_hand" * }, * "is_disabled": false, * "is_public": true, * "threshold": 1000 * } * ``` * * @param {WriteAlert} body * * POST /alerts -> ByteArray */ fun create_alert( body: WriteAlert ) : SDKResponse { return this.post<ByteArray>("/alerts", mapOf(), body) } /** * ### Enqueue an Alert by ID * * @param {String} alert_id ID of an alert * @param {Boolean} force Whether to enqueue an alert again if its already running. * * POST /alerts/{alert_id}/enqueue -> ByteArray */ @JvmOverloads fun enqueue_alert( alert_id: String, force: Boolean? = null ) : SDKResponse { val path_alert_id = encodeParam(alert_id) return this.post<ByteArray>("/alerts/${path_alert_id}/enqueue", mapOf("force" to force)) } /** * # Alert Notifications. * The endpoint returns all the alert notifications received by the user on email in the past 7 days. It also returns whether the notifications have been read by the user. * * @param {Long} limit (Optional) Number of results to return (used with `offset`). * @param {Long} offset (Optional) Number of results to skip before returning any (used with `limit`). * * GET /alert_notifications -> ByteArray */ @JvmOverloads fun alert_notifications( limit: Long? = null, offset: Long? = null ) : SDKResponse { return this.get<ByteArray>("/alert_notifications", mapOf("limit" to limit, "offset" to offset)) } /** * # Reads a Notification * The endpoint marks a given alert notification as read by the user, in case it wasn't already read. The AlertNotification model is updated for this purpose. It returns the notification as a response. * * @param {String} alert_notification_id ID of a notification * * PATCH /alert_notifications/{alert_notification_id} -> ByteArray */ fun read_alert_notification( alert_notification_id: String ) : SDKResponse { val path_alert_notification_id = encodeParam(alert_notification_id) return this.patch<ByteArray>("/alert_notifications/${path_alert_notification_id}", mapOf()) } //endregion Alert: Alert //region ApiAuth: API Authentication /** * ### Present client credentials to obtain an authorization token * * Looker API implements the OAuth2 [Resource Owner Password Credentials Grant](https://docs.looker.com/r/api/outh2_resource_owner_pc) pattern. * The client credentials required for this login must be obtained by creating an API3 key on a user account * in the Looker Admin console. The API3 key consists of a public `client_id` and a private `client_secret`. * * The access token returned by `login` must be used in the HTTP Authorization header of subsequent * API requests, like this: * ``` * Authorization: token 4QDkCyCtZzYgj4C2p2cj3csJH7zqS5RzKs2kTnG4 * ``` * Replace "4QDkCy..." with the `access_token` value returned by `login`. * The word `token` is a string literal and must be included exactly as shown. * * This function can accept `client_id` and `client_secret` parameters as URL query params or as www-form-urlencoded params in the body of the HTTP request. Since there is a small risk that URL parameters may be visible to intermediate nodes on the network route (proxies, routers, etc), passing credentials in the body of the request is considered more secure than URL params. * * Example of passing credentials in the HTTP request body: * ```` * POST HTTP /login * Content-Type: application/x-www-form-urlencoded * * client_id=CGc9B7v7J48dQSJvxxx&client_secret=nNVS9cSS3xNpSC9JdsBvvvvv * ```` * * ### Best Practice: * Always pass credentials in body params. Pass credentials in URL query params **only** when you cannot pass body params due to application, tool, or other limitations. * * For more information and detailed examples of Looker API authorization, see [How to Authenticate to Looker API3](https://github.com/looker/looker-sdk-ruby/blob/master/authentication.md). * * @param {String} client_id client_id part of API3 Key. * @param {String} client_secret client_secret part of API3 Key. * * POST /login -> ByteArray */ @JvmOverloads fun login( client_id: String? = null, client_secret: String? = null ) : SDKResponse { return this.post<ByteArray>("/login", mapOf("client_id" to client_id, "client_secret" to client_secret)) } /** * ### Create an access token that runs as a given user. * * This can only be called by an authenticated admin user. It allows that admin to generate a new * authentication token for the user with the given user id. That token can then be used for subsequent * API calls - which are then performed *as* that target user. * * The target user does *not* need to have a pre-existing API client_id/client_secret pair. And, no such * credentials are created by this call. * * This allows for building systems where api user authentication for an arbitrary number of users is done * outside of Looker and funneled through a single 'service account' with admin permissions. Note that a * new access token is generated on each call. If target users are going to be making numerous API * calls in a short period then it is wise to cache this authentication token rather than call this before * each of those API calls. * * See 'login' for more detail on the access token and how to use it. * * @param {String} user_id Id of user. * @param {Boolean} associative When true (default), API calls using the returned access_token are attributed to the admin user who created the access_token. When false, API activity is attributed to the user the access_token runs as. False requires a looker license. * * POST /login/{user_id} -> ByteArray */ @JvmOverloads fun login_user( user_id: String, associative: Boolean? = null ) : SDKResponse { val path_user_id = encodeParam(user_id) return this.post<ByteArray>("/login/${path_user_id}", mapOf("associative" to associative)) } /** * ### Logout of the API and invalidate the current access token. * * DELETE /logout -> ByteArray */ fun logout( ) : SDKResponse { return this.delete<ByteArray>("/logout", mapOf()) } //endregion ApiAuth: API Authentication //region Artifact: Artifact Storage /** * Get the maximum configured size of the entire artifact store, and the currently used storage in bytes. * * **Note**: The artifact storage API can only be used by Looker-built extensions. * * @param {String} fields Comma-delimited names of fields to return in responses. Omit for all fields * * GET /artifact/usage -> ByteArray */ @JvmOverloads fun artifact_usage( fields: String? = null ) : SDKResponse { return this.get<ByteArray>("/artifact/usage", mapOf("fields" to fields)) } /** * Get all artifact namespaces and the count of artifacts in each namespace * * **Note**: The artifact storage API can only be used by Looker-built extensions. * * @param {String} fields Comma-delimited names of fields to return in responses. Omit for all fields * @param {Long} limit Number of results to return. (used with offset) * @param {Long} offset Number of results to skip before returning any. (used with limit) * * GET /artifact/namespaces -> ByteArray */ @JvmOverloads fun artifact_namespaces( fields: String? = null, limit: Long? = null, offset: Long? = null ) : SDKResponse { return this.get<ByteArray>("/artifact/namespaces", mapOf("fields" to fields, "limit" to limit, "offset" to offset)) } /** * ### Return the value of an artifact * * The MIME type for the API response is set to the `content_type` of the value * * **Note**: The artifact storage API can only be used by Looker-built extensions. * * @param {String} namespace Artifact storage namespace * @param {String} key Artifact storage key. Namespace + Key must be unique * * GET /artifact/{namespace}/value -> ByteArray */ @JvmOverloads fun artifact_value( namespace: String, key: String? = null ) : SDKResponse { val path_namespace = encodeParam(namespace) return this.get<ByteArray>("/artifact/${path_namespace}/value", mapOf("key" to key)) } /** * Remove *all* artifacts from a namespace. Purged artifacts are permanently deleted * * **Note**: The artifact storage API can only be used by Looker-built extensions. * * @param {String} namespace Artifact storage namespace * * DELETE /artifact/{namespace}/purge -> ByteArray */ fun purge_artifacts( namespace: String ) : SDKResponse { val path_namespace = encodeParam(namespace) return this.delete<ByteArray>("/artifact/${path_namespace}/purge", mapOf()) } /** * ### Search all key/value pairs in a namespace for matching criteria. * * Returns an array of artifacts matching the specified search criteria. * * Key search patterns use case-insensitive matching and can contain `%` and `_` as SQL LIKE pattern match wildcard expressions. * * The parameters `min_size` and `max_size` can be used individually or together. * * - `min_size` finds artifacts with sizes greater than or equal to its value * - `max_size` finds artifacts with sizes less than or equal to its value * - using both parameters restricts the minimum and maximum size range for artifacts * * **NOTE**: Artifacts are always returned in alphanumeric order by key. * * Get a **single artifact** by namespace and key with [`artifact`](#!/Artifact/artifact) * * **Note**: The artifact storage API can only be used by Looker-built extensions. * * @param {String} namespace Artifact storage namespace * @param {String} fields Comma-delimited names of fields to return in responses. Omit for all fields * @param {String} key Key pattern to match * @param {String} user_ids Ids of users who created or updated the artifact (comma-delimited list) * @param {Long} min_size Minimum storage size of the artifact * @param {Long} max_size Maximum storage size of the artifact * @param {Long} limit Number of results to return. (used with offset) * @param {Long} offset Number of results to skip before returning any. (used with limit) * * GET /artifact/{namespace}/search -> ByteArray */ @JvmOverloads fun search_artifacts( namespace: String, fields: String? = null, key: String? = null, user_ids: String? = null, min_size: Long? = null, max_size: Long? = null, limit: Long? = null, offset: Long? = null ) : SDKResponse { val path_namespace = encodeParam(namespace) return this.get<ByteArray>("/artifact/${path_namespace}/search", mapOf("fields" to fields, "key" to key, "user_ids" to user_ids, "min_size" to min_size, "max_size" to max_size, "limit" to limit, "offset" to offset)) } /** * ### Get one or more artifacts * * Returns an array of artifacts matching the specified key value(s). * * **Note**: The artifact storage API can only be used by Looker-built extensions. * * @param {String} namespace Artifact storage namespace * @param {String} key Comma-delimited list of keys. Wildcards not allowed. * @param {String} fields Comma-delimited names of fields to return in responses. Omit for all fields * @param {Long} limit Number of results to return. (used with offset) * @param {Long} offset Number of results to skip before returning any. (used with limit) * * GET /artifact/{namespace} -> ByteArray */ @JvmOverloads fun artifact( namespace: String, key: String, fields: String? = null, limit: Long? = null, offset: Long? = null ) : SDKResponse { val path_namespace = encodeParam(namespace) return this.get<ByteArray>("/artifact/${path_namespace}", mapOf("key" to key, "fields" to fields, "limit" to limit, "offset" to offset)) } /** * ### Delete one or more artifacts * * To avoid rate limiting on deletion requests, multiple artifacts can be deleted at the same time by using a comma-delimited list of artifact keys. * * **Note**: The artifact storage API can only be used by Looker-built extensions. * * @param {String} namespace Artifact storage namespace * @param {String} key Comma-delimited list of keys. Wildcards not allowed. * * DELETE /artifact/{namespace} -> ByteArray */ fun delete_artifact( namespace: String, key: String ) : SDKResponse { val path_namespace = encodeParam(namespace) return this.delete<ByteArray>("/artifact/${path_namespace}", mapOf("key" to key)) } /** * ### Create or update one or more artifacts * * Only `key` and `value` are required to _create_ an artifact. * To _update_ an artifact, its current `version` value must be provided. * * In the following example `body` payload, `one` and `two` are existing artifacts, and `three` is new: * * ```json * [ * { "key": "one", "value": "[ \"updating\", \"existing\", \"one\" ]", "version": 10, "content_type": "application/json" }, * { "key": "two", "value": "updating existing two", "version": 20 }, * { "key": "three", "value": "creating new three" }, * ] * ``` * * Notes for this body: * * - The `value` for `key` **one** is a JSON payload, so a `content_type` override is needed. This override must be done **every** time a JSON value is set. * - The `version` values for **one** and **two** mean they have been saved 10 and 20 times, respectively. * - If `version` is **not** provided for an existing artifact, the entire request will be refused and a `Bad Request` response will be sent. * - If `version` is provided for an artifact, it is only used for helping to prevent inadvertent data overwrites. It cannot be used to **set** the version of an artifact. The Looker server controls `version`. * - We suggest encoding binary values as base64. Because the MIME content type for base64 is detected as plain text, also provide `content_type` to correctly indicate the value's type for retrieval and client-side processing. * * Because artifacts are stored encrypted, the same value can be written multiple times (provided the correct `version` number is used). Looker does not examine any values stored in the artifact store, and only decrypts when sending artifacts back in an API response. * * **Note**: The artifact storage API can only be used by Looker-built extensions. * * @param {String} namespace Artifact storage namespace * @param {Array<UpdateArtifact>} body * @param {String} fields Comma-delimited names of fields to return in responses. Omit for all fields * * PUT /artifacts/{namespace} -> ByteArray */ @JvmOverloads fun update_artifacts( namespace: String, body: Array<UpdateArtifact>, fields: String? = null ) : SDKResponse { val path_namespace = encodeParam(namespace) return this.put<ByteArray>("/artifacts/${path_namespace}", mapOf("fields" to fields), body) } //endregion Artifact: Artifact Storage //region Auth: Manage User Authentication Configuration /** * ### Create an embed secret using the specified information. * * The value of the `secret` field will be set by Looker and returned. * * @param {WriteEmbedSecret} body * * POST /embed_config/secrets -> ByteArray */ @JvmOverloads fun create_embed_secret( body: WriteEmbedSecret? = null ) : SDKResponse { return this.post<ByteArray>("/embed_config/secrets", mapOf(), body) } /** * ### Delete an embed secret. * * @param {String} embed_secret_id Id of Embed Secret * * DELETE /embed_config/secrets/{embed_secret_id} -> ByteArray */ fun delete_embed_secret( embed_secret_id: String ) : SDKResponse { val path_embed_secret_id = encodeParam(embed_secret_id) return this.delete<ByteArray>("/embed_config/secrets/${path_embed_secret_id}", mapOf()) } /** * ### Create SSO Embed URL * * Creates an SSO embed URL and cryptographically signs it with an embed secret. * This signed URL can then be used to instantiate a Looker embed session in a PBL web application. * Do not make any modifications to this URL - any change may invalidate the signature and * cause the URL to fail to load a Looker embed session. * * A signed SSO embed URL can only be used once. After it has been used to request a page from the * Looker server, the URL is invalid. Future requests using the same URL will fail. This is to prevent * 'replay attacks'. * * The `target_url` property must be a complete URL of a Looker UI page - scheme, hostname, path and query params. * To load a dashboard with id 56 and with a filter of `Date=1 years`, the looker URL would look like `https:/myname.looker.com/dashboards/56?Date=1%20years`. * The best way to obtain this target_url is to navigate to the desired Looker page in your web browser, * copy the URL shown in the browser address bar and paste it into the `target_url` property as a quoted string value in this API request. * * Permissions for the embed user are defined by the groups in which the embed user is a member (group_ids property) * and the lists of models and permissions assigned to the embed user. * At a minimum, you must provide values for either the group_ids property, or both the models and permissions properties. * These properties are additive; an embed user can be a member of certain groups AND be granted access to models and permissions. * * The embed user's access is the union of permissions granted by the group_ids, models, and permissions properties. * * This function does not strictly require all group_ids, user attribute names, or model names to exist at the moment the * SSO embed url is created. Unknown group_id, user attribute names or model names will be passed through to the output URL. * To diagnose potential problems with an SSO embed URL, you can copy the signed URL into the Embed URI Validator text box in `<your looker instance>/admin/embed`. * * The `secret_id` parameter is optional. If specified, its value must be the id of an active secret defined in the Looker instance. * if not specified, the URL will be signed using the newest active secret defined in the Looker instance. * * #### Security Note * Protect this signed URL as you would an access token or password credentials - do not write * it to disk, do not pass it to a third party, and only pass it through a secure HTTPS * encrypted transport. * * @param {EmbedSsoParams} body * * POST /embed/sso_url -> ByteArray */ fun create_sso_embed_url( body: EmbedSsoParams ) : SDKResponse { return this.post<ByteArray>("/embed/sso_url", mapOf(), body) } /** * ### Create an Embed URL * * Creates an embed URL that runs as the Looker user making this API call. ("Embed as me") * This embed URL can then be used to instantiate a Looker embed session in a * "Powered by Looker" (PBL) web application. * * This is similar to Private Embedding (https://docs.looker.com/r/admin/embed/private-embed). Instead of * of logging into the Web UI to authenticate, the user has already authenticated against the API to be able to * make this call. However, unlike Private Embed where the user has access to any other part of the Looker UI, * the embed web session created by requesting the EmbedUrlResponse.url in a browser only has access to * content visible under the `/embed` context. * * An embed URL can only be used once, and must be used within 5 minutes of being created. After it * has been used to request a page from the Looker server, the URL is invalid. Future requests using * the same URL will fail. This is to prevent 'replay attacks'. * * The `target_url` property must be a complete URL of a Looker Embedded UI page - scheme, hostname, path starting with "/embed" and query params. * To load a dashboard with id 56 and with a filter of `Date=1 years`, the looker Embed URL would look like `https://myname.looker.com/embed/dashboards/56?Date=1%20years`. * The best way to obtain this target_url is to navigate to the desired Looker page in your web browser, * copy the URL shown in the browser address bar, insert "/embed" after the host/port, and paste it into the `target_url` property as a quoted string value in this API request. * * #### Security Note * Protect this embed URL as you would an access token or password credentials - do not write * it to disk, do not pass it to a third party, and only pass it through a secure HTTPS * encrypted transport. * * @param {EmbedParams} body * * POST /embed/token_url/me -> ByteArray */ fun create_embed_url_as_me( body: EmbedParams ) : SDKResponse { return this.post<ByteArray>("/embed/token_url/me", mapOf(), body) } /** * ### Acquire a cookieless embed session. * * The acquire session endpoint negates the need for signing the embed url and passing it as a parameter * to the embed login. This endpoint accepts an embed user definition and creates it if it does not exist, * otherwise it reuses it. Note that this endpoint will not update the user, user attributes or group * attributes if the embed user already exists. This is the same behavior as the embed SSO login. * * The endpoint also accepts an optional `session_reference_token`. If present and the session has not expired * and the credentials match the credentials for the embed session, a new authentication token will be * generated. This allows the embed session to attach a new embedded IFRAME to the embed session. Note that * the session will NOT be extended in this scenario, in other words the session_length parameter is ignored. * * If the session_reference_token has expired, it will be ignored and a new embed session will be created. * * If the credentials do not match the credentials associated with an exisiting session_reference_token, a * 404 will be returned. * * The endpoint returns the following: * - Authentication token - a token that is passed to `/embed/login` endpoint that creates or attaches to the * embed session. This token can be used once and has a lifetime of 30 seconds. * - Session reference token - a token that lives for the length of the session. This token is used to * generate new api and navigation tokens OR create new embed IFRAMEs. * - Api token - lives for 10 minutes. The Looker client will ask for this token once it is loaded into the * iframe. * - Navigation token - lives for 10 minutes. The Looker client will ask for this token once it is loaded into * the iframe. * * @param {EmbedCookielessSessionAcquire} body * * POST /embed/cookieless_session/acquire -> ByteArray */ fun acquire_embed_cookieless_session( body: EmbedCookielessSessionAcquire ) : SDKResponse { return this.post<ByteArray>("/embed/cookieless_session/acquire", mapOf(), body) } /** * ### Delete cookieless embed session * * This will delete the session associated with the given session reference token. Calling this endpoint will result * in the session and session reference data being cleared from the system. This endpoint can be used to log an embed * user out of the Looker instance. * * @param {String} session_reference_token Embed session reference token * * DELETE /embed/cookieless_session/{session_reference_token} -> ByteArray */ fun delete_embed_cookieless_session( session_reference_token: String ) : SDKResponse { val path_session_reference_token = encodeParam(session_reference_token) return this.delete<ByteArray>("/embed/cookieless_session/${path_session_reference_token}", mapOf()) } /** * ### Generate api and navigation tokens for a cookieless embed session * * The generate tokens endpoint is used to create new tokens of type: * - Api token. * - Navigation token. * The generate tokens endpoint should be called every time the Looker client asks for a token (except for the * first time when the tokens returned by the acquire_session endpoint should be used). * * @param {EmbedCookielessSessionGenerateTokens} body * * PUT /embed/cookieless_session/generate_tokens -> ByteArray */ fun generate_tokens_for_cookieless_session( body: EmbedCookielessSessionGenerateTokens ) : SDKResponse { return this.put<ByteArray>("/embed/cookieless_session/generate_tokens", mapOf(), body) } /** * ### Get the LDAP configuration. * * Looker can be optionally configured to authenticate users against an Active Directory or other LDAP directory server. * LDAP setup requires coordination with an administrator of that directory server. * * Only Looker administrators can read and update the LDAP configuration. * * Configuring LDAP impacts authentication for all users. This configuration should be done carefully. * * Looker maintains a single LDAP configuration. It can be read and updated. Updates only succeed if the new state will be valid (in the sense that all required fields are populated); it is up to you to ensure that the configuration is appropriate and correct). * * LDAP is enabled or disabled for Looker using the **enabled** field. * * Looker will never return an **auth_password** field. That value can be set, but never retrieved. * * See the [Looker LDAP docs](https://docs.looker.com/r/api/ldap_setup) for additional information. * * GET /ldap_config -> ByteArray */ fun ldap_config( ) : SDKResponse { return this.get<ByteArray>("/ldap_config", mapOf()) } /** * ### Update the LDAP configuration. * * Configuring LDAP impacts authentication for all users. This configuration should be done carefully. * * Only Looker administrators can read and update the LDAP configuration. * * LDAP is enabled or disabled for Looker using the **enabled** field. * * It is **highly** recommended that any LDAP setting changes be tested using the APIs below before being set globally. * * See the [Looker LDAP docs](https://docs.looker.com/r/api/ldap_setup) for additional information. * * @param {WriteLDAPConfig} body * * PATCH /ldap_config -> ByteArray */ fun update_ldap_config( body: WriteLDAPConfig ) : SDKResponse { return this.patch<ByteArray>("/ldap_config", mapOf(), body) } /** * ### Test the connection settings for an LDAP configuration. * * This tests that the connection is possible given a connection_host and connection_port. * * **connection_host** and **connection_port** are required. **connection_tls** is optional. * * Example: * ```json * { * "connection_host": "ldap.example.com", * "connection_port": "636", * "connection_tls": true * } * ``` * * No authentication to the LDAP server is attempted. * * The active LDAP settings are not modified. * * @param {WriteLDAPConfig} body * * PUT /ldap_config/test_connection -> ByteArray */ fun test_ldap_config_connection( body: WriteLDAPConfig ) : SDKResponse { return this.put<ByteArray>("/ldap_config/test_connection", mapOf(), body) } /** * ### Test the connection authentication settings for an LDAP configuration. * * This tests that the connection is possible and that a 'server' account to be used by Looker can authenticate to the LDAP server given connection and authentication information. * * **connection_host**, **connection_port**, and **auth_username**, are required. **connection_tls** and **auth_password** are optional. * * Example: * ```json * { * "connection_host": "ldap.example.com", * "connection_port": "636", * "connection_tls": true, * "auth_username": "cn=looker,dc=example,dc=com", * "auth_password": "secret" * } * ``` * * Looker will never return an **auth_password**. If this request omits the **auth_password** field, then the **auth_password** value from the active config (if present) will be used for the test. * * The active LDAP settings are not modified. * * @param {WriteLDAPConfig} body * * PUT /ldap_config/test_auth -> ByteArray */ fun test_ldap_config_auth( body: WriteLDAPConfig ) : SDKResponse { return this.put<ByteArray>("/ldap_config/test_auth", mapOf(), body) } /** * ### Test the user authentication settings for an LDAP configuration without authenticating the user. * * This test will let you easily test the mapping for user properties and roles for any user without needing to authenticate as that user. * * This test accepts a full LDAP configuration along with a username and attempts to find the full info for the user from the LDAP server without actually authenticating the user. So, user password is not required.The configuration is validated before attempting to contact the server. * * **test_ldap_user** is required. * * The active LDAP settings are not modified. * * @param {WriteLDAPConfig} body * * PUT /ldap_config/test_user_info -> ByteArray */ fun test_ldap_config_user_info( body: WriteLDAPConfig ) : SDKResponse { return this.put<ByteArray>("/ldap_config/test_user_info", mapOf(), body) } /** * ### Test the user authentication settings for an LDAP configuration. * * This test accepts a full LDAP configuration along with a username/password pair and attempts to authenticate the user with the LDAP server. The configuration is validated before attempting the authentication. * * Looker will never return an **auth_password**. If this request omits the **auth_password** field, then the **auth_password** value from the active config (if present) will be used for the test. * * **test_ldap_user** and **test_ldap_password** are required. * * The active LDAP settings are not modified. * * @param {WriteLDAPConfig} body * * PUT /ldap_config/test_user_auth -> ByteArray */ fun test_ldap_config_user_auth( body: WriteLDAPConfig ) : SDKResponse { return this.put<ByteArray>("/ldap_config/test_user_auth", mapOf(), body) } /** * ### Registers a mobile device. * # Required fields: [:device_token, :device_type] * * @param {WriteMobileToken} body * * POST /mobile/device -> ByteArray */ fun register_mobile_device( body: WriteMobileToken ) : SDKResponse { return this.post<ByteArray>("/mobile/device", mapOf(), body) } /** * ### Updates the mobile device registration * * @param {String} device_id Unique id of the device. * * PATCH /mobile/device/{device_id} -> ByteArray */ fun update_mobile_device_registration( device_id: String ) : SDKResponse { val path_device_id = encodeParam(device_id) return this.patch<ByteArray>("/mobile/device/${path_device_id}", mapOf()) } /** * ### Deregister a mobile device. * * @param {String} device_id Unique id of the device. * * DELETE /mobile/device/{device_id} -> ByteArray */ fun deregister_mobile_device( device_id: String ) : SDKResponse { val path_device_id = encodeParam(device_id) return this.delete<ByteArray>("/mobile/device/${path_device_id}", mapOf()) } /** * ### List All OAuth Client Apps * * Lists all applications registered to use OAuth2 login with this Looker instance, including * enabled and disabled apps. * * Results are filtered to include only the apps that the caller (current user) * has permission to see. * * @param {String} fields Requested fields. * * GET /oauth_client_apps -> ByteArray */ @JvmOverloads fun all_oauth_client_apps( fields: String? = null ) : SDKResponse { return this.get<ByteArray>("/oauth_client_apps", mapOf("fields" to fields)) } /** * ### Get Oauth Client App * * Returns the registered app client with matching client_guid. * * @param {String} client_guid The unique id of this application * @param {String} fields Requested fields. * * GET /oauth_client_apps/{client_guid} -> ByteArray */ @JvmOverloads fun oauth_client_app( client_guid: String, fields: String? = null ) : SDKResponse { val path_client_guid = encodeParam(client_guid) return this.get<ByteArray>("/oauth_client_apps/${path_client_guid}", mapOf("fields" to fields)) } /** * ### Register an OAuth2 Client App * * Registers details identifying an external web app or native app as an OAuth2 login client of the Looker instance. * The app registration must provide a unique client_guid and redirect_uri that the app will present * in OAuth login requests. If the client_guid and redirect_uri parameters in the login request do not match * the app details registered with the Looker instance, the request is assumed to be a forgery and is rejected. * * @param {String} client_guid The unique id of this application * @param {WriteOauthClientApp} body * @param {String} fields Requested fields. * * POST /oauth_client_apps/{client_guid} -> ByteArray */ @JvmOverloads fun register_oauth_client_app( client_guid: String, body: WriteOauthClientApp, fields: String? = null ) : SDKResponse { val path_client_guid = encodeParam(client_guid) return this.post<ByteArray>("/oauth_client_apps/${path_client_guid}", mapOf("fields" to fields), body) } /** * ### Update OAuth2 Client App Details * * Modifies the details a previously registered OAuth2 login client app. * * @param {String} client_guid The unique id of this application * @param {WriteOauthClientApp} body * @param {String} fields Requested fields. * * PATCH /oauth_client_apps/{client_guid} -> ByteArray */ @JvmOverloads fun update_oauth_client_app( client_guid: String, body: WriteOauthClientApp, fields: String? = null ) : SDKResponse { val path_client_guid = encodeParam(client_guid) return this.patch<ByteArray>("/oauth_client_apps/${path_client_guid}", mapOf("fields" to fields), body) } /** * ### Delete OAuth Client App * * Deletes the registration info of the app with the matching client_guid. * All active sessions and tokens issued for this app will immediately become invalid. * * As with most REST DELETE operations, this endpoint does not return an error if the * indicated resource does not exist. * * ### Note: this deletion cannot be undone. * * @param {String} client_guid The unique id of this application * * DELETE /oauth_client_apps/{client_guid} -> ByteArray */ fun delete_oauth_client_app( client_guid: String ) : SDKResponse { val path_client_guid = encodeParam(client_guid) return this.delete<ByteArray>("/oauth_client_apps/${path_client_guid}", mapOf()) } /** * ### Invalidate All Issued Tokens * * Immediately invalidates all auth codes, sessions, access tokens and refresh tokens issued for * this app for ALL USERS of this app. * * @param {String} client_guid The unique id of the application * * DELETE /oauth_client_apps/{client_guid}/tokens -> ByteArray */ fun invalidate_tokens( client_guid: String ) : SDKResponse { val path_client_guid = encodeParam(client_guid) return this.delete<ByteArray>("/oauth_client_apps/${path_client_guid}/tokens", mapOf()) } /** * ### Activate an app for a user * * Activates a user for a given oauth client app. This indicates the user has been informed that * the app will have access to the user's looker data, and that the user has accepted and allowed * the app to use their Looker account. * * Activating a user for an app that the user is already activated with returns a success response. * * @param {String} client_guid The unique id of this application * @param {String} user_id The id of the user to enable use of this app * @param {String} fields Requested fields. * * POST /oauth_client_apps/{client_guid}/users/{user_id} -> ByteArray */ @JvmOverloads fun activate_app_user( client_guid: String, user_id: String, fields: String? = null ) : SDKResponse { val path_client_guid = encodeParam(client_guid) val path_user_id = encodeParam(user_id) return this.post<ByteArray>("/oauth_client_apps/${path_client_guid}/users/${path_user_id}", mapOf("fields" to fields)) } /** * ### Deactivate an app for a user * * Deactivate a user for a given oauth client app. All tokens issued to the app for * this user will be invalid immediately. Before the user can use the app with their * Looker account, the user will have to read and accept an account use disclosure statement for the app. * * Admin users can deactivate other users, but non-admin users can only deactivate themselves. * * As with most REST DELETE operations, this endpoint does not return an error if the indicated * resource (app or user) does not exist or has already been deactivated. * * @param {String} client_guid The unique id of this application * @param {String} user_id The id of the user to enable use of this app * @param {String} fields Requested fields. * * DELETE /oauth_client_apps/{client_guid}/users/{user_id} -> ByteArray */ @JvmOverloads fun deactivate_app_user( client_guid: String, user_id: String, fields: String? = null ) : SDKResponse { val path_client_guid = encodeParam(client_guid) val path_user_id = encodeParam(user_id) return this.delete<ByteArray>("/oauth_client_apps/${path_client_guid}/users/${path_user_id}", mapOf("fields" to fields)) } /** * ### Get the OIDC configuration. * * Looker can be optionally configured to authenticate users against an OpenID Connect (OIDC) * authentication server. OIDC setup requires coordination with an administrator of that server. * * Only Looker administrators can read and update the OIDC configuration. * * Configuring OIDC impacts authentication for all users. This configuration should be done carefully. * * Looker maintains a single OIDC configuation. It can be read and updated. Updates only succeed if the new state will be valid (in the sense that all required fields are populated); it is up to you to ensure that the configuration is appropriate and correct). * * OIDC is enabled or disabled for Looker using the **enabled** field. * * GET /oidc_config -> ByteArray */ fun oidc_config( ) : SDKResponse { return this.get<ByteArray>("/oidc_config", mapOf()) } /** * ### Update the OIDC configuration. * * Configuring OIDC impacts authentication for all users. This configuration should be done carefully. * * Only Looker administrators can read and update the OIDC configuration. * * OIDC is enabled or disabled for Looker using the **enabled** field. * * It is **highly** recommended that any OIDC setting changes be tested using the APIs below before being set globally. * * @param {WriteOIDCConfig} body * * PATCH /oidc_config -> ByteArray */ fun update_oidc_config( body: WriteOIDCConfig ) : SDKResponse { return this.patch<ByteArray>("/oidc_config", mapOf(), body) } /** * ### Get a OIDC test configuration by test_slug. * * @param {String} test_slug Slug of test config * * GET /oidc_test_configs/{test_slug} -> ByteArray */ fun oidc_test_config( test_slug: String ) : SDKResponse { val path_test_slug = encodeParam(test_slug) return this.get<ByteArray>("/oidc_test_configs/${path_test_slug}", mapOf()) } /** * ### Delete a OIDC test configuration. * * @param {String} test_slug Slug of test config * * DELETE /oidc_test_configs/{test_slug} -> ByteArray */ fun delete_oidc_test_config( test_slug: String ) : SDKResponse { val path_test_slug = encodeParam(test_slug) return this.delete<ByteArray>("/oidc_test_configs/${path_test_slug}", mapOf()) } /** * ### Create a OIDC test configuration. * * @param {WriteOIDCConfig} body * * POST /oidc_test_configs -> ByteArray */ fun create_oidc_test_config( body: WriteOIDCConfig ) : SDKResponse { return this.post<ByteArray>("/oidc_test_configs", mapOf(), body) } /** * ### Get password config. * * GET /password_config -> ByteArray */ fun password_config( ) : SDKResponse { return this.get<ByteArray>("/password_config", mapOf()) } /** * ### Update password config. * * @param {WritePasswordConfig} body * * PATCH /password_config -> ByteArray */ fun update_password_config( body: WritePasswordConfig ) : SDKResponse { return this.patch<ByteArray>("/password_config", mapOf(), body) } /** * ### Force all credentials_email users to reset their login passwords upon their next login. * * PUT /password_config/force_password_reset_at_next_login_for_all_users -> ByteArray */ fun force_password_reset_at_next_login_for_all_users( ) : SDKResponse { return this.put<ByteArray>("/password_config/force_password_reset_at_next_login_for_all_users", mapOf()) } /** * ### Get the SAML configuration. * * Looker can be optionally configured to authenticate users against a SAML authentication server. * SAML setup requires coordination with an administrator of that server. * * Only Looker administrators can read and update the SAML configuration. * * Configuring SAML impacts authentication for all users. This configuration should be done carefully. * * Looker maintains a single SAML configuation. It can be read and updated. Updates only succeed if the new state will be valid (in the sense that all required fields are populated); it is up to you to ensure that the configuration is appropriate and correct). * * SAML is enabled or disabled for Looker using the **enabled** field. * * GET /saml_config -> ByteArray */ fun saml_config( ) : SDKResponse { return this.get<ByteArray>("/saml_config", mapOf()) } /** * ### Update the SAML configuration. * * Configuring SAML impacts authentication for all users. This configuration should be done carefully. * * Only Looker administrators can read and update the SAML configuration. * * SAML is enabled or disabled for Looker using the **enabled** field. * * It is **highly** recommended that any SAML setting changes be tested using the APIs below before being set globally. * * @param {WriteSamlConfig} body * * PATCH /saml_config -> ByteArray */ fun update_saml_config( body: WriteSamlConfig ) : SDKResponse { return this.patch<ByteArray>("/saml_config", mapOf(), body) } /** * ### Get a SAML test configuration by test_slug. * * @param {String} test_slug Slug of test config * * GET /saml_test_configs/{test_slug} -> ByteArray */ fun saml_test_config( test_slug: String ) : SDKResponse { val path_test_slug = encodeParam(test_slug) return this.get<ByteArray>("/saml_test_configs/${path_test_slug}", mapOf()) } /** * ### Delete a SAML test configuration. * * @param {String} test_slug Slug of test config * * DELETE /saml_test_configs/{test_slug} -> ByteArray */ fun delete_saml_test_config( test_slug: String ) : SDKResponse { val path_test_slug = encodeParam(test_slug) return this.delete<ByteArray>("/saml_test_configs/${path_test_slug}", mapOf()) } /** * ### Create a SAML test configuration. * * @param {WriteSamlConfig} body * * POST /saml_test_configs -> ByteArray */ fun create_saml_test_config( body: WriteSamlConfig ) : SDKResponse { return this.post<ByteArray>("/saml_test_configs", mapOf(), body) } /** * ### Parse the given xml as a SAML IdP metadata document and return the result. * * @param {String} body * * POST /parse_saml_idp_metadata -> ByteArray */ fun parse_saml_idp_metadata( body: String ) : SDKResponse { return this.post<ByteArray>("/parse_saml_idp_metadata", mapOf(), body) } /** * ### Fetch the given url and parse it as a SAML IdP metadata document and return the result. * Note that this requires that the url be public or at least at a location where the Looker instance * can fetch it without requiring any special authentication. * * @param {String} body * * POST /fetch_and_parse_saml_idp_metadata -> ByteArray */ fun fetch_and_parse_saml_idp_metadata( body: String ) : SDKResponse { return this.post<ByteArray>("/fetch_and_parse_saml_idp_metadata", mapOf(), body) } /** * ### Get session config. * * GET /session_config -> ByteArray */ fun session_config( ) : SDKResponse { return this.get<ByteArray>("/session_config", mapOf()) } /** * ### Update session config. * * @param {WriteSessionConfig} body * * PATCH /session_config -> ByteArray */ fun update_session_config( body: WriteSessionConfig ) : SDKResponse { return this.patch<ByteArray>("/session_config", mapOf(), body) } /** * ### Get Support Access Allowlist Users * * Returns the users that have been added to the Support Access Allowlist * * @param {String} fields Requested fields. * * GET /support_access/allowlist -> ByteArray */ @JvmOverloads fun get_support_access_allowlist_entries( fields: String? = null ) : SDKResponse { return this.get<ByteArray>("/support_access/allowlist", mapOf("fields" to fields)) } /** * ### Add Support Access Allowlist Users * * Adds a list of emails to the Allowlist, using the provided reason * * @param {SupportAccessAddEntries} body * * POST /support_access/allowlist -> ByteArray */ fun add_support_access_allowlist_entries( body: SupportAccessAddEntries ) : SDKResponse { return this.post<ByteArray>("/support_access/allowlist", mapOf(), body) } /** * ### Delete Support Access Allowlist User * * Deletes the specified Allowlist Entry Id * * @param {String} entry_id Id of Allowlist Entry * * DELETE /support_access/allowlist/{entry_id} -> ByteArray */ fun delete_support_access_allowlist_entry( entry_id: String ) : SDKResponse { val path_entry_id = encodeParam(entry_id) return this.delete<ByteArray>("/support_access/allowlist/${path_entry_id}", mapOf()) } /** * ### Enable Support Access * * Enables Support Access for the provided duration * * @param {SupportAccessEnable} body * * PUT /support_access/enable -> ByteArray */ fun enable_support_access( body: SupportAccessEnable ) : SDKResponse { return this.put<ByteArray>("/support_access/enable", mapOf(), body) } /** * ### Disable Support Access * * Disables Support Access immediately * * PUT /support_access/disable -> ByteArray */ fun disable_support_access( ) : SDKResponse { return this.put<ByteArray>("/support_access/disable", mapOf()) } /** * ### Support Access Status * * Returns the current Support Access Status * * GET /support_access/status -> ByteArray */ fun support_access_status( ) : SDKResponse { return this.get<ByteArray>("/support_access/status", mapOf()) } /** * ### Get currently locked-out users. * * @param {String} fields Include only these fields in the response * * GET /user_login_lockouts -> ByteArray */ @JvmOverloads fun all_user_login_lockouts( fields: String? = null ) : SDKResponse { return this.get<ByteArray>("/user_login_lockouts", mapOf("fields" to fields)) } /** * ### Search currently locked-out users. * * @param {String} fields Include only these fields in the response * @param {Long} page DEPRECATED. Use limit and offset instead. Return only page N of paginated results * @param {Long} per_page DEPRECATED. Use limit and offset instead. Return N rows of data per page * @param {Long} limit Number of results to return. (used with offset and takes priority over page and per_page) * @param {Long} offset Number of results to skip before returning any. (used with limit and takes priority over page and per_page) * @param {String} sorts Fields to sort by. * @param {String} auth_type Auth type user is locked out for (email, ldap, totp, api) * @param {String} full_name Match name * @param {String} email Match email * @param {String} remote_id Match remote LDAP ID * @param {Boolean} filter_or Combine given search criteria in a boolean OR expression * * GET /user_login_lockouts/search -> ByteArray */ @JvmOverloads fun search_user_login_lockouts( fields: String? = null, page: Long? = null, per_page: Long? = null, limit: Long? = null, offset: Long? = null, sorts: String? = null, auth_type: String? = null, full_name: String? = null, email: String? = null, remote_id: String? = null, filter_or: Boolean? = null ) : SDKResponse { return this.get<ByteArray>("/user_login_lockouts/search", mapOf("fields" to fields, "page" to page, "per_page" to per_page, "limit" to limit, "offset" to offset, "sorts" to sorts, "auth_type" to auth_type, "full_name" to full_name, "email" to email, "remote_id" to remote_id, "filter_or" to filter_or)) } /** * ### Removes login lockout for the associated user. * * @param {String} key The key associated with the locked user * * DELETE /user_login_lockout/{key} -> ByteArray */ fun delete_user_login_lockout( key: String ) : SDKResponse { val path_key = encodeParam(key) return this.delete<ByteArray>("/user_login_lockout/${path_key}", mapOf()) } //endregion Auth: Manage User Authentication Configuration //region Board: Manage Boards /** * ### Get information about all boards. * * @param {String} fields Requested fields. * * GET /boards -> ByteArray */ @JvmOverloads fun all_boards( fields: String? = null ) : SDKResponse { return this.get<ByteArray>("/boards", mapOf("fields" to fields)) } /** * ### Create a new board. * * @param {WriteBoard} body * @param {String} fields Requested fields. * * POST /boards -> ByteArray */ @JvmOverloads fun create_board( body: WriteBoard, fields: String? = null ) : SDKResponse { return this.post<ByteArray>("/boards", mapOf("fields" to fields), body) } /** * ### Search Boards * * If multiple search params are given and `filter_or` is FALSE or not specified, * search params are combined in a logical AND operation. * Only rows that match *all* search param criteria will be returned. * * If `filter_or` is TRUE, multiple search params are combined in a logical OR operation. * Results will include rows that match **any** of the search criteria. * * String search params use case-insensitive matching. * String search params can contain `%` and '_' as SQL LIKE pattern match wildcard expressions. * example="dan%" will match "danger" and "Danzig" but not "David" * example="D_m%" will match "Damage" and "dump" * * Integer search params can accept a single value or a comma separated list of values. The multiple * values will be combined under a logical OR operation - results will match at least one of * the given values. * * Most search params can accept "IS NULL" and "NOT NULL" as special expressions to match * or exclude (respectively) rows where the column is null. * * Boolean search params accept only "true" and "false" as values. * * @param {String} title Matches board title. * @param {String} created_at Matches the timestamp for when the board was created. * @param {String} first_name The first name of the user who created this board. * @param {String} last_name The last name of the user who created this board. * @param {String} fields Requested fields. * @param {Boolean} favorited Return favorited boards when true. * @param {String} creator_id Filter on boards created by a particular user. * @param {String} sorts The fields to sort the results by * @param {Long} page The page to return. DEPRECATED. Use offset instead. * @param {Long} per_page The number of items in the returned page. DEPRECATED. Use limit instead. * @param {Long} offset The number of items to skip before returning any. (used with limit and takes priority over page and per_page) * @param {Long} limit The maximum number of items to return. (used with offset and takes priority over page and per_page) * @param {Boolean} filter_or Combine given search criteria in a boolean OR expression * @param {String} permission Filter results based on permission, either show (default) or update * * GET /boards/search -> ByteArray */ @JvmOverloads fun search_boards( title: String? = null, created_at: String? = null, first_name: String? = null, last_name: String? = null, fields: String? = null, favorited: Boolean? = null, creator_id: String? = null, sorts: String? = null, page: Long? = null, per_page: Long? = null, offset: Long? = null, limit: Long? = null, filter_or: Boolean? = null, permission: String? = null ) : SDKResponse { return this.get<ByteArray>("/boards/search", mapOf("title" to title, "created_at" to created_at, "first_name" to first_name, "last_name" to last_name, "fields" to fields, "favorited" to favorited, "creator_id" to creator_id, "sorts" to sorts, "page" to page, "per_page" to per_page, "offset" to offset, "limit" to limit, "filter_or" to filter_or, "permission" to permission)) } /** * ### Get information about a board. * * @param {String} board_id Id of board * @param {String} fields Requested fields. * * GET /boards/{board_id} -> ByteArray */ @JvmOverloads fun board( board_id: String, fields: String? = null ) : SDKResponse { val path_board_id = encodeParam(board_id) return this.get<ByteArray>("/boards/${path_board_id}", mapOf("fields" to fields)) } /** * ### Update a board definition. * * @param {String} board_id Id of board * @param {WriteBoard} body * @param {String} fields Requested fields. * * PATCH /boards/{board_id} -> ByteArray */ @JvmOverloads fun update_board( board_id: String, body: WriteBoard, fields: String? = null ) : SDKResponse { val path_board_id = encodeParam(board_id) return this.patch<ByteArray>("/boards/${path_board_id}", mapOf("fields" to fields), body) } /** * ### Delete a board. * * @param {String} board_id Id of board * * DELETE /boards/{board_id} -> ByteArray */ fun delete_board( board_id: String ) : SDKResponse { val path_board_id = encodeParam(board_id) return this.delete<ByteArray>("/boards/${path_board_id}", mapOf()) } /** * ### Get information about all board items. * * @param {String} fields Requested fields. * @param {String} sorts Fields to sort by. * @param {String} board_section_id Filter to a specific board section * * GET /board_items -> ByteArray */ @JvmOverloads fun all_board_items( fields: String? = null, sorts: String? = null, board_section_id: String? = null ) : SDKResponse { return this.get<ByteArray>("/board_items", mapOf("fields" to fields, "sorts" to sorts, "board_section_id" to board_section_id)) } /** * ### Create a new board item. * * @param {WriteBoardItem} body * @param {String} fields Requested fields. * * POST /board_items -> ByteArray */ @JvmOverloads fun create_board_item( body: WriteBoardItem, fields: String? = null ) : SDKResponse { return this.post<ByteArray>("/board_items", mapOf("fields" to fields), body) } /** * ### Get information about a board item. * * @param {String} board_item_id Id of board item * @param {String} fields Requested fields. * * GET /board_items/{board_item_id} -> ByteArray */ @JvmOverloads fun board_item( board_item_id: String, fields: String? = null ) : SDKResponse { val path_board_item_id = encodeParam(board_item_id) return this.get<ByteArray>("/board_items/${path_board_item_id}", mapOf("fields" to fields)) } /** * ### Update a board item definition. * * @param {String} board_item_id Id of board item * @param {WriteBoardItem} body * @param {String} fields Requested fields. * * PATCH /board_items/{board_item_id} -> ByteArray */ @JvmOverloads fun update_board_item( board_item_id: String, body: WriteBoardItem, fields: String? = null ) : SDKResponse { val path_board_item_id = encodeParam(board_item_id) return this.patch<ByteArray>("/board_items/${path_board_item_id}", mapOf("fields" to fields), body) } /** * ### Delete a board item. * * @param {String} board_item_id Id of board item * * DELETE /board_items/{board_item_id} -> ByteArray */ fun delete_board_item( board_item_id: String ) : SDKResponse { val path_board_item_id = encodeParam(board_item_id) return this.delete<ByteArray>("/board_items/${path_board_item_id}", mapOf()) } /** * ### Get information about all board sections. * * @param {String} fields Requested fields. * @param {String} sorts Fields to sort by. * * GET /board_sections -> ByteArray */ @JvmOverloads fun all_board_sections( fields: String? = null, sorts: String? = null ) : SDKResponse { return this.get<ByteArray>("/board_sections", mapOf("fields" to fields, "sorts" to sorts)) } /** * ### Create a new board section. * * @param {WriteBoardSection} body * @param {String} fields Requested fields. * * POST /board_sections -> ByteArray */ @JvmOverloads fun create_board_section( body: WriteBoardSection, fields: String? = null ) : SDKResponse { return this.post<ByteArray>("/board_sections", mapOf("fields" to fields), body) } /** * ### Get information about a board section. * * @param {String} board_section_id Id of board section * @param {String} fields Requested fields. * * GET /board_sections/{board_section_id} -> ByteArray */ @JvmOverloads fun board_section( board_section_id: String, fields: String? = null ) : SDKResponse { val path_board_section_id = encodeParam(board_section_id) return this.get<ByteArray>("/board_sections/${path_board_section_id}", mapOf("fields" to fields)) } /** * ### Update a board section definition. * * @param {String} board_section_id Id of board section * @param {WriteBoardSection} body * @param {String} fields Requested fields. * * PATCH /board_sections/{board_section_id} -> ByteArray */ @JvmOverloads fun update_board_section( board_section_id: String, body: WriteBoardSection, fields: String? = null ) : SDKResponse { val path_board_section_id = encodeParam(board_section_id) return this.patch<ByteArray>("/board_sections/${path_board_section_id}", mapOf("fields" to fields), body) } /** * ### Delete a board section. * * @param {String} board_section_id Id of board section * * DELETE /board_sections/{board_section_id} -> ByteArray */ fun delete_board_section( board_section_id: String ) : SDKResponse { val path_board_section_id = encodeParam(board_section_id) return this.delete<ByteArray>("/board_sections/${path_board_section_id}", mapOf()) } //endregion Board: Manage Boards //region ColorCollection: Manage Color Collections /** * ### Get an array of all existing Color Collections * Get a **single** color collection by id with [ColorCollection](#!/ColorCollection/color_collection) * * Get all **standard** color collections with [ColorCollection](#!/ColorCollection/color_collections_standard) * * Get all **custom** color collections with [ColorCollection](#!/ColorCollection/color_collections_custom) * * **Note**: Only an API user with the Admin role can call this endpoint. Unauthorized requests will return `Not Found` (404) errors. * * @param {String} fields Requested fields. * * GET /color_collections -> ByteArray */ @JvmOverloads fun all_color_collections( fields: String? = null ) : SDKResponse { return this.get<ByteArray>("/color_collections", mapOf("fields" to fields)) } /** * ### Create a custom color collection with the specified information * * Creates a new custom color collection object, returning the details, including the created id. * * **Update** an existing color collection with [Update Color Collection](#!/ColorCollection/update_color_collection) * * **Permanently delete** an existing custom color collection with [Delete Color Collection](#!/ColorCollection/delete_color_collection) * * **Note**: Only an API user with the Admin role can call this endpoint. Unauthorized requests will return `Not Found` (404) errors. * * @param {WriteColorCollection} body * * POST /color_collections -> ByteArray */ fun create_color_collection( body: WriteColorCollection ) : SDKResponse { return this.post<ByteArray>("/color_collections", mapOf(), body) } /** * ### Get an array of all existing **Custom** Color Collections * Get a **single** color collection by id with [ColorCollection](#!/ColorCollection/color_collection) * * Get all **standard** color collections with [ColorCollection](#!/ColorCollection/color_collections_standard) * * **Note**: Only an API user with the Admin role can call this endpoint. Unauthorized requests will return `Not Found` (404) errors. * * @param {String} fields Requested fields. * * GET /color_collections/custom -> ByteArray */ @JvmOverloads fun color_collections_custom( fields: String? = null ) : SDKResponse { return this.get<ByteArray>("/color_collections/custom", mapOf("fields" to fields)) } /** * ### Get an array of all existing **Standard** Color Collections * Get a **single** color collection by id with [ColorCollection](#!/ColorCollection/color_collection) * * Get all **custom** color collections with [ColorCollection](#!/ColorCollection/color_collections_custom) * * **Note**: Only an API user with the Admin role can call this endpoint. Unauthorized requests will return `Not Found` (404) errors. * * @param {String} fields Requested fields. * * GET /color_collections/standard -> ByteArray */ @JvmOverloads fun color_collections_standard( fields: String? = null ) : SDKResponse { return this.get<ByteArray>("/color_collections/standard", mapOf("fields" to fields)) } /** * ### Get the default color collection * * Use this to retrieve the default Color Collection. * * Set the default color collection with [ColorCollection](#!/ColorCollection/set_default_color_collection) * * GET /color_collections/default -> ByteArray */ fun default_color_collection( ) : SDKResponse { return this.get<ByteArray>("/color_collections/default", mapOf()) } /** * ### Set the global default Color Collection by ID * * Returns the new specified default Color Collection object. * **Note**: Only an API user with the Admin role can call this endpoint. Unauthorized requests will return `Not Found` (404) errors. * * @param {String} collection_id ID of color collection to set as default * * PUT /color_collections/default -> ByteArray */ fun set_default_color_collection( collection_id: String ) : SDKResponse { return this.put<ByteArray>("/color_collections/default", mapOf("collection_id" to collection_id)) } /** * ### Get a Color Collection by ID * * Use this to retrieve a specific Color Collection. * Get a **single** color collection by id with [ColorCollection](#!/ColorCollection/color_collection) * * Get all **standard** color collections with [ColorCollection](#!/ColorCollection/color_collections_standard) * * Get all **custom** color collections with [ColorCollection](#!/ColorCollection/color_collections_custom) * * **Note**: Only an API user with the Admin role can call this endpoint. Unauthorized requests will return `Not Found` (404) errors. * * @param {String} collection_id Id of Color Collection * @param {String} fields Requested fields. * * GET /color_collections/{collection_id} -> ByteArray */ @JvmOverloads fun color_collection( collection_id: String, fields: String? = null ) : SDKResponse { val path_collection_id = encodeParam(collection_id) return this.get<ByteArray>("/color_collections/${path_collection_id}", mapOf("fields" to fields)) } /** * ### Update a custom color collection by id. * **Note**: Only an API user with the Admin role can call this endpoint. Unauthorized requests will return `Not Found` (404) errors. * * @param {String} collection_id Id of Custom Color Collection * @param {WriteColorCollection} body * * PATCH /color_collections/{collection_id} -> ByteArray */ fun update_color_collection( collection_id: String, body: WriteColorCollection ) : SDKResponse { val path_collection_id = encodeParam(collection_id) return this.patch<ByteArray>("/color_collections/${path_collection_id}", mapOf(), body) } /** * ### Delete a custom color collection by id * * This operation permanently deletes the identified **Custom** color collection. * * **Standard** color collections cannot be deleted * * Because multiple color collections can have the same label, they must be deleted by ID, not name. * **Note**: Only an API user with the Admin role can call this endpoint. Unauthorized requests will return `Not Found` (404) errors. * * @param {String} collection_id Id of Color Collection * * DELETE /color_collections/{collection_id} -> ByteArray */ fun delete_color_collection( collection_id: String ) : SDKResponse { val path_collection_id = encodeParam(collection_id) return this.delete<ByteArray>("/color_collections/${path_collection_id}", mapOf()) } //endregion ColorCollection: Manage Color Collections //region Config: Manage General Configuration /** * Get the current Cloud Storage Configuration. * * GET /cloud_storage -> ByteArray */ fun cloud_storage_configuration( ) : SDKResponse { return this.get<ByteArray>("/cloud_storage", mapOf()) } /** * Update the current Cloud Storage Configuration. * * @param {WriteBackupConfiguration} body * * PATCH /cloud_storage -> ByteArray */ fun update_cloud_storage_configuration( body: WriteBackupConfiguration ) : SDKResponse { return this.patch<ByteArray>("/cloud_storage", mapOf(), body) } /** * ### Looker Configuration Refresh * * This is an endpoint for manually calling refresh on Configuration manager. * * PUT /configuration_force_refresh -> ByteArray */ fun configuration_force_refresh( ) : SDKResponse { return this.put<ByteArray>("/configuration_force_refresh", mapOf()) } /** * ### Get the current status and content of custom welcome emails * * GET /custom_welcome_email -> ByteArray */ @Deprecated(message = "Deprecated method") fun custom_welcome_email( ) : SDKResponse { return this.get<ByteArray>("/custom_welcome_email", mapOf()) } /** * Update custom welcome email setting and values. Optionally send a test email with the new content to the currently logged in user. * * @param {CustomWelcomeEmail} body * @param {Boolean} send_test_welcome_email If true a test email with the content from the request will be sent to the current user after saving * * PATCH /custom_welcome_email -> ByteArray */ @Deprecated(message = "Deprecated method") @JvmOverloads fun update_custom_welcome_email( body: CustomWelcomeEmail, send_test_welcome_email: Boolean? = null ) : SDKResponse { return this.patch<ByteArray>("/custom_welcome_email", mapOf("send_test_welcome_email" to send_test_welcome_email), body) } /** * Requests to this endpoint will send a welcome email with the custom content provided in the body to the currently logged in user. * * @param {WelcomeEmailTest} body * * PUT /custom_welcome_email_test -> ByteArray */ fun update_custom_welcome_email_test( body: WelcomeEmailTest ) : SDKResponse { return this.put<ByteArray>("/custom_welcome_email_test", mapOf(), body) } /** * ### Retrieve the value for whether or not digest emails is enabled * * GET /digest_emails_enabled -> ByteArray */ fun digest_emails_enabled( ) : SDKResponse { return this.get<ByteArray>("/digest_emails_enabled", mapOf()) } /** * ### Update the setting for enabling/disabling digest emails * * @param {DigestEmails} body * * PATCH /digest_emails_enabled -> ByteArray */ fun update_digest_emails_enabled( body: DigestEmails ) : SDKResponse { return this.patch<ByteArray>("/digest_emails_enabled", mapOf(), body) } /** * ### Trigger the generation of digest email records and send them to Looker's internal system. This does not send * any actual emails, it generates records containing content which may be of interest for users who have become inactive. * Emails will be sent at a later time from Looker's internal system if the Digest Emails feature is enabled in settings. * * POST /digest_email_send -> ByteArray */ fun create_digest_email_send( ) : SDKResponse { return this.post<ByteArray>("/digest_email_send", mapOf()) } /** * ### Get Egress IP Addresses * * Returns the list of public egress IP Addresses for a hosted customer's instance * * GET /public_egress_ip_addresses -> ByteArray */ fun public_egress_ip_addresses( ) : SDKResponse { return this.get<ByteArray>("/public_egress_ip_addresses", mapOf()) } /** * ### Set the menu item name and content for internal help resources * * GET /internal_help_resources_content -> ByteArray */ fun internal_help_resources_content( ) : SDKResponse { return this.get<ByteArray>("/internal_help_resources_content", mapOf()) } /** * Update internal help resources content * * @param {WriteInternalHelpResourcesContent} body * * PATCH /internal_help_resources_content -> ByteArray */ fun update_internal_help_resources_content( body: WriteInternalHelpResourcesContent ) : SDKResponse { return this.patch<ByteArray>("/internal_help_resources_content", mapOf(), body) } /** * ### Get and set the options for internal help resources * * GET /internal_help_resources_enabled -> ByteArray */ fun internal_help_resources( ) : SDKResponse { return this.get<ByteArray>("/internal_help_resources_enabled", mapOf()) } /** * Update internal help resources settings * * @param {WriteInternalHelpResources} body * * PATCH /internal_help_resources -> ByteArray */ fun update_internal_help_resources( body: WriteInternalHelpResources ) : SDKResponse { return this.patch<ByteArray>("/internal_help_resources", mapOf(), body) } /** * ### Get all legacy features. * * GET /legacy_features -> ByteArray */ fun all_legacy_features( ) : SDKResponse { return this.get<ByteArray>("/legacy_features", mapOf()) } /** * ### Get information about the legacy feature with a specific id. * * @param {String} legacy_feature_id id of legacy feature * * GET /legacy_features/{legacy_feature_id} -> ByteArray */ fun legacy_feature( legacy_feature_id: String ) : SDKResponse { val path_legacy_feature_id = encodeParam(legacy_feature_id) return this.get<ByteArray>("/legacy_features/${path_legacy_feature_id}", mapOf()) } /** * ### Update information about the legacy feature with a specific id. * * @param {String} legacy_feature_id id of legacy feature * @param {WriteLegacyFeature} body * * PATCH /legacy_features/{legacy_feature_id} -> ByteArray */ fun update_legacy_feature( legacy_feature_id: String, body: WriteLegacyFeature ) : SDKResponse { val path_legacy_feature_id = encodeParam(legacy_feature_id) return this.patch<ByteArray>("/legacy_features/${path_legacy_feature_id}", mapOf(), body) } /** * ### Get a list of locales that Looker supports. * * GET /locales -> ByteArray */ fun all_locales( ) : SDKResponse { return this.get<ByteArray>("/locales", mapOf()) } /** * ### Get all mobile settings. * * GET /mobile/settings -> ByteArray */ fun mobile_settings( ) : SDKResponse { return this.get<ByteArray>("/mobile/settings", mapOf()) } /** * ### Get Looker Settings * * Available settings are: * - allow_user_timezones * - custom_welcome_email * - data_connector_default_enabled * - extension_framework_enabled * - extension_load_url_enabled * - marketplace_auto_install_enabled * - marketplace_enabled * - onboarding_enabled * - privatelabel_configuration * - timezone * * @param {String} fields Requested fields * * GET /setting -> ByteArray */ @JvmOverloads fun get_setting( fields: String? = null ) : SDKResponse { return this.get<ByteArray>("/setting", mapOf("fields" to fields)) } /** * ### Configure Looker Settings * * Available settings are: * - allow_user_timezones * - custom_welcome_email * - data_connector_default_enabled * - extension_framework_enabled * - extension_load_url_enabled * - marketplace_auto_install_enabled * - marketplace_enabled * - onboarding_enabled * - privatelabel_configuration * - timezone * * See the `Setting` type for more information on the specific values that can be configured. * * @param {WriteSetting} body * @param {String} fields Requested fields * * PATCH /setting -> ByteArray */ @JvmOverloads fun set_setting( body: WriteSetting, fields: String? = null ) : SDKResponse { return this.patch<ByteArray>("/setting", mapOf("fields" to fields), body) } /** * ### Configure SMTP Settings * This API allows users to configure the SMTP settings on the Looker instance. * This API is only supported in the OEM jar. Additionally, only admin users are authorised to call this API. * * @param {SmtpSettings} body * * POST /smtp_settings -> ByteArray */ fun set_smtp_settings( body: SmtpSettings ) : SDKResponse { return this.post<ByteArray>("/smtp_settings", mapOf(), body) } /** * ### Get current SMTP status. * * @param {String} fields Include only these fields in the response * * GET /smtp_status -> ByteArray */ @JvmOverloads fun smtp_status( fields: String? = null ) : SDKResponse { return this.get<ByteArray>("/smtp_status", mapOf("fields" to fields)) } /** * ### Get a list of timezones that Looker supports (e.g. useful for scheduling tasks). * * GET /timezones -> ByteArray */ fun all_timezones( ) : SDKResponse { return this.get<ByteArray>("/timezones", mapOf()) } /** * ### Get information about all API versions supported by this Looker instance. * * @param {String} fields Requested fields. * * GET /versions -> ByteArray */ @JvmOverloads fun versions( fields: String? = null ) : SDKResponse { return this.get<ByteArray>("/versions", mapOf("fields" to fields)) } /** * ### Get an API specification for this Looker instance. * * The specification is returned as a JSON document in Swagger 2.x format * * @param {String} api_version API version * @param {String} specification Specification name. Typically, this is "swagger.json" * * GET /api_spec/{api_version}/{specification} -> ByteArray */ fun api_spec( api_version: String, specification: String ) : SDKResponse { val path_api_version = encodeParam(api_version) val path_specification = encodeParam(specification) return this.get<ByteArray>("/api_spec/${path_api_version}/${path_specification}", mapOf()) } /** * ### This feature is enabled only by special license. * ### Gets the whitelabel configuration, which includes hiding documentation links, custom favicon uploading, etc. * * @param {String} fields Requested fields. * * GET /whitelabel_configuration -> ByteArray */ @Deprecated(message = "Deprecated method") @JvmOverloads fun whitelabel_configuration( fields: String? = null ) : SDKResponse { return this.get<ByteArray>("/whitelabel_configuration", mapOf("fields" to fields)) } /** * ### Update the whitelabel configuration * * @param {WriteWhitelabelConfiguration} body * * PUT /whitelabel_configuration -> ByteArray */ @Deprecated(message = "Deprecated method") fun update_whitelabel_configuration( body: WriteWhitelabelConfiguration ) : SDKResponse { return this.put<ByteArray>("/whitelabel_configuration", mapOf(), body) } //endregion Config: Manage General Configuration //region Connection: Manage Database Connections /** * ### Get information about all connections. * * @param {String} fields Requested fields. * * GET /connections -> ByteArray */ @JvmOverloads fun all_connections( fields: String? = null ) : SDKResponse { return this.get<ByteArray>("/connections", mapOf("fields" to fields)) } /** * ### Create a connection using the specified configuration. * * @param {WriteDBConnection} body * * POST /connections -> ByteArray */ fun create_connection( body: WriteDBConnection ) : SDKResponse { return this.post<ByteArray>("/connections", mapOf(), body) } /** * ### Get information about a connection. * * @param {String} connection_name Name of connection * @param {String} fields Requested fields. * * GET /connections/{connection_name} -> ByteArray */ @JvmOverloads fun connection( connection_name: String, fields: String? = null ) : SDKResponse { val path_connection_name = encodeParam(connection_name) return this.get<ByteArray>("/connections/${path_connection_name}", mapOf("fields" to fields)) } /** * ### Update a connection using the specified configuration. * * @param {String} connection_name Name of connection * @param {WriteDBConnection} body * * PATCH /connections/{connection_name} -> ByteArray */ fun update_connection( connection_name: String, body: WriteDBConnection ) : SDKResponse { val path_connection_name = encodeParam(connection_name) return this.patch<ByteArray>("/connections/${path_connection_name}", mapOf(), body) } /** * ### Delete a connection. * * @param {String} connection_name Name of connection * * DELETE /connections/{connection_name} -> ByteArray */ fun delete_connection( connection_name: String ) : SDKResponse { val path_connection_name = encodeParam(connection_name) return this.delete<ByteArray>("/connections/${path_connection_name}", mapOf()) } /** * ### Delete a connection override. * * @param {String} connection_name Name of connection * @param {String} override_context Context of connection override * * DELETE /connections/{connection_name}/connection_override/{override_context} -> ByteArray */ fun delete_connection_override( connection_name: String, override_context: String ) : SDKResponse { val path_connection_name = encodeParam(connection_name) val path_override_context = encodeParam(override_context) return this.delete<ByteArray>("/connections/${path_connection_name}/connection_override/${path_override_context}", mapOf()) } /** * ### Test an existing connection. * * Note that a connection's 'dialect' property has a 'connection_tests' property that lists the * specific types of tests that the connection supports. * * This API is rate limited. * * Unsupported tests in the request will be ignored. * * @param {String} connection_name Name of connection * @param {DelimArray<String>} tests Array of names of tests to run * * PUT /connections/{connection_name}/test -> ByteArray */ @JvmOverloads fun test_connection( connection_name: String, tests: DelimArray<String>? = null ) : SDKResponse { val path_connection_name = encodeParam(connection_name) return this.put<ByteArray>("/connections/${path_connection_name}/test", mapOf("tests" to tests)) } /** * ### Test a connection configuration. * * Note that a connection's 'dialect' property has a 'connection_tests' property that lists the * specific types of tests that the connection supports. * * This API is rate limited. * * Unsupported tests in the request will be ignored. * * @param {WriteDBConnection} body * @param {DelimArray<String>} tests Array of names of tests to run * * PUT /connections/test -> ByteArray */ @JvmOverloads fun test_connection_config( body: WriteDBConnection, tests: DelimArray<String>? = null ) : SDKResponse { return this.put<ByteArray>("/connections/test", mapOf("tests" to tests), body) } /** * ### Get information about all dialects. * * @param {String} fields Requested fields. * * GET /dialect_info -> ByteArray */ @JvmOverloads fun all_dialect_infos( fields: String? = null ) : SDKResponse { return this.get<ByteArray>("/dialect_info", mapOf("fields" to fields)) } /** * ### Get all External OAuth Applications. * * This is an OAuth Application which Looker uses to access external systems. * * @param {String} name Application name * @param {String} client_id Application Client ID * * GET /external_oauth_applications -> ByteArray */ @JvmOverloads fun all_external_oauth_applications( name: String? = null, client_id: String? = null ) : SDKResponse { return this.get<ByteArray>("/external_oauth_applications", mapOf("name" to name, "client_id" to client_id)) } /** * ### Create an OAuth Application using the specified configuration. * * This is an OAuth Application which Looker uses to access external systems. * * @param {WriteExternalOauthApplication} body * * POST /external_oauth_applications -> ByteArray */ fun create_external_oauth_application( body: WriteExternalOauthApplication ) : SDKResponse { return this.post<ByteArray>("/external_oauth_applications", mapOf(), body) } /** * ### Create OAuth User state. * * @param {CreateOAuthApplicationUserStateRequest} body * * POST /external_oauth_applications/user_state -> ByteArray */ fun create_oauth_application_user_state( body: CreateOAuthApplicationUserStateRequest ) : SDKResponse { return this.post<ByteArray>("/external_oauth_applications/user_state", mapOf(), body) } /** * ### Get information about all SSH Servers. * * @param {String} fields Requested fields. * * GET /ssh_servers -> ByteArray */ @JvmOverloads fun all_ssh_servers( fields: String? = null ) : SDKResponse { return this.get<ByteArray>("/ssh_servers", mapOf("fields" to fields)) } /** * ### Create an SSH Server. * * @param {WriteSshServer} body * * POST /ssh_servers -> ByteArray */ fun create_ssh_server( body: WriteSshServer ) : SDKResponse { return this.post<ByteArray>("/ssh_servers", mapOf(), body) } /** * ### Get information about an SSH Server. * * @param {String} ssh_server_id Id of SSH Server * * GET /ssh_server/{ssh_server_id} -> ByteArray */ fun ssh_server( ssh_server_id: String ) : SDKResponse { val path_ssh_server_id = encodeParam(ssh_server_id) return this.get<ByteArray>("/ssh_server/${path_ssh_server_id}", mapOf()) } /** * ### Update an SSH Server. * * @param {String} ssh_server_id Id of SSH Server * @param {WriteSshServer} body * * PATCH /ssh_server/{ssh_server_id} -> ByteArray */ fun update_ssh_server( ssh_server_id: String, body: WriteSshServer ) : SDKResponse { val path_ssh_server_id = encodeParam(ssh_server_id) return this.patch<ByteArray>("/ssh_server/${path_ssh_server_id}", mapOf(), body) } /** * ### Delete an SSH Server. * * @param {String} ssh_server_id Id of SSH Server * * DELETE /ssh_server/{ssh_server_id} -> ByteArray */ fun delete_ssh_server( ssh_server_id: String ) : SDKResponse { val path_ssh_server_id = encodeParam(ssh_server_id) return this.delete<ByteArray>("/ssh_server/${path_ssh_server_id}", mapOf()) } /** * ### Test the SSH Server * * @param {String} ssh_server_id Id of SSH Server * * GET /ssh_server/{ssh_server_id}/test -> ByteArray */ fun test_ssh_server( ssh_server_id: String ) : SDKResponse { val path_ssh_server_id = encodeParam(ssh_server_id) return this.get<ByteArray>("/ssh_server/${path_ssh_server_id}/test", mapOf()) } /** * ### Get information about all SSH Tunnels. * * @param {String} fields Requested fields. * * GET /ssh_tunnels -> ByteArray */ @JvmOverloads fun all_ssh_tunnels( fields: String? = null ) : SDKResponse { return this.get<ByteArray>("/ssh_tunnels", mapOf("fields" to fields)) } /** * ### Create an SSH Tunnel * * @param {WriteSshTunnel} body * * POST /ssh_tunnels -> ByteArray */ fun create_ssh_tunnel( body: WriteSshTunnel ) : SDKResponse { return this.post<ByteArray>("/ssh_tunnels", mapOf(), body) } /** * ### Get information about an SSH Tunnel. * * @param {String} ssh_tunnel_id Id of SSH Tunnel * * GET /ssh_tunnel/{ssh_tunnel_id} -> ByteArray */ fun ssh_tunnel( ssh_tunnel_id: String ) : SDKResponse { val path_ssh_tunnel_id = encodeParam(ssh_tunnel_id) return this.get<ByteArray>("/ssh_tunnel/${path_ssh_tunnel_id}", mapOf()) } /** * ### Update an SSH Tunnel * * @param {String} ssh_tunnel_id Id of SSH Tunnel * @param {WriteSshTunnel} body * * PATCH /ssh_tunnel/{ssh_tunnel_id} -> ByteArray */ fun update_ssh_tunnel( ssh_tunnel_id: String, body: WriteSshTunnel ) : SDKResponse { val path_ssh_tunnel_id = encodeParam(ssh_tunnel_id) return this.patch<ByteArray>("/ssh_tunnel/${path_ssh_tunnel_id}", mapOf(), body) } /** * ### Delete an SSH Tunnel * * @param {String} ssh_tunnel_id Id of SSH Tunnel * * DELETE /ssh_tunnel/{ssh_tunnel_id} -> ByteArray */ fun delete_ssh_tunnel( ssh_tunnel_id: String ) : SDKResponse { val path_ssh_tunnel_id = encodeParam(ssh_tunnel_id) return this.delete<ByteArray>("/ssh_tunnel/${path_ssh_tunnel_id}", mapOf()) } /** * ### Test the SSH Tunnel * * @param {String} ssh_tunnel_id Id of SSH Tunnel * * GET /ssh_tunnel/{ssh_tunnel_id}/test -> ByteArray */ fun test_ssh_tunnel( ssh_tunnel_id: String ) : SDKResponse { val path_ssh_tunnel_id = encodeParam(ssh_tunnel_id) return this.get<ByteArray>("/ssh_tunnel/${path_ssh_tunnel_id}/test", mapOf()) } /** * ### Get the SSH public key * * Get the public key created for this instance to identify itself to a remote SSH server. * * GET /ssh_public_key -> ByteArray */ fun ssh_public_key( ) : SDKResponse { return this.get<ByteArray>("/ssh_public_key", mapOf()) } //endregion Connection: Manage Database Connections //region Content: Manage Content /** * ### Search Favorite Content * * If multiple search params are given and `filter_or` is FALSE or not specified, * search params are combined in a logical AND operation. * Only rows that match *all* search param criteria will be returned. * * If `filter_or` is TRUE, multiple search params are combined in a logical OR operation. * Results will include rows that match **any** of the search criteria. * * String search params use case-insensitive matching. * String search params can contain `%` and '_' as SQL LIKE pattern match wildcard expressions. * example="dan%" will match "danger" and "Danzig" but not "David" * example="D_m%" will match "Damage" and "dump" * * Integer search params can accept a single value or a comma separated list of values. The multiple * values will be combined under a logical OR operation - results will match at least one of * the given values. * * Most search params can accept "IS NULL" and "NOT NULL" as special expressions to match * or exclude (respectively) rows where the column is null. * * Boolean search params accept only "true" and "false" as values. * * @param {String} id Match content favorite id(s) * @param {String} user_id Match user id(s).To create a list of multiple ids, use commas as separators * @param {String} content_metadata_id Match content metadata id(s).To create a list of multiple ids, use commas as separators * @param {String} dashboard_id Match dashboard id(s).To create a list of multiple ids, use commas as separators * @param {String} look_id Match look id(s).To create a list of multiple ids, use commas as separators * @param {String} board_id Match board id(s).To create a list of multiple ids, use commas as separators * @param {Long} limit Number of results to return. (used with offset) * @param {Long} offset Number of results to skip before returning any. (used with limit) * @param {String} sorts Fields to sort by. * @param {String} fields Requested fields. * @param {Boolean} filter_or Combine given search criteria in a boolean OR expression * * GET /content_favorite/search -> ByteArray */ @JvmOverloads fun search_content_favorites( id: String? = null, user_id: String? = null, content_metadata_id: String? = null, dashboard_id: String? = null, look_id: String? = null, board_id: String? = null, limit: Long? = null, offset: Long? = null, sorts: String? = null, fields: String? = null, filter_or: Boolean? = null ) : SDKResponse { return this.get<ByteArray>("/content_favorite/search", mapOf("id" to id, "user_id" to user_id, "content_metadata_id" to content_metadata_id, "dashboard_id" to dashboard_id, "look_id" to look_id, "board_id" to board_id, "limit" to limit, "offset" to offset, "sorts" to sorts, "fields" to fields, "filter_or" to filter_or)) } /** * ### Get favorite content by its id * * @param {String} content_favorite_id Id of favorite content * @param {String} fields Requested fields. * * GET /content_favorite/{content_favorite_id} -> ByteArray */ @JvmOverloads fun content_favorite( content_favorite_id: String, fields: String? = null ) : SDKResponse { val path_content_favorite_id = encodeParam(content_favorite_id) return this.get<ByteArray>("/content_favorite/${path_content_favorite_id}", mapOf("fields" to fields)) } /** * ### Delete favorite content * * @param {String} content_favorite_id Id of favorite content * * DELETE /content_favorite/{content_favorite_id} -> ByteArray */ fun delete_content_favorite( content_favorite_id: String ) : SDKResponse { val path_content_favorite_id = encodeParam(content_favorite_id) return this.delete<ByteArray>("/content_favorite/${path_content_favorite_id}", mapOf()) } /** * ### Create favorite content * * @param {WriteContentFavorite} body * * POST /content_favorite -> ByteArray */ fun create_content_favorite( body: WriteContentFavorite ) : SDKResponse { return this.post<ByteArray>("/content_favorite", mapOf(), body) } /** * ### Get information about all content metadata in a space. * * @param {String} parent_id Parent space of content. * @param {String} fields Requested fields. * * GET /content_metadata -> ByteArray */ @JvmOverloads fun all_content_metadatas( parent_id: String, fields: String? = null ) : SDKResponse { return this.get<ByteArray>("/content_metadata", mapOf("parent_id" to parent_id, "fields" to fields)) } /** * ### Get information about an individual content metadata record. * * @param {String} content_metadata_id Id of content metadata * @param {String} fields Requested fields. * * GET /content_metadata/{content_metadata_id} -> ByteArray */ @JvmOverloads fun content_metadata( content_metadata_id: String, fields: String? = null ) : SDKResponse { val path_content_metadata_id = encodeParam(content_metadata_id) return this.get<ByteArray>("/content_metadata/${path_content_metadata_id}", mapOf("fields" to fields)) } /** * ### Move a piece of content. * * @param {String} content_metadata_id Id of content metadata * @param {WriteContentMeta} body * * PATCH /content_metadata/{content_metadata_id} -> ByteArray */ fun update_content_metadata( content_metadata_id: String, body: WriteContentMeta ) : SDKResponse { val path_content_metadata_id = encodeParam(content_metadata_id) return this.patch<ByteArray>("/content_metadata/${path_content_metadata_id}", mapOf(), body) } /** * ### All content metadata access records for a content metadata item. * * @param {String} content_metadata_id Id of content metadata * @param {String} fields Requested fields. * * GET /content_metadata_access -> ByteArray */ @JvmOverloads fun all_content_metadata_accesses( content_metadata_id: String, fields: String? = null ) : SDKResponse { return this.get<ByteArray>("/content_metadata_access", mapOf("content_metadata_id" to content_metadata_id, "fields" to fields)) } /** * ### Create content metadata access. * * @param {ContentMetaGroupUser} body WARNING: no writeable properties found for POST, PUT, or PATCH * @param {Boolean} send_boards_notification_email Optionally sends notification email when granting access to a board. * * POST /content_metadata_access -> ByteArray */ @JvmOverloads fun create_content_metadata_access( body: ContentMetaGroupUser, send_boards_notification_email: Boolean? = null ) : SDKResponse { return this.post<ByteArray>("/content_metadata_access", mapOf("send_boards_notification_email" to send_boards_notification_email), body) } /** * ### Update type of access for content metadata. * * @param {String} content_metadata_access_id Id of content metadata access * @param {ContentMetaGroupUser} body WARNING: no writeable properties found for POST, PUT, or PATCH * * PUT /content_metadata_access/{content_metadata_access_id} -> ByteArray */ fun update_content_metadata_access( content_metadata_access_id: String, body: ContentMetaGroupUser ) : SDKResponse { val path_content_metadata_access_id = encodeParam(content_metadata_access_id) return this.put<ByteArray>("/content_metadata_access/${path_content_metadata_access_id}", mapOf(), body) } /** * ### Remove content metadata access. * * @param {String} content_metadata_access_id Id of content metadata access * * DELETE /content_metadata_access/{content_metadata_access_id} -> ByteArray */ fun delete_content_metadata_access( content_metadata_access_id: String ) : SDKResponse { val path_content_metadata_access_id = encodeParam(content_metadata_access_id) return this.delete<ByteArray>("/content_metadata_access/${path_content_metadata_access_id}", mapOf()) } /** * ### Get an image representing the contents of a dashboard or look. * * The returned thumbnail is an abstract representation of the contents of a dashbord or look and does not * reflect the actual data displayed in the respective visualizations. * * @param {String} type Either dashboard or look * @param {String} resource_id ID of the dashboard or look to render * @param {String} reload Whether or not to refresh the rendered image with the latest content * @param {String} format A value of png produces a thumbnail in PNG format instead of SVG (default) * @param {Long} width The width of the image if format is supplied * @param {Long} height The height of the image if format is supplied * * GET /content_thumbnail/{type}/{resource_id} -> ByteArray * * **Note**: Binary content may be returned by this method. */ @JvmOverloads fun content_thumbnail( type: String, resource_id: String, reload: String? = null, format: String? = null, width: Long? = null, height: Long? = null ) : SDKResponse { val path_type = encodeParam(type) val path_resource_id = encodeParam(resource_id) return this.get<ByteArray>("/content_thumbnail/${path_type}/${path_resource_id}", mapOf("reload" to reload, "format" to format, "width" to width, "height" to height)) } /** * ### Validate All Content * * Performs validation of all looks and dashboards * Returns a list of errors found as well as metadata about the content validation run. * * @param {String} fields Requested fields. * * GET /content_validation -> ByteArray */ @JvmOverloads fun content_validation( fields: String? = null ) : SDKResponse { return this.get<ByteArray>("/content_validation", mapOf("fields" to fields)) } /** * ### Search Content Views * * If multiple search params are given and `filter_or` is FALSE or not specified, * search params are combined in a logical AND operation. * Only rows that match *all* search param criteria will be returned. * * If `filter_or` is TRUE, multiple search params are combined in a logical OR operation. * Results will include rows that match **any** of the search criteria. * * String search params use case-insensitive matching. * String search params can contain `%` and '_' as SQL LIKE pattern match wildcard expressions. * example="dan%" will match "danger" and "Danzig" but not "David" * example="D_m%" will match "Damage" and "dump" * * Integer search params can accept a single value or a comma separated list of values. The multiple * values will be combined under a logical OR operation - results will match at least one of * the given values. * * Most search params can accept "IS NULL" and "NOT NULL" as special expressions to match * or exclude (respectively) rows where the column is null. * * Boolean search params accept only "true" and "false" as values. * * @param {String} view_count Match view count * @param {String} group_id Match Group Id * @param {String} look_id Match look_id * @param {String} dashboard_id Match dashboard_id * @param {String} content_metadata_id Match content metadata id * @param {String} start_of_week_date Match start of week date (format is "YYYY-MM-DD") * @param {Boolean} all_time True if only all time view records should be returned * @param {String} user_id Match user id * @param {String} fields Requested fields * @param {Long} limit Number of results to return. Use with `offset` to manage pagination of results * @param {Long} offset Number of results to skip before returning data * @param {String} sorts Fields to sort by * @param {Boolean} filter_or Combine given search criteria in a boolean OR expression * * GET /content_view/search -> ByteArray */ @JvmOverloads fun search_content_views( view_count: String? = null, group_id: String? = null, look_id: String? = null, dashboard_id: String? = null, content_metadata_id: String? = null, start_of_week_date: String? = null, all_time: Boolean? = null, user_id: String? = null, fields: String? = null, limit: Long? = null, offset: Long? = null, sorts: String? = null, filter_or: Boolean? = null ) : SDKResponse { return this.get<ByteArray>("/content_view/search", mapOf("view_count" to view_count, "group_id" to group_id, "look_id" to look_id, "dashboard_id" to dashboard_id, "content_metadata_id" to content_metadata_id, "start_of_week_date" to start_of_week_date, "all_time" to all_time, "user_id" to user_id, "fields" to fields, "limit" to limit, "offset" to offset, "sorts" to sorts, "filter_or" to filter_or)) } /** * ### Get a vector image representing the contents of a dashboard or look. * * # DEPRECATED: Use [content_thumbnail()](#!/Content/content_thumbnail) * * The returned thumbnail is an abstract representation of the contents of a dashbord or look and does not * reflect the actual data displayed in the respective visualizations. * * @param {String} type Either dashboard or look * @param {String} resource_id ID of the dashboard or look to render * @param {String} reload Whether or not to refresh the rendered image with the latest content * * GET /vector_thumbnail/{type}/{resource_id} -> ByteArray */ @Deprecated(message = "Deprecated method") @JvmOverloads fun vector_thumbnail( type: String, resource_id: String, reload: String? = null ) : SDKResponse { val path_type = encodeParam(type) val path_resource_id = encodeParam(resource_id) return this.get<ByteArray>("/vector_thumbnail/${path_type}/${path_resource_id}", mapOf("reload" to reload)) } //endregion Content: Manage Content //region Dashboard: Manage Dashboards /** * ### Get information about all active dashboards. * * Returns an array of **abbreviated dashboard objects**. Dashboards marked as deleted are excluded from this list. * * Get the **full details** of a specific dashboard by id with [dashboard()](#!/Dashboard/dashboard) * * Find **deleted dashboards** with [search_dashboards()](#!/Dashboard/search_dashboards) * * @param {String} fields Requested fields. * * GET /dashboards -> ByteArray */ @JvmOverloads fun all_dashboards( fields: String? = null ) : SDKResponse { return this.get<ByteArray>("/dashboards", mapOf("fields" to fields)) } /** * ### Create a new dashboard * * Creates a new dashboard object and returns the details of the newly created dashboard. * * `Title` and `space_id` are required fields. * `Space_id` must contain the id of an existing space. * A dashboard's `title` must be unique within the space in which it resides. * * If you receive a 422 error response when creating a dashboard, be sure to look at the * response body for information about exactly which fields are missing or contain invalid data. * * You can **update** an existing dashboard with [update_dashboard()](#!/Dashboard/update_dashboard) * * You can **permanently delete** an existing dashboard with [delete_dashboard()](#!/Dashboard/delete_dashboard) * * @param {WriteDashboard} body * * POST /dashboards -> ByteArray */ fun create_dashboard( body: WriteDashboard ) : SDKResponse { return this.post<ByteArray>("/dashboards", mapOf(), body) } /** * ### Search Dashboards * * Returns an **array of dashboard objects** that match the specified search criteria. * * If multiple search params are given and `filter_or` is FALSE or not specified, * search params are combined in a logical AND operation. * Only rows that match *all* search param criteria will be returned. * * If `filter_or` is TRUE, multiple search params are combined in a logical OR operation. * Results will include rows that match **any** of the search criteria. * * String search params use case-insensitive matching. * String search params can contain `%` and '_' as SQL LIKE pattern match wildcard expressions. * example="dan%" will match "danger" and "Danzig" but not "David" * example="D_m%" will match "Damage" and "dump" * * Integer search params can accept a single value or a comma separated list of values. The multiple * values will be combined under a logical OR operation - results will match at least one of * the given values. * * Most search params can accept "IS NULL" and "NOT NULL" as special expressions to match * or exclude (respectively) rows where the column is null. * * Boolean search params accept only "true" and "false" as values. * * * The parameters `limit`, and `offset` are recommended for fetching results in page-size chunks. * * Get a **single dashboard** by id with [dashboard()](#!/Dashboard/dashboard) * * @param {String} id Match dashboard id. * @param {String} slug Match dashboard slug. * @param {String} title Match Dashboard title. * @param {String} description Match Dashboard description. * @param {String} content_favorite_id Filter on a content favorite id. * @param {String} folder_id Filter on a particular space. * @param {String} deleted Filter on dashboards deleted status. * @param {String} user_id Filter on dashboards created by a particular user. * @param {String} view_count Filter on a particular value of view_count * @param {String} content_metadata_id Filter on a content favorite id. * @param {Boolean} curate Exclude items that exist only in personal spaces other than the users * @param {String} last_viewed_at Select dashboards based on when they were last viewed * @param {String} fields Requested fields. * @param {Long} page DEPRECATED. Use limit and offset instead. Return only page N of paginated results * @param {Long} per_page DEPRECATED. Use limit and offset instead. Return N rows of data per page * @param {Long} limit Number of results to return. (used with offset and takes priority over page and per_page) * @param {Long} offset Number of results to skip before returning any. (used with limit and takes priority over page and per_page) * @param {String} sorts One or more fields to sort by. Sortable fields: [:title, :user_id, :id, :created_at, :space_id, :folder_id, :description, :view_count, :favorite_count, :slug, :content_favorite_id, :content_metadata_id, :deleted, :deleted_at, :last_viewed_at, :last_accessed_at] * @param {Boolean} filter_or Combine given search criteria in a boolean OR expression * * GET /dashboards/search -> ByteArray */ @JvmOverloads fun search_dashboards( id: String? = null, slug: String? = null, title: String? = null, description: String? = null, content_favorite_id: String? = null, folder_id: String? = null, deleted: String? = null, user_id: String? = null, view_count: String? = null, content_metadata_id: String? = null, curate: Boolean? = null, last_viewed_at: String? = null, fields: String? = null, page: Long? = null, per_page: Long? = null, limit: Long? = null, offset: Long? = null, sorts: String? = null, filter_or: Boolean? = null ) : SDKResponse { return this.get<ByteArray>("/dashboards/search", mapOf("id" to id, "slug" to slug, "title" to title, "description" to description, "content_favorite_id" to content_favorite_id, "folder_id" to folder_id, "deleted" to deleted, "user_id" to user_id, "view_count" to view_count, "content_metadata_id" to content_metadata_id, "curate" to curate, "last_viewed_at" to last_viewed_at, "fields" to fields, "page" to page, "per_page" to per_page, "limit" to limit, "offset" to offset, "sorts" to sorts, "filter_or" to filter_or)) } /** * ### Import a LookML dashboard to a space as a UDD * Creates a UDD (a dashboard which exists in the Looker database rather than as a LookML file) from the LookML dashboard * and places it in the space specified. The created UDD will have a lookml_link_id which links to the original LookML dashboard. * * To give the imported dashboard specify a (e.g. title: "my title") in the body of your request, otherwise the imported * dashboard will have the same title as the original LookML dashboard. * * For this operation to succeed the user must have permission to see the LookML dashboard in question, and have permission to * create content in the space the dashboard is being imported to. * * **Sync** a linked UDD with [sync_lookml_dashboard()](#!/Dashboard/sync_lookml_dashboard) * **Unlink** a linked UDD by setting lookml_link_id to null with [update_dashboard()](#!/Dashboard/update_dashboard) * * @param {String} lookml_dashboard_id Id of LookML dashboard * @param {String} space_id Id of space to import the dashboard to * @param {WriteDashboard} body * @param {Boolean} raw_locale If true, and this dashboard is localized, export it with the raw keys, not localized. * * POST /dashboards/{lookml_dashboard_id}/import/{space_id} -> ByteArray */ @JvmOverloads fun import_lookml_dashboard( lookml_dashboard_id: String, space_id: String, body: WriteDashboard? = null, raw_locale: Boolean? = null ) : SDKResponse { val path_lookml_dashboard_id = encodeParam(lookml_dashboard_id) val path_space_id = encodeParam(space_id) return this.post<ByteArray>("/dashboards/${path_lookml_dashboard_id}/import/${path_space_id}", mapOf("raw_locale" to raw_locale), body) } /** * ### Update all linked dashboards to match the specified LookML dashboard. * * Any UDD (a dashboard which exists in the Looker database rather than as a LookML file) which has a `lookml_link_id` * property value referring to a LookML dashboard's id (model::dashboardname) will be updated so that it matches the current state of the LookML dashboard. * * For this operation to succeed the user must have permission to view the LookML dashboard, and only linked dashboards * that the user has permission to update will be synced. * * To **link** or **unlink** a UDD set the `lookml_link_id` property with [update_dashboard()](#!/Dashboard/update_dashboard) * * @param {String} lookml_dashboard_id Id of LookML dashboard, in the form 'model::dashboardname' * @param {WriteDashboard} body * @param {Boolean} raw_locale If true, and this dashboard is localized, export it with the raw keys, not localized. * * PATCH /dashboards/{lookml_dashboard_id}/sync -> ByteArray */ @JvmOverloads fun sync_lookml_dashboard( lookml_dashboard_id: String, body: WriteDashboard, raw_locale: Boolean? = null ) : SDKResponse { val path_lookml_dashboard_id = encodeParam(lookml_dashboard_id) return this.patch<ByteArray>("/dashboards/${path_lookml_dashboard_id}/sync", mapOf("raw_locale" to raw_locale), body) } /** * ### Get information about a dashboard * * Returns the full details of the identified dashboard object * * Get a **summary list** of all active dashboards with [all_dashboards()](#!/Dashboard/all_dashboards) * * You can **Search** for dashboards with [search_dashboards()](#!/Dashboard/search_dashboards) * * @param {String} dashboard_id Id of dashboard * @param {String} fields Requested fields. * * GET /dashboards/{dashboard_id} -> ByteArray */ @JvmOverloads fun dashboard( dashboard_id: String, fields: String? = null ) : SDKResponse { val path_dashboard_id = encodeParam(dashboard_id) return this.get<ByteArray>("/dashboards/${path_dashboard_id}", mapOf("fields" to fields)) } /** * ### Update a dashboard * * You can use this function to change the string and integer properties of * a dashboard. Nested objects such as filters, dashboard elements, or dashboard layout components * cannot be modified by this function - use the update functions for the respective * nested object types (like [update_dashboard_filter()](#!/3.1/Dashboard/update_dashboard_filter) to change a filter) * to modify nested objects referenced by a dashboard. * * If you receive a 422 error response when updating a dashboard, be sure to look at the * response body for information about exactly which fields are missing or contain invalid data. * * @param {String} dashboard_id Id of dashboard * @param {WriteDashboard} body * * PATCH /dashboards/{dashboard_id} -> ByteArray */ fun update_dashboard( dashboard_id: String, body: WriteDashboard ) : SDKResponse { val path_dashboard_id = encodeParam(dashboard_id) return this.patch<ByteArray>("/dashboards/${path_dashboard_id}", mapOf(), body) } /** * ### Delete the dashboard with the specified id * * Permanently **deletes** a dashboard. (The dashboard cannot be recovered after this operation.) * * "Soft" delete or hide a dashboard by setting its `deleted` status to `True` with [update_dashboard()](#!/Dashboard/update_dashboard). * * Note: When a dashboard is deleted in the UI, it is soft deleted. Use this API call to permanently remove it, if desired. * * @param {String} dashboard_id Id of dashboard * * DELETE /dashboards/{dashboard_id} -> ByteArray */ fun delete_dashboard( dashboard_id: String ) : SDKResponse { val path_dashboard_id = encodeParam(dashboard_id) return this.delete<ByteArray>("/dashboards/${path_dashboard_id}", mapOf()) } /** * ### Get Aggregate Table LookML for Each Query on a Dahboard * * Returns a JSON object that contains the dashboard id and Aggregate Table lookml * * @param {String} dashboard_id Id of dashboard * * GET /dashboards/aggregate_table_lookml/{dashboard_id} -> ByteArray */ fun dashboard_aggregate_table_lookml( dashboard_id: String ) : SDKResponse { val path_dashboard_id = encodeParam(dashboard_id) return this.get<ByteArray>("/dashboards/aggregate_table_lookml/${path_dashboard_id}", mapOf()) } /** * ### Get lookml of a UDD * * Returns a JSON object that contains the dashboard id and the full lookml * * @param {String} dashboard_id Id of dashboard * * GET /dashboards/lookml/{dashboard_id} -> ByteArray */ fun dashboard_lookml( dashboard_id: String ) : SDKResponse { val path_dashboard_id = encodeParam(dashboard_id) return this.get<ByteArray>("/dashboards/lookml/${path_dashboard_id}", mapOf()) } /** * ### Move an existing dashboard * * Moves a dashboard to a specified folder, and returns the moved dashboard. * * `dashboard_id` and `folder_id` are required. * `dashboard_id` and `folder_id` must already exist, and `folder_id` must be different from the current `folder_id` of the dashboard. * * @param {String} dashboard_id Dashboard id to move. * @param {String} folder_id Folder id to move to. * * PATCH /dashboards/{dashboard_id}/move -> ByteArray */ fun move_dashboard( dashboard_id: String, folder_id: String ) : SDKResponse { val path_dashboard_id = encodeParam(dashboard_id) return this.patch<ByteArray>("/dashboards/${path_dashboard_id}/move", mapOf("folder_id" to folder_id)) } /** * ### Creates a dashboard object based on LookML Dashboard YAML, and returns the details of the newly created dashboard. * * If a dashboard exists with the YAML-defined "preferred_slug", the new dashboard will overwrite it. Otherwise, a new * dashboard will be created. Note that when a dashboard is overwritten, alerts will not be maintained. * * If a folder_id is specified: new dashboards will be placed in that folder, and overwritten dashboards will be moved to it * If the folder_id isn't specified: new dashboards will be placed in the caller's personal folder, and overwritten dashboards * will remain where they were * * LookML must contain valid LookML YAML code. It's recommended to use the LookML format returned * from [dashboard_lookml()](#!/Dashboard/dashboard_lookml) as the input LookML (newlines replaced with * ). * * Note that the created dashboard is not linked to any LookML Dashboard, * i.e. [sync_lookml_dashboard()](#!/Dashboard/sync_lookml_dashboard) will not update dashboards created by this method. * * @param {WriteDashboardLookml} body * * POST /dashboards/lookml -> ByteArray */ fun import_dashboard_from_lookml( body: WriteDashboardLookml ) : SDKResponse { return this.post<ByteArray>("/dashboards/lookml", mapOf(), body) } /** * # DEPRECATED: Use [import_dashboard_from_lookml()](#!/Dashboard/import_dashboard_from_lookml) * * @param {WriteDashboardLookml} body * * POST /dashboards/from_lookml -> ByteArray */ fun create_dashboard_from_lookml( body: WriteDashboardLookml ) : SDKResponse { return this.post<ByteArray>("/dashboards/from_lookml", mapOf(), body) } /** * ### Copy an existing dashboard * * Creates a copy of an existing dashboard, in a specified folder, and returns the copied dashboard. * * `dashboard_id` is required, `dashboard_id` and `folder_id` must already exist if specified. * `folder_id` will default to the existing folder. * * If a dashboard with the same title already exists in the target folder, the copy will have '(copy)' * or '(copy <# of copies>)' appended. * * @param {String} dashboard_id Dashboard id to copy. * @param {String} folder_id Folder id to copy to. * * POST /dashboards/{dashboard_id}/copy -> ByteArray */ @JvmOverloads fun copy_dashboard( dashboard_id: String, folder_id: String? = null ) : SDKResponse { val path_dashboard_id = encodeParam(dashboard_id) return this.post<ByteArray>("/dashboards/${path_dashboard_id}/copy", mapOf("folder_id" to folder_id)) } /** * ### Search Dashboard Elements * * Returns an **array of DashboardElement objects** that match the specified search criteria. * * If multiple search params are given and `filter_or` is FALSE or not specified, * search params are combined in a logical AND operation. * Only rows that match *all* search param criteria will be returned. * * If `filter_or` is TRUE, multiple search params are combined in a logical OR operation. * Results will include rows that match **any** of the search criteria. * * String search params use case-insensitive matching. * String search params can contain `%` and '_' as SQL LIKE pattern match wildcard expressions. * example="dan%" will match "danger" and "Danzig" but not "David" * example="D_m%" will match "Damage" and "dump" * * Integer search params can accept a single value or a comma separated list of values. The multiple * values will be combined under a logical OR operation - results will match at least one of * the given values. * * Most search params can accept "IS NULL" and "NOT NULL" as special expressions to match * or exclude (respectively) rows where the column is null. * * Boolean search params accept only "true" and "false" as values. * * @param {String} dashboard_id Select elements that refer to a given dashboard id * @param {String} look_id Select elements that refer to a given look id * @param {String} title Match the title of element * @param {Boolean} deleted Select soft-deleted dashboard elements * @param {String} fields Requested fields. * @param {Boolean} filter_or Combine given search criteria in a boolean OR expression * @param {String} sorts Fields to sort by. Sortable fields: [:look_id, :dashboard_id, :deleted, :title] * * GET /dashboard_elements/search -> ByteArray */ @JvmOverloads fun search_dashboard_elements( dashboard_id: String? = null, look_id: String? = null, title: String? = null, deleted: Boolean? = null, fields: String? = null, filter_or: Boolean? = null, sorts: String? = null ) : SDKResponse { return this.get<ByteArray>("/dashboard_elements/search", mapOf("dashboard_id" to dashboard_id, "look_id" to look_id, "title" to title, "deleted" to deleted, "fields" to fields, "filter_or" to filter_or, "sorts" to sorts)) } /** * ### Get information about the dashboard element with a specific id. * * @param {String} dashboard_element_id Id of dashboard element * @param {String} fields Requested fields. * * GET /dashboard_elements/{dashboard_element_id} -> ByteArray */ @JvmOverloads fun dashboard_element( dashboard_element_id: String, fields: String? = null ) : SDKResponse { val path_dashboard_element_id = encodeParam(dashboard_element_id) return this.get<ByteArray>("/dashboard_elements/${path_dashboard_element_id}", mapOf("fields" to fields)) } /** * ### Update the dashboard element with a specific id. * * @param {String} dashboard_element_id Id of dashboard element * @param {WriteDashboardElement} body * @param {String} fields Requested fields. * * PATCH /dashboard_elements/{dashboard_element_id} -> ByteArray */ @JvmOverloads fun update_dashboard_element( dashboard_element_id: String, body: WriteDashboardElement, fields: String? = null ) : SDKResponse { val path_dashboard_element_id = encodeParam(dashboard_element_id) return this.patch<ByteArray>("/dashboard_elements/${path_dashboard_element_id}", mapOf("fields" to fields), body) } /** * ### Delete a dashboard element with a specific id. * * @param {String} dashboard_element_id Id of dashboard element * * DELETE /dashboard_elements/{dashboard_element_id} -> ByteArray */ fun delete_dashboard_element( dashboard_element_id: String ) : SDKResponse { val path_dashboard_element_id = encodeParam(dashboard_element_id) return this.delete<ByteArray>("/dashboard_elements/${path_dashboard_element_id}", mapOf()) } /** * ### Get information about all the dashboard elements on a dashboard with a specific id. * * @param {String} dashboard_id Id of dashboard * @param {String} fields Requested fields. * * GET /dashboards/{dashboard_id}/dashboard_elements -> ByteArray */ @JvmOverloads fun dashboard_dashboard_elements( dashboard_id: String, fields: String? = null ) : SDKResponse { val path_dashboard_id = encodeParam(dashboard_id) return this.get<ByteArray>("/dashboards/${path_dashboard_id}/dashboard_elements", mapOf("fields" to fields)) } /** * ### Create a dashboard element on the dashboard with a specific id. * * @param {WriteDashboardElement} body * @param {String} fields Requested fields. * @param {Boolean} apply_filters Apply relevant filters on dashboard to this tile * * POST /dashboard_elements -> ByteArray */ @JvmOverloads fun create_dashboard_element( body: WriteDashboardElement, fields: String? = null, apply_filters: Boolean? = null ) : SDKResponse { return this.post<ByteArray>("/dashboard_elements", mapOf("fields" to fields, "apply_filters" to apply_filters), body) } /** * ### Get information about the dashboard filters with a specific id. * * @param {String} dashboard_filter_id Id of dashboard filters * @param {String} fields Requested fields. * * GET /dashboard_filters/{dashboard_filter_id} -> ByteArray */ @JvmOverloads fun dashboard_filter( dashboard_filter_id: String, fields: String? = null ) : SDKResponse { val path_dashboard_filter_id = encodeParam(dashboard_filter_id) return this.get<ByteArray>("/dashboard_filters/${path_dashboard_filter_id}", mapOf("fields" to fields)) } /** * ### Update the dashboard filter with a specific id. * * @param {String} dashboard_filter_id Id of dashboard filter * @param {WriteDashboardFilter} body * @param {String} fields Requested fields. * * PATCH /dashboard_filters/{dashboard_filter_id} -> ByteArray */ @JvmOverloads fun update_dashboard_filter( dashboard_filter_id: String, body: WriteDashboardFilter, fields: String? = null ) : SDKResponse { val path_dashboard_filter_id = encodeParam(dashboard_filter_id) return this.patch<ByteArray>("/dashboard_filters/${path_dashboard_filter_id}", mapOf("fields" to fields), body) } /** * ### Delete a dashboard filter with a specific id. * * @param {String} dashboard_filter_id Id of dashboard filter * * DELETE /dashboard_filters/{dashboard_filter_id} -> ByteArray */ fun delete_dashboard_filter( dashboard_filter_id: String ) : SDKResponse { val path_dashboard_filter_id = encodeParam(dashboard_filter_id) return this.delete<ByteArray>("/dashboard_filters/${path_dashboard_filter_id}", mapOf()) } /** * ### Get information about all the dashboard filters on a dashboard with a specific id. * * @param {String} dashboard_id Id of dashboard * @param {String} fields Requested fields. * * GET /dashboards/{dashboard_id}/dashboard_filters -> ByteArray */ @JvmOverloads fun dashboard_dashboard_filters( dashboard_id: String, fields: String? = null ) : SDKResponse { val path_dashboard_id = encodeParam(dashboard_id) return this.get<ByteArray>("/dashboards/${path_dashboard_id}/dashboard_filters", mapOf("fields" to fields)) } /** * ### Create a dashboard filter on the dashboard with a specific id. * * @param {WriteCreateDashboardFilter} body * @param {String} fields Requested fields * * POST /dashboard_filters -> ByteArray */ @JvmOverloads fun create_dashboard_filter( body: WriteCreateDashboardFilter, fields: String? = null ) : SDKResponse { return this.post<ByteArray>("/dashboard_filters", mapOf("fields" to fields), body) } /** * ### Get information about the dashboard elements with a specific id. * * @param {String} dashboard_layout_component_id Id of dashboard layout component * @param {String} fields Requested fields. * * GET /dashboard_layout_components/{dashboard_layout_component_id} -> ByteArray */ @JvmOverloads fun dashboard_layout_component( dashboard_layout_component_id: String, fields: String? = null ) : SDKResponse { val path_dashboard_layout_component_id = encodeParam(dashboard_layout_component_id) return this.get<ByteArray>("/dashboard_layout_components/${path_dashboard_layout_component_id}", mapOf("fields" to fields)) } /** * ### Update the dashboard element with a specific id. * * @param {String} dashboard_layout_component_id Id of dashboard layout component * @param {WriteDashboardLayoutComponent} body * @param {String} fields Requested fields. * * PATCH /dashboard_layout_components/{dashboard_layout_component_id} -> ByteArray */ @JvmOverloads fun update_dashboard_layout_component( dashboard_layout_component_id: String, body: WriteDashboardLayoutComponent, fields: String? = null ) : SDKResponse { val path_dashboard_layout_component_id = encodeParam(dashboard_layout_component_id) return this.patch<ByteArray>("/dashboard_layout_components/${path_dashboard_layout_component_id}", mapOf("fields" to fields), body) } /** * ### Get information about all the dashboard layout components for a dashboard layout with a specific id. * * @param {String} dashboard_layout_id Id of dashboard layout component * @param {String} fields Requested fields. * * GET /dashboard_layouts/{dashboard_layout_id}/dashboard_layout_components -> ByteArray */ @JvmOverloads fun dashboard_layout_dashboard_layout_components( dashboard_layout_id: String, fields: String? = null ) : SDKResponse { val path_dashboard_layout_id = encodeParam(dashboard_layout_id) return this.get<ByteArray>("/dashboard_layouts/${path_dashboard_layout_id}/dashboard_layout_components", mapOf("fields" to fields)) } /** * ### Get information about the dashboard layouts with a specific id. * * @param {String} dashboard_layout_id Id of dashboard layouts * @param {String} fields Requested fields. * * GET /dashboard_layouts/{dashboard_layout_id} -> ByteArray */ @JvmOverloads fun dashboard_layout( dashboard_layout_id: String, fields: String? = null ) : SDKResponse { val path_dashboard_layout_id = encodeParam(dashboard_layout_id) return this.get<ByteArray>("/dashboard_layouts/${path_dashboard_layout_id}", mapOf("fields" to fields)) } /** * ### Update the dashboard layout with a specific id. * * @param {String} dashboard_layout_id Id of dashboard layout * @param {WriteDashboardLayout} body * @param {String} fields Requested fields. * * PATCH /dashboard_layouts/{dashboard_layout_id} -> ByteArray */ @JvmOverloads fun update_dashboard_layout( dashboard_layout_id: String, body: WriteDashboardLayout, fields: String? = null ) : SDKResponse { val path_dashboard_layout_id = encodeParam(dashboard_layout_id) return this.patch<ByteArray>("/dashboard_layouts/${path_dashboard_layout_id}", mapOf("fields" to fields), body) } /** * ### Delete a dashboard layout with a specific id. * * @param {String} dashboard_layout_id Id of dashboard layout * * DELETE /dashboard_layouts/{dashboard_layout_id} -> ByteArray */ fun delete_dashboard_layout( dashboard_layout_id: String ) : SDKResponse { val path_dashboard_layout_id = encodeParam(dashboard_layout_id) return this.delete<ByteArray>("/dashboard_layouts/${path_dashboard_layout_id}", mapOf()) } /** * ### Get information about all the dashboard elements on a dashboard with a specific id. * * @param {String} dashboard_id Id of dashboard * @param {String} fields Requested fields. * * GET /dashboards/{dashboard_id}/dashboard_layouts -> ByteArray */ @JvmOverloads fun dashboard_dashboard_layouts( dashboard_id: String, fields: String? = null ) : SDKResponse { val path_dashboard_id = encodeParam(dashboard_id) return this.get<ByteArray>("/dashboards/${path_dashboard_id}/dashboard_layouts", mapOf("fields" to fields)) } /** * ### Create a dashboard layout on the dashboard with a specific id. * * @param {WriteDashboardLayout} body * @param {String} fields Requested fields. * * POST /dashboard_layouts -> ByteArray */ @JvmOverloads fun create_dashboard_layout( body: WriteDashboardLayout, fields: String? = null ) : SDKResponse { return this.post<ByteArray>("/dashboard_layouts", mapOf("fields" to fields), body) } //endregion Dashboard: Manage Dashboards //region DataAction: Run Data Actions /** * Perform a data action. The data action object can be obtained from query results, and used to perform an arbitrary action. * * @param {DataActionRequest} body * * POST /data_actions -> ByteArray */ fun perform_data_action( body: DataActionRequest ) : SDKResponse { return this.post<ByteArray>("/data_actions", mapOf(), body) } /** * For some data actions, the remote server may supply a form requesting further user input. This endpoint takes a data action, asks the remote server to generate a form for it, and returns that form to you for presentation to the user. * * @param {Map<String,Any>} body * * POST /data_actions/form -> ByteArray */ fun fetch_remote_data_action_form( body: Map<String,Any> ) : SDKResponse { return this.post<ByteArray>("/data_actions/form", mapOf(), body) } //endregion DataAction: Run Data Actions //region Datagroup: Manage Datagroups /** * ### Get information about all datagroups. * * GET /datagroups -> ByteArray */ fun all_datagroups( ) : SDKResponse { return this.get<ByteArray>("/datagroups", mapOf()) } /** * ### Get information about a datagroup. * * @param {String} datagroup_id ID of datagroup. * * GET /datagroups/{datagroup_id} -> ByteArray */ fun datagroup( datagroup_id: String ) : SDKResponse { val path_datagroup_id = encodeParam(datagroup_id) return this.get<ByteArray>("/datagroups/${path_datagroup_id}", mapOf()) } /** * ### Update a datagroup using the specified params. * * @param {String} datagroup_id ID of datagroup. * @param {WriteDatagroup} body * * PATCH /datagroups/{datagroup_id} -> ByteArray */ fun update_datagroup( datagroup_id: String, body: WriteDatagroup ) : SDKResponse { val path_datagroup_id = encodeParam(datagroup_id) return this.patch<ByteArray>("/datagroups/${path_datagroup_id}", mapOf(), body) } //endregion Datagroup: Manage Datagroups //region DerivedTable: View Derived Table graphs /** * ### Discover information about derived tables * * @param {String} model The name of the Lookml model. * @param {String} format The format of the graph. Valid values are [dot]. Default is `dot` * @param {String} color Color denoting the build status of the graph. Grey = not built, green = built, yellow = building, red = error. * * GET /derived_table/graph/model/{model} -> ByteArray */ @JvmOverloads fun graph_derived_tables_for_model( model: String, format: String? = null, color: String? = null ) : SDKResponse { val path_model = encodeParam(model) return this.get<ByteArray>("/derived_table/graph/model/${path_model}", mapOf("format" to format, "color" to color)) } /** * ### Get the subgraph representing this derived table and its dependencies. * * @param {String} view The derived table's view name. * @param {String} models The models where this derived table is defined. * @param {String} workspace The model directory to look in, either `dev` or `production`. * * GET /derived_table/graph/view/{view} -> ByteArray */ @JvmOverloads fun graph_derived_tables_for_view( view: String, models: String? = null, workspace: String? = null ) : SDKResponse { val path_view = encodeParam(view) return this.get<ByteArray>("/derived_table/graph/view/${path_view}", mapOf("models" to models, "workspace" to workspace)) } /** * Enqueue materialization for a PDT with the given model name and view name * * @param {String} model_name The model of the PDT to start building. * @param {String} view_name The view name of the PDT to start building. * @param {String} force_rebuild Force rebuild of required dependent PDTs, even if they are already materialized. * @param {String} force_full_incremental Force involved incremental PDTs to fully re-materialize. * @param {String} workspace Workspace in which to materialize selected PDT ('dev' or default 'production'). * @param {String} source The source of this request. * * GET /derived_table/{model_name}/{view_name}/start -> ByteArray */ @JvmOverloads fun start_pdt_build( model_name: String, view_name: String, force_rebuild: String? = null, force_full_incremental: String? = null, workspace: String? = null, source: String? = null ) : SDKResponse { val path_model_name = encodeParam(model_name) val path_view_name = encodeParam(view_name) return this.get<ByteArray>("/derived_table/${path_model_name}/${path_view_name}/start", mapOf("force_rebuild" to force_rebuild, "force_full_incremental" to force_full_incremental, "workspace" to workspace, "source" to source)) } /** * Check status of PDT materialization * * @param {String} materialization_id The materialization id to check status for. * * GET /derived_table/{materialization_id}/status -> ByteArray */ fun check_pdt_build( materialization_id: String ) : SDKResponse { val path_materialization_id = encodeParam(materialization_id) return this.get<ByteArray>("/derived_table/${path_materialization_id}/status", mapOf()) } /** * Stop a PDT materialization * * @param {String} materialization_id The materialization id to stop. * @param {String} source The source of this request. * * GET /derived_table/{materialization_id}/stop -> ByteArray */ @JvmOverloads fun stop_pdt_build( materialization_id: String, source: String? = null ) : SDKResponse { val path_materialization_id = encodeParam(materialization_id) return this.get<ByteArray>("/derived_table/${path_materialization_id}/stop", mapOf("source" to source)) } //endregion DerivedTable: View Derived Table graphs //region Folder: Manage Folders /** * Search for folders by creator id, parent id, name, etc * * @param {String} fields Requested fields. * @param {Long} page DEPRECATED. Use limit and offset instead. Return only page N of paginated results * @param {Long} per_page DEPRECATED. Use limit and offset instead. Return N rows of data per page * @param {Long} limit Number of results to return. (used with offset and takes priority over page and per_page) * @param {Long} offset Number of results to skip before returning any. (used with limit and takes priority over page and per_page) * @param {String} sorts Fields to sort by. * @param {String} name Match Space title. * @param {String} id Match Space id * @param {String} parent_id Filter on a children of a particular folder. * @param {String} creator_id Filter on folder created by a particular user. * @param {Boolean} filter_or Combine given search criteria in a boolean OR expression * @param {Boolean} is_shared_root Match is shared root * * GET /folders/search -> ByteArray */ @JvmOverloads fun search_folders( fields: String? = null, page: Long? = null, per_page: Long? = null, limit: Long? = null, offset: Long? = null, sorts: String? = null, name: String? = null, id: String? = null, parent_id: String? = null, creator_id: String? = null, filter_or: Boolean? = null, is_shared_root: Boolean? = null ) : SDKResponse { return this.get<ByteArray>("/folders/search", mapOf("fields" to fields, "page" to page, "per_page" to per_page, "limit" to limit, "offset" to offset, "sorts" to sorts, "name" to name, "id" to id, "parent_id" to parent_id, "creator_id" to creator_id, "filter_or" to filter_or, "is_shared_root" to is_shared_root)) } /** * ### Get information about the folder with a specific id. * * @param {String} folder_id Id of folder * @param {String} fields Requested fields. * * GET /folders/{folder_id} -> ByteArray */ @JvmOverloads fun folder( folder_id: String, fields: String? = null ) : SDKResponse { val path_folder_id = encodeParam(folder_id) return this.get<ByteArray>("/folders/${path_folder_id}", mapOf("fields" to fields)) } /** * ### Update the folder with a specific id. * * @param {String} folder_id Id of folder * @param {UpdateFolder} body * * PATCH /folders/{folder_id} -> ByteArray */ fun update_folder( folder_id: String, body: UpdateFolder ) : SDKResponse { val path_folder_id = encodeParam(folder_id) return this.patch<ByteArray>("/folders/${path_folder_id}", mapOf(), body) } /** * ### Delete the folder with a specific id including any children folders. * **DANGER** this will delete all looks and dashboards in the folder. * * @param {String} folder_id Id of folder * * DELETE /folders/{folder_id} -> ByteArray */ fun delete_folder( folder_id: String ) : SDKResponse { val path_folder_id = encodeParam(folder_id) return this.delete<ByteArray>("/folders/${path_folder_id}", mapOf()) } /** * ### Get information about all folders. * * In API 3.x, this will not return empty personal folders, unless they belong to the calling user, * or if they contain soft-deleted content. * * In API 4.0+, all personal folders will be returned. * * @param {String} fields Requested fields. * * GET /folders -> ByteArray */ @JvmOverloads fun all_folders( fields: String? = null ) : SDKResponse { return this.get<ByteArray>("/folders", mapOf("fields" to fields)) } /** * ### Create a folder with specified information. * * Caller must have permission to edit the parent folder and to create folders, otherwise the request * returns 404 Not Found. * * @param {CreateFolder} body * * POST /folders -> ByteArray */ fun create_folder( body: CreateFolder ) : SDKResponse { return this.post<ByteArray>("/folders", mapOf(), body) } /** * ### Get the children of a folder. * * @param {String} folder_id Id of folder * @param {String} fields Requested fields. * @param {Long} page DEPRECATED. Use limit and offset instead. Return only page N of paginated results * @param {Long} per_page DEPRECATED. Use limit and offset instead. Return N rows of data per page * @param {Long} limit Number of results to return. (used with offset and takes priority over page and per_page) * @param {Long} offset Number of results to skip before returning any. (used with limit and takes priority over page and per_page) * @param {String} sorts Fields to sort by. * * GET /folders/{folder_id}/children -> ByteArray */ @JvmOverloads fun folder_children( folder_id: String, fields: String? = null, page: Long? = null, per_page: Long? = null, limit: Long? = null, offset: Long? = null, sorts: String? = null ) : SDKResponse { val path_folder_id = encodeParam(folder_id) return this.get<ByteArray>("/folders/${path_folder_id}/children", mapOf("fields" to fields, "page" to page, "per_page" to per_page, "limit" to limit, "offset" to offset, "sorts" to sorts)) } /** * ### Search the children of a folder * * @param {String} folder_id Id of folder * @param {String} fields Requested fields. * @param {String} sorts Fields to sort by. * @param {String} name Match folder name. * * GET /folders/{folder_id}/children/search -> ByteArray */ @JvmOverloads fun folder_children_search( folder_id: String, fields: String? = null, sorts: String? = null, name: String? = null ) : SDKResponse { val path_folder_id = encodeParam(folder_id) return this.get<ByteArray>("/folders/${path_folder_id}/children/search", mapOf("fields" to fields, "sorts" to sorts, "name" to name)) } /** * ### Get the parent of a folder * * @param {String} folder_id Id of folder * @param {String} fields Requested fields. * * GET /folders/{folder_id}/parent -> ByteArray */ @JvmOverloads fun folder_parent( folder_id: String, fields: String? = null ) : SDKResponse { val path_folder_id = encodeParam(folder_id) return this.get<ByteArray>("/folders/${path_folder_id}/parent", mapOf("fields" to fields)) } /** * ### Get the ancestors of a folder * * @param {String} folder_id Id of folder * @param {String} fields Requested fields. * * GET /folders/{folder_id}/ancestors -> ByteArray */ @JvmOverloads fun folder_ancestors( folder_id: String, fields: String? = null ) : SDKResponse { val path_folder_id = encodeParam(folder_id) return this.get<ByteArray>("/folders/${path_folder_id}/ancestors", mapOf("fields" to fields)) } /** * ### Get all looks in a folder. * In API 3.x, this will return all looks in a folder, including looks in the trash. * In API 4.0+, all looks in a folder will be returned, excluding looks in the trash. * * @param {String} folder_id Id of folder * @param {String} fields Requested fields. * * GET /folders/{folder_id}/looks -> ByteArray */ @JvmOverloads fun folder_looks( folder_id: String, fields: String? = null ) : SDKResponse { val path_folder_id = encodeParam(folder_id) return this.get<ByteArray>("/folders/${path_folder_id}/looks", mapOf("fields" to fields)) } /** * ### Get the dashboards in a folder * * @param {String} folder_id Id of folder * @param {String} fields Requested fields. * * GET /folders/{folder_id}/dashboards -> ByteArray */ @JvmOverloads fun folder_dashboards( folder_id: String, fields: String? = null ) : SDKResponse { val path_folder_id = encodeParam(folder_id) return this.get<ByteArray>("/folders/${path_folder_id}/dashboards", mapOf("fields" to fields)) } //endregion Folder: Manage Folders //region Group: Manage Groups /** * ### Get information about all groups. * * @param {String} fields Requested fields. * @param {Long} page DEPRECATED. Use limit and offset instead. Return only page N of paginated results * @param {Long} per_page DEPRECATED. Use limit and offset instead. Return N rows of data per page * @param {Long} limit Number of results to return. (used with offset and takes priority over page and per_page) * @param {Long} offset Number of results to skip before returning any. (used with limit and takes priority over page and per_page) * @param {String} sorts Fields to sort by. * @param {DelimArray<String>} ids Optional of ids to get specific groups. * @param {String} content_metadata_id Id of content metadata to which groups must have access. * @param {Boolean} can_add_to_content_metadata Select only groups that either can/cannot be given access to content. * * GET /groups -> ByteArray */ @JvmOverloads fun all_groups( fields: String? = null, page: Long? = null, per_page: Long? = null, limit: Long? = null, offset: Long? = null, sorts: String? = null, ids: DelimArray<String>? = null, content_metadata_id: String? = null, can_add_to_content_metadata: Boolean? = null ) : SDKResponse { return this.get<ByteArray>("/groups", mapOf("fields" to fields, "page" to page, "per_page" to per_page, "limit" to limit, "offset" to offset, "sorts" to sorts, "ids" to ids, "content_metadata_id" to content_metadata_id, "can_add_to_content_metadata" to can_add_to_content_metadata)) } /** * ### Creates a new group (admin only). * * @param {WriteGroup} body * @param {String} fields Requested fields. * * POST /groups -> ByteArray */ @JvmOverloads fun create_group( body: WriteGroup, fields: String? = null ) : SDKResponse { return this.post<ByteArray>("/groups", mapOf("fields" to fields), body) } /** * ### Search groups * * Returns all group records that match the given search criteria. * * If multiple search params are given and `filter_or` is FALSE or not specified, * search params are combined in a logical AND operation. * Only rows that match *all* search param criteria will be returned. * * If `filter_or` is TRUE, multiple search params are combined in a logical OR operation. * Results will include rows that match **any** of the search criteria. * * String search params use case-insensitive matching. * String search params can contain `%` and '_' as SQL LIKE pattern match wildcard expressions. * example="dan%" will match "danger" and "Danzig" but not "David" * example="D_m%" will match "Damage" and "dump" * * Integer search params can accept a single value or a comma separated list of values. The multiple * values will be combined under a logical OR operation - results will match at least one of * the given values. * * Most search params can accept "IS NULL" and "NOT NULL" as special expressions to match * or exclude (respectively) rows where the column is null. * * Boolean search params accept only "true" and "false" as values. * * @param {String} fields Requested fields. * @param {Long} limit Number of results to return (used with `offset`). * @param {Long} offset Number of results to skip before returning any (used with `limit`). * @param {String} sorts Fields to sort by. * @param {Boolean} filter_or Combine given search criteria in a boolean OR expression * @param {String} id Match group id. * @param {String} name Match group name. * @param {String} external_group_id Match group external_group_id. * @param {Boolean} externally_managed Match group externally_managed. * @param {Boolean} externally_orphaned Match group externally_orphaned. * * GET /groups/search -> ByteArray */ @JvmOverloads fun search_groups( fields: String? = null, limit: Long? = null, offset: Long? = null, sorts: String? = null, filter_or: Boolean? = null, id: String? = null, name: String? = null, external_group_id: String? = null, externally_managed: Boolean? = null, externally_orphaned: Boolean? = null ) : SDKResponse { return this.get<ByteArray>("/groups/search", mapOf("fields" to fields, "limit" to limit, "offset" to offset, "sorts" to sorts, "filter_or" to filter_or, "id" to id, "name" to name, "external_group_id" to external_group_id, "externally_managed" to externally_managed, "externally_orphaned" to externally_orphaned)) } /** * ### Search groups include roles * * Returns all group records that match the given search criteria, and attaches any associated roles. * * If multiple search params are given and `filter_or` is FALSE or not specified, * search params are combined in a logical AND operation. * Only rows that match *all* search param criteria will be returned. * * If `filter_or` is TRUE, multiple search params are combined in a logical OR operation. * Results will include rows that match **any** of the search criteria. * * String search params use case-insensitive matching. * String search params can contain `%` and '_' as SQL LIKE pattern match wildcard expressions. * example="dan%" will match "danger" and "Danzig" but not "David" * example="D_m%" will match "Damage" and "dump" * * Integer search params can accept a single value or a comma separated list of values. The multiple * values will be combined under a logical OR operation - results will match at least one of * the given values. * * Most search params can accept "IS NULL" and "NOT NULL" as special expressions to match * or exclude (respectively) rows where the column is null. * * Boolean search params accept only "true" and "false" as values. * * @param {String} fields Requested fields. * @param {Long} limit Number of results to return (used with `offset`). * @param {Long} offset Number of results to skip before returning any (used with `limit`). * @param {String} sorts Fields to sort by. * @param {Boolean} filter_or Combine given search criteria in a boolean OR expression * @param {String} id Match group id. * @param {String} name Match group name. * @param {String} external_group_id Match group external_group_id. * @param {Boolean} externally_managed Match group externally_managed. * @param {Boolean} externally_orphaned Match group externally_orphaned. * * GET /groups/search/with_roles -> ByteArray */ @JvmOverloads fun search_groups_with_roles( fields: String? = null, limit: Long? = null, offset: Long? = null, sorts: String? = null, filter_or: Boolean? = null, id: String? = null, name: String? = null, external_group_id: String? = null, externally_managed: Boolean? = null, externally_orphaned: Boolean? = null ) : SDKResponse { return this.get<ByteArray>("/groups/search/with_roles", mapOf("fields" to fields, "limit" to limit, "offset" to offset, "sorts" to sorts, "filter_or" to filter_or, "id" to id, "name" to name, "external_group_id" to external_group_id, "externally_managed" to externally_managed, "externally_orphaned" to externally_orphaned)) } /** * ### Search groups include hierarchy * * Returns all group records that match the given search criteria, and attaches * associated role_ids and parent group_ids. * * If multiple search params are given and `filter_or` is FALSE or not specified, * search params are combined in a logical AND operation. * Only rows that match *all* search param criteria will be returned. * * If `filter_or` is TRUE, multiple search params are combined in a logical OR operation. * Results will include rows that match **any** of the search criteria. * * String search params use case-insensitive matching. * String search params can contain `%` and '_' as SQL LIKE pattern match wildcard expressions. * example="dan%" will match "danger" and "Danzig" but not "David" * example="D_m%" will match "Damage" and "dump" * * Integer search params can accept a single value or a comma separated list of values. The multiple * values will be combined under a logical OR operation - results will match at least one of * the given values. * * Most search params can accept "IS NULL" and "NOT NULL" as special expressions to match * or exclude (respectively) rows where the column is null. * * Boolean search params accept only "true" and "false" as values. * * @param {String} fields Requested fields. * @param {Long} limit Number of results to return (used with `offset`). * @param {Long} offset Number of results to skip before returning any (used with `limit`). * @param {String} sorts Fields to sort by. * @param {Boolean} filter_or Combine given search criteria in a boolean OR expression * @param {String} id Match group id. * @param {String} name Match group name. * @param {String} external_group_id Match group external_group_id. * @param {Boolean} externally_managed Match group externally_managed. * @param {Boolean} externally_orphaned Match group externally_orphaned. * * GET /groups/search/with_hierarchy -> ByteArray */ @JvmOverloads fun search_groups_with_hierarchy( fields: String? = null, limit: Long? = null, offset: Long? = null, sorts: String? = null, filter_or: Boolean? = null, id: String? = null, name: String? = null, external_group_id: String? = null, externally_managed: Boolean? = null, externally_orphaned: Boolean? = null ) : SDKResponse { return this.get<ByteArray>("/groups/search/with_hierarchy", mapOf("fields" to fields, "limit" to limit, "offset" to offset, "sorts" to sorts, "filter_or" to filter_or, "id" to id, "name" to name, "external_group_id" to external_group_id, "externally_managed" to externally_managed, "externally_orphaned" to externally_orphaned)) } /** * ### Get information about a group. * * @param {String} group_id Id of group * @param {String} fields Requested fields. * * GET /groups/{group_id} -> ByteArray */ @JvmOverloads fun group( group_id: String, fields: String? = null ) : SDKResponse { val path_group_id = encodeParam(group_id) return this.get<ByteArray>("/groups/${path_group_id}", mapOf("fields" to fields)) } /** * ### Updates the a group (admin only). * * @param {String} group_id Id of group * @param {WriteGroup} body * @param {String} fields Requested fields. * * PATCH /groups/{group_id} -> ByteArray */ @JvmOverloads fun update_group( group_id: String, body: WriteGroup, fields: String? = null ) : SDKResponse { val path_group_id = encodeParam(group_id) return this.patch<ByteArray>("/groups/${path_group_id}", mapOf("fields" to fields), body) } /** * ### Deletes a group (admin only). * * @param {String} group_id Id of group * * DELETE /groups/{group_id} -> ByteArray */ fun delete_group( group_id: String ) : SDKResponse { val path_group_id = encodeParam(group_id) return this.delete<ByteArray>("/groups/${path_group_id}", mapOf()) } /** * ### Get information about all the groups in a group * * @param {String} group_id Id of group * @param {String} fields Requested fields. * * GET /groups/{group_id}/groups -> ByteArray */ @JvmOverloads fun all_group_groups( group_id: String, fields: String? = null ) : SDKResponse { val path_group_id = encodeParam(group_id) return this.get<ByteArray>("/groups/${path_group_id}/groups", mapOf("fields" to fields)) } /** * ### Adds a new group to a group. * * @param {String} group_id Id of group * @param {GroupIdForGroupInclusion} body WARNING: no writeable properties found for POST, PUT, or PATCH * * POST /groups/{group_id}/groups -> ByteArray */ fun add_group_group( group_id: String, body: GroupIdForGroupInclusion ) : SDKResponse { val path_group_id = encodeParam(group_id) return this.post<ByteArray>("/groups/${path_group_id}/groups", mapOf(), body) } /** * ### Get information about all the users directly included in a group. * * @param {String} group_id Id of group * @param {String} fields Requested fields. * @param {Long} page DEPRECATED. Use limit and offset instead. Return only page N of paginated results * @param {Long} per_page DEPRECATED. Use limit and offset instead. Return N rows of data per page * @param {Long} limit Number of results to return. (used with offset and takes priority over page and per_page) * @param {Long} offset Number of results to skip before returning any. (used with limit and takes priority over page and per_page) * @param {String} sorts Fields to sort by. * * GET /groups/{group_id}/users -> ByteArray */ @JvmOverloads fun all_group_users( group_id: String, fields: String? = null, page: Long? = null, per_page: Long? = null, limit: Long? = null, offset: Long? = null, sorts: String? = null ) : SDKResponse { val path_group_id = encodeParam(group_id) return this.get<ByteArray>("/groups/${path_group_id}/users", mapOf("fields" to fields, "page" to page, "per_page" to per_page, "limit" to limit, "offset" to offset, "sorts" to sorts)) } /** * ### Adds a new user to a group. * * @param {String} group_id Id of group * @param {GroupIdForGroupUserInclusion} body WARNING: no writeable properties found for POST, PUT, or PATCH * * POST /groups/{group_id}/users -> ByteArray */ fun add_group_user( group_id: String, body: GroupIdForGroupUserInclusion ) : SDKResponse { val path_group_id = encodeParam(group_id) return this.post<ByteArray>("/groups/${path_group_id}/users", mapOf(), body) } /** * ### Removes a user from a group. * * @param {String} group_id Id of group * @param {String} user_id Id of user to remove from group * * DELETE /groups/{group_id}/users/{user_id} -> ByteArray */ fun delete_group_user( group_id: String, user_id: String ) : SDKResponse { val path_group_id = encodeParam(group_id) val path_user_id = encodeParam(user_id) return this.delete<ByteArray>("/groups/${path_group_id}/users/${path_user_id}", mapOf()) } /** * ### Removes a group from a group. * * @param {String} group_id Id of group * @param {String} deleting_group_id Id of group to delete * * DELETE /groups/{group_id}/groups/{deleting_group_id} -> ByteArray */ fun delete_group_from_group( group_id: String, deleting_group_id: String ) : SDKResponse { val path_group_id = encodeParam(group_id) val path_deleting_group_id = encodeParam(deleting_group_id) return this.delete<ByteArray>("/groups/${path_group_id}/groups/${path_deleting_group_id}", mapOf()) } /** * ### Set the value of a user attribute for a group. * * For information about how user attribute values are calculated, see [Set User Attribute Group Values](#!/UserAttribute/set_user_attribute_group_values). * * @param {String} group_id Id of group * @param {String} user_attribute_id Id of user attribute * @param {UserAttributeGroupValue} body WARNING: no writeable properties found for POST, PUT, or PATCH * * PATCH /groups/{group_id}/attribute_values/{user_attribute_id} -> ByteArray */ fun update_user_attribute_group_value( group_id: String, user_attribute_id: String, body: UserAttributeGroupValue ) : SDKResponse { val path_group_id = encodeParam(group_id) val path_user_attribute_id = encodeParam(user_attribute_id) return this.patch<ByteArray>("/groups/${path_group_id}/attribute_values/${path_user_attribute_id}", mapOf(), body) } /** * ### Remove a user attribute value from a group. * * @param {String} group_id Id of group * @param {String} user_attribute_id Id of user attribute * * DELETE /groups/{group_id}/attribute_values/{user_attribute_id} -> ByteArray */ fun delete_user_attribute_group_value( group_id: String, user_attribute_id: String ) : SDKResponse { val path_group_id = encodeParam(group_id) val path_user_attribute_id = encodeParam(user_attribute_id) return this.delete<ByteArray>("/groups/${path_group_id}/attribute_values/${path_user_attribute_id}", mapOf()) } //endregion Group: Manage Groups //region Homepage: Manage Homepage /** * ### Get information about the primary homepage's sections. * * @param {String} fields Requested fields. * * GET /primary_homepage_sections -> ByteArray */ @JvmOverloads fun all_primary_homepage_sections( fields: String? = null ) : SDKResponse { return this.get<ByteArray>("/primary_homepage_sections", mapOf("fields" to fields)) } //endregion Homepage: Manage Homepage //region Integration: Manage Integrations /** * ### Get information about all Integration Hubs. * * @param {String} fields Requested fields. * * GET /integration_hubs -> ByteArray */ @JvmOverloads fun all_integration_hubs( fields: String? = null ) : SDKResponse { return this.get<ByteArray>("/integration_hubs", mapOf("fields" to fields)) } /** * ### Create a new Integration Hub. * * This API is rate limited to prevent it from being used for SSRF attacks * * @param {WriteIntegrationHub} body * @param {String} fields Requested fields. * * POST /integration_hubs -> ByteArray */ @JvmOverloads fun create_integration_hub( body: WriteIntegrationHub, fields: String? = null ) : SDKResponse { return this.post<ByteArray>("/integration_hubs", mapOf("fields" to fields), body) } /** * ### Get information about a Integration Hub. * * @param {String} integration_hub_id Id of integration_hub * @param {String} fields Requested fields. * * GET /integration_hubs/{integration_hub_id} -> ByteArray */ @JvmOverloads fun integration_hub( integration_hub_id: String, fields: String? = null ) : SDKResponse { val path_integration_hub_id = encodeParam(integration_hub_id) return this.get<ByteArray>("/integration_hubs/${path_integration_hub_id}", mapOf("fields" to fields)) } /** * ### Update a Integration Hub definition. * * This API is rate limited to prevent it from being used for SSRF attacks * * @param {String} integration_hub_id Id of integration_hub * @param {WriteIntegrationHub} body * @param {String} fields Requested fields. * * PATCH /integration_hubs/{integration_hub_id} -> ByteArray */ @JvmOverloads fun update_integration_hub( integration_hub_id: String, body: WriteIntegrationHub, fields: String? = null ) : SDKResponse { val path_integration_hub_id = encodeParam(integration_hub_id) return this.patch<ByteArray>("/integration_hubs/${path_integration_hub_id}", mapOf("fields" to fields), body) } /** * ### Delete a Integration Hub. * * @param {String} integration_hub_id Id of integration_hub * * DELETE /integration_hubs/{integration_hub_id} -> ByteArray */ fun delete_integration_hub( integration_hub_id: String ) : SDKResponse { val path_integration_hub_id = encodeParam(integration_hub_id) return this.delete<ByteArray>("/integration_hubs/${path_integration_hub_id}", mapOf()) } /** * Accepts the legal agreement for a given integration hub. This only works for integration hubs that have legal_agreement_required set to true and legal_agreement_signed set to false. * * @param {String} integration_hub_id Id of integration_hub * * POST /integration_hubs/{integration_hub_id}/accept_legal_agreement -> ByteArray */ fun accept_integration_hub_legal_agreement( integration_hub_id: String ) : SDKResponse { val path_integration_hub_id = encodeParam(integration_hub_id) return this.post<ByteArray>("/integration_hubs/${path_integration_hub_id}/accept_legal_agreement", mapOf()) } /** * ### Get information about all Integrations. * * @param {String} fields Requested fields. * @param {String} integration_hub_id Filter to a specific provider * * GET /integrations -> ByteArray */ @JvmOverloads fun all_integrations( fields: String? = null, integration_hub_id: String? = null ) : SDKResponse { return this.get<ByteArray>("/integrations", mapOf("fields" to fields, "integration_hub_id" to integration_hub_id)) } /** * ### Get information about a Integration. * * @param {String} integration_id Id of integration * @param {String} fields Requested fields. * * GET /integrations/{integration_id} -> ByteArray */ @JvmOverloads fun integration( integration_id: String, fields: String? = null ) : SDKResponse { val path_integration_id = encodeParam(integration_id) return this.get<ByteArray>("/integrations/${path_integration_id}", mapOf("fields" to fields)) } /** * ### Update parameters on a Integration. * * @param {String} integration_id Id of integration * @param {WriteIntegration} body * @param {String} fields Requested fields. * * PATCH /integrations/{integration_id} -> ByteArray */ @JvmOverloads fun update_integration( integration_id: String, body: WriteIntegration, fields: String? = null ) : SDKResponse { val path_integration_id = encodeParam(integration_id) return this.patch<ByteArray>("/integrations/${path_integration_id}", mapOf("fields" to fields), body) } /** * Returns the Integration form for presentation to the user. * * @param {String} integration_id Id of integration * @param {Map<String,Any>} body * * POST /integrations/{integration_id}/form -> ByteArray */ @JvmOverloads fun fetch_integration_form( integration_id: String, body: Map<String,Any>? = null ) : SDKResponse { val path_integration_id = encodeParam(integration_id) return this.post<ByteArray>("/integrations/${path_integration_id}/form", mapOf(), body) } /** * Tests the integration to make sure all the settings are working. * * @param {String} integration_id Id of integration * * POST /integrations/{integration_id}/test -> ByteArray */ fun test_integration( integration_id: String ) : SDKResponse { val path_integration_id = encodeParam(integration_id) return this.post<ByteArray>("/integrations/${path_integration_id}/test", mapOf()) } //endregion Integration: Manage Integrations //region Look: Run and Manage Looks /** * ### Get information about all active Looks * * Returns an array of **abbreviated Look objects** describing all the looks that the caller has access to. Soft-deleted Looks are **not** included. * * Get the **full details** of a specific look by id with [look(id)](#!/Look/look) * * Find **soft-deleted looks** with [search_looks()](#!/Look/search_looks) * * @param {String} fields Requested fields. * * GET /looks -> ByteArray */ @JvmOverloads fun all_looks( fields: String? = null ) : SDKResponse { return this.get<ByteArray>("/looks", mapOf("fields" to fields)) } /** * ### Create a Look * * To create a look to display query data, first create the query with [create_query()](#!/Query/create_query) * then assign the query's id to the `query_id` property in the call to `create_look()`. * * To place the look into a particular space, assign the space's id to the `space_id` property * in the call to `create_look()`. * * @param {WriteLookWithQuery} body * @param {String} fields Requested fields. * * POST /looks -> ByteArray */ @JvmOverloads fun create_look( body: WriteLookWithQuery, fields: String? = null ) : SDKResponse { return this.post<ByteArray>("/looks", mapOf("fields" to fields), body) } /** * ### Search Looks * * Returns an **array of Look objects** that match the specified search criteria. * * If multiple search params are given and `filter_or` is FALSE or not specified, * search params are combined in a logical AND operation. * Only rows that match *all* search param criteria will be returned. * * If `filter_or` is TRUE, multiple search params are combined in a logical OR operation. * Results will include rows that match **any** of the search criteria. * * String search params use case-insensitive matching. * String search params can contain `%` and '_' as SQL LIKE pattern match wildcard expressions. * example="dan%" will match "danger" and "Danzig" but not "David" * example="D_m%" will match "Damage" and "dump" * * Integer search params can accept a single value or a comma separated list of values. The multiple * values will be combined under a logical OR operation - results will match at least one of * the given values. * * Most search params can accept "IS NULL" and "NOT NULL" as special expressions to match * or exclude (respectively) rows where the column is null. * * Boolean search params accept only "true" and "false" as values. * * * Get a **single look** by id with [look(id)](#!/Look/look) * * @param {String} id Match look id. * @param {String} title Match Look title. * @param {String} description Match Look description. * @param {String} content_favorite_id Select looks with a particular content favorite id * @param {String} folder_id Select looks in a particular folder. * @param {String} user_id Select looks created by a particular user. * @param {String} view_count Select looks with particular view_count value * @param {Boolean} deleted Select soft-deleted looks * @param {String} query_id Select looks that reference a particular query by query_id * @param {Boolean} curate Exclude items that exist only in personal spaces other than the users * @param {String} last_viewed_at Select looks based on when they were last viewed * @param {String} fields Requested fields. * @param {Long} page DEPRECATED. Use limit and offset instead. Return only page N of paginated results * @param {Long} per_page DEPRECATED. Use limit and offset instead. Return N rows of data per page * @param {Long} limit Number of results to return. (used with offset and takes priority over page and per_page) * @param {Long} offset Number of results to skip before returning any. (used with limit and takes priority over page and per_page) * @param {String} sorts One or more fields to sort results by. Sortable fields: [:title, :user_id, :id, :created_at, :space_id, :folder_id, :description, :updated_at, :last_updater_id, :view_count, :favorite_count, :content_favorite_id, :deleted, :deleted_at, :last_viewed_at, :last_accessed_at, :query_id] * @param {Boolean} filter_or Combine given search criteria in a boolean OR expression * * GET /looks/search -> ByteArray */ @JvmOverloads fun search_looks( id: String? = null, title: String? = null, description: String? = null, content_favorite_id: String? = null, folder_id: String? = null, user_id: String? = null, view_count: String? = null, deleted: Boolean? = null, query_id: String? = null, curate: Boolean? = null, last_viewed_at: String? = null, fields: String? = null, page: Long? = null, per_page: Long? = null, limit: Long? = null, offset: Long? = null, sorts: String? = null, filter_or: Boolean? = null ) : SDKResponse { return this.get<ByteArray>("/looks/search", mapOf("id" to id, "title" to title, "description" to description, "content_favorite_id" to content_favorite_id, "folder_id" to folder_id, "user_id" to user_id, "view_count" to view_count, "deleted" to deleted, "query_id" to query_id, "curate" to curate, "last_viewed_at" to last_viewed_at, "fields" to fields, "page" to page, "per_page" to per_page, "limit" to limit, "offset" to offset, "sorts" to sorts, "filter_or" to filter_or)) } /** * ### Get a Look. * * Returns detailed information about a Look and its associated Query. * * @param {String} look_id Id of look * @param {String} fields Requested fields. * * GET /looks/{look_id} -> ByteArray */ @JvmOverloads fun look( look_id: String, fields: String? = null ) : SDKResponse { val path_look_id = encodeParam(look_id) return this.get<ByteArray>("/looks/${path_look_id}", mapOf("fields" to fields)) } /** * ### Modify a Look * * Use this function to modify parts of a look. Property values given in a call to `update_look` are * applied to the existing look, so there's no need to include properties whose values are not changing. * It's best to specify only the properties you want to change and leave everything else out * of your `update_look` call. **Look properties marked 'read-only' will be ignored.** * * When a user deletes a look in the Looker UI, the look data remains in the database but is * marked with a deleted flag ("soft-deleted"). Soft-deleted looks can be undeleted (by an admin) * if the delete was in error. * * To soft-delete a look via the API, use [update_look()](#!/Look/update_look) to change the look's `deleted` property to `true`. * You can undelete a look by calling `update_look` to change the look's `deleted` property to `false`. * * Soft-deleted looks are excluded from the results of [all_looks()](#!/Look/all_looks) and [search_looks()](#!/Look/search_looks), so they * essentially disappear from view even though they still reside in the db. * In API 3.1 and later, you can pass `deleted: true` as a parameter to [search_looks()](#!/3.1/Look/search_looks) to list soft-deleted looks. * * NOTE: [delete_look()](#!/Look/delete_look) performs a "hard delete" - the look data is removed from the Looker * database and destroyed. There is no "undo" for `delete_look()`. * * @param {String} look_id Id of look * @param {WriteLookWithQuery} body * @param {String} fields Requested fields. * * PATCH /looks/{look_id} -> ByteArray */ @JvmOverloads fun update_look( look_id: String, body: WriteLookWithQuery, fields: String? = null ) : SDKResponse { val path_look_id = encodeParam(look_id) return this.patch<ByteArray>("/looks/${path_look_id}", mapOf("fields" to fields), body) } /** * ### Permanently Delete a Look * * This operation **permanently** removes a look from the Looker database. * * NOTE: There is no "undo" for this kind of delete. * * For information about soft-delete (which can be undone) see [update_look()](#!/Look/update_look). * * @param {String} look_id Id of look * * DELETE /looks/{look_id} -> ByteArray */ fun delete_look( look_id: String ) : SDKResponse { val path_look_id = encodeParam(look_id) return this.delete<ByteArray>("/looks/${path_look_id}", mapOf()) } /** * ### Run a Look * * Runs a given look's query and returns the results in the requested format. * * Supported formats: * * | result_format | Description * | :-----------: | :--- | * | json | Plain json * | json_detail | Row data plus metadata describing the fields, pivots, table calcs, and other aspects of the query * | csv | Comma separated values with a header * | txt | Tab separated values with a header * | html | Simple html * | md | Simple markdown * | xlsx | MS Excel spreadsheet * | sql | Returns the generated SQL rather than running the query * | png | A PNG image of the visualization of the query * | jpg | A JPG image of the visualization of the query * * @param {String} look_id Id of look * @param {String} result_format Format of result * @param {Long} limit Row limit (may override the limit in the saved query). * @param {Boolean} apply_formatting Apply model-specified formatting to each result. * @param {Boolean} apply_vis Apply visualization options to results. * @param {Boolean} cache Get results from cache if available. * @param {Long} image_width Render width for image formats. * @param {Long} image_height Render height for image formats. * @param {Boolean} generate_drill_links Generate drill links (only applicable to 'json_detail' format. * @param {Boolean} force_production Force use of production models even if the user is in development mode. Note that this flag being false does not guarantee development models will be used. * @param {Boolean} cache_only Retrieve any results from cache even if the results have expired. * @param {String} path_prefix Prefix to use for drill links (url encoded). * @param {Boolean} rebuild_pdts Rebuild PDTS used in query. * @param {Boolean} server_table_calcs Perform table calculations on query results * * GET /looks/{look_id}/run/{result_format} -> ByteArray * * **Note**: Binary content may be returned by this method. */ @JvmOverloads fun run_look( look_id: String, result_format: String, limit: Long? = null, apply_formatting: Boolean? = null, apply_vis: Boolean? = null, cache: Boolean? = null, image_width: Long? = null, image_height: Long? = null, generate_drill_links: Boolean? = null, force_production: Boolean? = null, cache_only: Boolean? = null, path_prefix: String? = null, rebuild_pdts: Boolean? = null, server_table_calcs: Boolean? = null ) : SDKResponse { val path_look_id = encodeParam(look_id) val path_result_format = encodeParam(result_format) return this.get<ByteArray>("/looks/${path_look_id}/run/${path_result_format}", mapOf("limit" to limit, "apply_formatting" to apply_formatting, "apply_vis" to apply_vis, "cache" to cache, "image_width" to image_width, "image_height" to image_height, "generate_drill_links" to generate_drill_links, "force_production" to force_production, "cache_only" to cache_only, "path_prefix" to path_prefix, "rebuild_pdts" to rebuild_pdts, "server_table_calcs" to server_table_calcs)) } /** * ### Copy an existing look * * Creates a copy of an existing look, in a specified folder, and returns the copied look. * * `look_id` and `folder_id` are required. * * `look_id` and `folder_id` must already exist, and `folder_id` must be different from the current `folder_id` of the dashboard. * * @param {String} look_id Look id to copy. * @param {String} folder_id Folder id to copy to. * * POST /looks/{look_id}/copy -> ByteArray */ @JvmOverloads fun copy_look( look_id: String, folder_id: String? = null ) : SDKResponse { val path_look_id = encodeParam(look_id) return this.post<ByteArray>("/looks/${path_look_id}/copy", mapOf("folder_id" to folder_id)) } /** * ### Move an existing look * * Moves a look to a specified folder, and returns the moved look. * * `look_id` and `folder_id` are required. * `look_id` and `folder_id` must already exist, and `folder_id` must be different from the current `folder_id` of the dashboard. * * @param {String} look_id Look id to move. * @param {String} folder_id Folder id to move to. * * PATCH /looks/{look_id}/move -> ByteArray */ fun move_look( look_id: String, folder_id: String ) : SDKResponse { val path_look_id = encodeParam(look_id) return this.patch<ByteArray>("/looks/${path_look_id}/move", mapOf("folder_id" to folder_id)) } //endregion Look: Run and Manage Looks //region LookmlModel: Manage LookML Models /** * ### Get information about all lookml models. * * @param {String} fields Requested fields. * @param {Long} limit Number of results to return. (can be used with offset) * @param {Long} offset Number of results to skip before returning any. (Defaults to 0 if not set when limit is used) * * GET /lookml_models -> ByteArray */ @JvmOverloads fun all_lookml_models( fields: String? = null, limit: Long? = null, offset: Long? = null ) : SDKResponse { return this.get<ByteArray>("/lookml_models", mapOf("fields" to fields, "limit" to limit, "offset" to offset)) } /** * ### Create a lookml model using the specified configuration. * * @param {WriteLookmlModel} body * * POST /lookml_models -> ByteArray */ fun create_lookml_model( body: WriteLookmlModel ) : SDKResponse { return this.post<ByteArray>("/lookml_models", mapOf(), body) } /** * ### Get information about a lookml model. * * @param {String} lookml_model_name Name of lookml model. * @param {String} fields Requested fields. * * GET /lookml_models/{lookml_model_name} -> ByteArray */ @JvmOverloads fun lookml_model( lookml_model_name: String, fields: String? = null ) : SDKResponse { val path_lookml_model_name = encodeParam(lookml_model_name) return this.get<ByteArray>("/lookml_models/${path_lookml_model_name}", mapOf("fields" to fields)) } /** * ### Update a lookml model using the specified configuration. * * @param {String} lookml_model_name Name of lookml model. * @param {WriteLookmlModel} body * * PATCH /lookml_models/{lookml_model_name} -> ByteArray */ fun update_lookml_model( lookml_model_name: String, body: WriteLookmlModel ) : SDKResponse { val path_lookml_model_name = encodeParam(lookml_model_name) return this.patch<ByteArray>("/lookml_models/${path_lookml_model_name}", mapOf(), body) } /** * ### Delete a lookml model. * * @param {String} lookml_model_name Name of lookml model. * * DELETE /lookml_models/{lookml_model_name} -> ByteArray */ fun delete_lookml_model( lookml_model_name: String ) : SDKResponse { val path_lookml_model_name = encodeParam(lookml_model_name) return this.delete<ByteArray>("/lookml_models/${path_lookml_model_name}", mapOf()) } /** * ### Get information about a lookml model explore. * * @param {String} lookml_model_name Name of lookml model. * @param {String} explore_name Name of explore. * @param {String} fields Requested fields. * * GET /lookml_models/{lookml_model_name}/explores/{explore_name} -> ByteArray */ @JvmOverloads fun lookml_model_explore( lookml_model_name: String, explore_name: String, fields: String? = null ) : SDKResponse { val path_lookml_model_name = encodeParam(lookml_model_name) val path_explore_name = encodeParam(explore_name) return this.get<ByteArray>("/lookml_models/${path_lookml_model_name}/explores/${path_explore_name}", mapOf("fields" to fields)) } //endregion LookmlModel: Manage LookML Models //region Metadata: Connection Metadata Features /** * ### Field name suggestions for a model and view * * `filters` is a string hash of values, with the key as the field name and the string value as the filter expression: * * ```ruby * {'users.age': '>=60'} * ``` * * or * * ```ruby * {'users.age': '<30'} * ``` * * or * * ```ruby * {'users.age': '=50'} * ``` * * @param {String} model_name Name of model * @param {String} view_name Name of view * @param {String} field_name Name of field to use for suggestions * @param {String} term Search term pattern (evaluated as as `%term%`) * @param {Any} filters Suggestion filters with field name keys and comparison expressions * * GET /models/{model_name}/views/{view_name}/fields/{field_name}/suggestions -> ByteArray */ @JvmOverloads fun model_fieldname_suggestions( model_name: String, view_name: String, field_name: String, term: String? = null, filters: Any? = null ) : SDKResponse { val path_model_name = encodeParam(model_name) val path_view_name = encodeParam(view_name) val path_field_name = encodeParam(field_name) return this.get<ByteArray>("/models/${path_model_name}/views/${path_view_name}/fields/${path_field_name}/suggestions", mapOf("term" to term, "filters" to filters)) } /** * ### Get a single model * * @param {String} model_name Name of model * * GET /models/{model_name} -> ByteArray */ fun get_model( model_name: String ) : SDKResponse { val path_model_name = encodeParam(model_name) return this.get<ByteArray>("/models/${path_model_name}", mapOf()) } /** * ### List databases available to this connection * * Certain dialects can support multiple databases per single connection. * If this connection supports multiple databases, the database names will be returned in an array. * * Connections using dialects that do not support multiple databases will return an empty array. * * **Note**: [Connection Features](#!/Metadata/connection_features) can be used to determine if a connection supports * multiple databases. * * @param {String} connection_name Name of connection * * GET /connections/{connection_name}/databases -> ByteArray */ fun connection_databases( connection_name: String ) : SDKResponse { val path_connection_name = encodeParam(connection_name) return this.get<ByteArray>("/connections/${path_connection_name}/databases", mapOf()) } /** * ### Retrieve metadata features for this connection * * Returns a list of feature names with `true` (available) or `false` (not available) * * @param {String} connection_name Name of connection * @param {String} fields Requested fields. * * GET /connections/{connection_name}/features -> ByteArray */ @JvmOverloads fun connection_features( connection_name: String, fields: String? = null ) : SDKResponse { val path_connection_name = encodeParam(connection_name) return this.get<ByteArray>("/connections/${path_connection_name}/features", mapOf("fields" to fields)) } /** * ### Get the list of schemas and tables for a connection * * @param {String} connection_name Name of connection * @param {String} database For dialects that support multiple databases, optionally identify which to use * @param {Boolean} cache True to use fetch from cache, false to load fresh * @param {String} fields Requested fields. * * GET /connections/{connection_name}/schemas -> ByteArray */ @JvmOverloads fun connection_schemas( connection_name: String, database: String? = null, cache: Boolean? = null, fields: String? = null ) : SDKResponse { val path_connection_name = encodeParam(connection_name) return this.get<ByteArray>("/connections/${path_connection_name}/schemas", mapOf("database" to database, "cache" to cache, "fields" to fields)) } /** * ### Get the list of tables for a schema * * For dialects that support multiple databases, optionally identify which to use. If not provided, the default * database for the connection will be used. * * For dialects that do **not** support multiple databases, **do not use** the database parameter * * @param {String} connection_name Name of connection * @param {String} database Optional. Name of database to use for the query, only if applicable * @param {String} schema_name Optional. Return only tables for this schema * @param {Boolean} cache True to fetch from cache, false to load fresh * @param {String} fields Requested fields. * @param {String} table_filter Optional. Return tables with names that contain this value * @param {Long} table_limit Optional. Return tables up to the table_limit * * GET /connections/{connection_name}/tables -> ByteArray */ @JvmOverloads fun connection_tables( connection_name: String, database: String? = null, schema_name: String? = null, cache: Boolean? = null, fields: String? = null, table_filter: String? = null, table_limit: Long? = null ) : SDKResponse { val path_connection_name = encodeParam(connection_name) return this.get<ByteArray>("/connections/${path_connection_name}/tables", mapOf("database" to database, "schema_name" to schema_name, "cache" to cache, "fields" to fields, "table_filter" to table_filter, "table_limit" to table_limit)) } /** * ### Get the columns (and therefore also the tables) in a specific schema * * @param {String} connection_name Name of connection * @param {String} database For dialects that support multiple databases, optionally identify which to use * @param {String} schema_name Name of schema to use. * @param {Boolean} cache True to fetch from cache, false to load fresh * @param {Long} table_limit limits the tables per schema returned * @param {String} table_names only fetch columns for a given (comma-separated) list of tables * @param {String} fields Requested fields. * * GET /connections/{connection_name}/columns -> ByteArray */ @JvmOverloads fun connection_columns( connection_name: String, database: String? = null, schema_name: String? = null, cache: Boolean? = null, table_limit: Long? = null, table_names: String? = null, fields: String? = null ) : SDKResponse { val path_connection_name = encodeParam(connection_name) return this.get<ByteArray>("/connections/${path_connection_name}/columns", mapOf("database" to database, "schema_name" to schema_name, "cache" to cache, "table_limit" to table_limit, "table_names" to table_names, "fields" to fields)) } /** * ### Search a connection for columns matching the specified name * * **Note**: `column_name` must be a valid column name. It is not a search pattern. * * @param {String} connection_name Name of connection * @param {String} column_name Column name to find * @param {String} fields Requested fields. * * GET /connections/{connection_name}/search_columns -> ByteArray */ @JvmOverloads fun connection_search_columns( connection_name: String, column_name: String? = null, fields: String? = null ) : SDKResponse { val path_connection_name = encodeParam(connection_name) return this.get<ByteArray>("/connections/${path_connection_name}/search_columns", mapOf("column_name" to column_name, "fields" to fields)) } /** * ### Connection cost estimating * * Assign a `sql` statement to the body of the request. e.g., for Ruby, `{sql: 'select * from users'}` * * **Note**: If the connection's dialect has no support for cost estimates, an error will be returned * * @param {String} connection_name Name of connection * @param {CreateCostEstimate} body WARNING: no writeable properties found for POST, PUT, or PATCH * @param {String} fields Requested fields. * * POST /connections/{connection_name}/cost_estimate -> ByteArray */ @JvmOverloads fun connection_cost_estimate( connection_name: String, body: CreateCostEstimate, fields: String? = null ) : SDKResponse { val path_connection_name = encodeParam(connection_name) return this.post<ByteArray>("/connections/${path_connection_name}/cost_estimate", mapOf("fields" to fields), body) } //endregion Metadata: Connection Metadata Features //region Project: Manage Projects /** * ### Generate Lockfile for All LookML Dependencies * * Git must have been configured, must be in dev mode and deploy permission required * * Install_all is a two step process * 1. For each remote_dependency in a project the dependency manager will resolve any ambiguous ref. * 2. The project will then write out a lockfile including each remote_dependency with its resolved ref. * * @param {String} project_id Id of project * @param {String} fields Requested fields * * POST /projects/{project_id}/manifest/lock_all -> ByteArray */ @JvmOverloads fun lock_all( project_id: String, fields: String? = null ) : SDKResponse { val path_project_id = encodeParam(project_id) return this.post<ByteArray>("/projects/${path_project_id}/manifest/lock_all", mapOf("fields" to fields)) } /** * ### Get All Git Branches * * Returns a list of git branches in the project repository * * @param {String} project_id Project Id * * GET /projects/{project_id}/git_branches -> ByteArray */ fun all_git_branches( project_id: String ) : SDKResponse { val path_project_id = encodeParam(project_id) return this.get<ByteArray>("/projects/${path_project_id}/git_branches", mapOf()) } /** * ### Get the Current Git Branch * * Returns the git branch currently checked out in the given project repository * * @param {String} project_id Project Id * * GET /projects/{project_id}/git_branch -> ByteArray */ fun git_branch( project_id: String ) : SDKResponse { val path_project_id = encodeParam(project_id) return this.get<ByteArray>("/projects/${path_project_id}/git_branch", mapOf()) } /** * ### Checkout and/or reset --hard an existing Git Branch * * Only allowed in development mode * - Call `update_session` to select the 'dev' workspace. * * Checkout an existing branch if name field is different from the name of the currently checked out branch. * * Optionally specify a branch name, tag name or commit SHA to which the branch should be reset. * **DANGER** hard reset will be force pushed to the remote. Unsaved changes and commits may be permanently lost. * * @param {String} project_id Project Id * @param {WriteGitBranch} body * * PUT /projects/{project_id}/git_branch -> ByteArray */ fun update_git_branch( project_id: String, body: WriteGitBranch ) : SDKResponse { val path_project_id = encodeParam(project_id) return this.put<ByteArray>("/projects/${path_project_id}/git_branch", mapOf(), body) } /** * ### Create and Checkout a Git Branch * * Creates and checks out a new branch in the given project repository * Only allowed in development mode * - Call `update_session` to select the 'dev' workspace. * * Optionally specify a branch name, tag name or commit SHA as the start point in the ref field. * If no ref is specified, HEAD of the current branch will be used as the start point for the new branch. * * @param {String} project_id Project Id * @param {WriteGitBranch} body * * POST /projects/{project_id}/git_branch -> ByteArray */ fun create_git_branch( project_id: String, body: WriteGitBranch ) : SDKResponse { val path_project_id = encodeParam(project_id) return this.post<ByteArray>("/projects/${path_project_id}/git_branch", mapOf(), body) } /** * ### Get the specified Git Branch * * Returns the git branch specified in branch_name path param if it exists in the given project repository * * @param {String} project_id Project Id * @param {String} branch_name Branch Name * * GET /projects/{project_id}/git_branch/{branch_name} -> ByteArray */ fun find_git_branch( project_id: String, branch_name: String ) : SDKResponse { val path_project_id = encodeParam(project_id) val path_branch_name = encodeParam(branch_name) return this.get<ByteArray>("/projects/${path_project_id}/git_branch/${path_branch_name}", mapOf()) } /** * ### Delete the specified Git Branch * * Delete git branch specified in branch_name path param from local and remote of specified project repository * * @param {String} project_id Project Id * @param {String} branch_name Branch Name * * DELETE /projects/{project_id}/git_branch/{branch_name} -> ByteArray */ fun delete_git_branch( project_id: String, branch_name: String ) : SDKResponse { val path_project_id = encodeParam(project_id) val path_branch_name = encodeParam(branch_name) return this.delete<ByteArray>("/projects/${path_project_id}/git_branch/${path_branch_name}", mapOf()) } /** * ### Deploy a Remote Branch or Ref to Production * * Git must have been configured and deploy permission required. * * Deploy is a one/two step process * 1. If this is the first deploy of this project, create the production project with git repository. * 2. Pull the branch or ref into the production project. * * Can only specify either a branch or a ref. * * @param {String} project_id Id of project * @param {String} branch Branch to deploy to production * @param {String} ref Ref to deploy to production * * POST /projects/{project_id}/deploy_ref_to_production -> ByteArray */ @JvmOverloads fun deploy_ref_to_production( project_id: String, branch: String? = null, ref: String? = null ) : SDKResponse { val path_project_id = encodeParam(project_id) return this.post<ByteArray>("/projects/${path_project_id}/deploy_ref_to_production", mapOf("branch" to branch, "ref" to ref)) } /** * ### Deploy LookML from this Development Mode Project to Production * * Git must have been configured, must be in dev mode and deploy permission required * * Deploy is a two / three step process: * * 1. Push commits in current branch of dev mode project to the production branch (origin/master). * Note a. This step is skipped in read-only projects. * Note b. If this step is unsuccessful for any reason (e.g. rejected non-fastforward because production branch has * commits not in current branch), subsequent steps will be skipped. * 2. If this is the first deploy of this project, create the production project with git repository. * 3. Pull the production branch into the production project. * * @param {String} project_id Id of project * * POST /projects/{project_id}/deploy_to_production -> ByteArray */ fun deploy_to_production( project_id: String ) : SDKResponse { val path_project_id = encodeParam(project_id) return this.post<ByteArray>("/projects/${path_project_id}/deploy_to_production", mapOf()) } /** * ### Reset a project to the revision of the project that is in production. * * **DANGER** this will delete any changes that have not been pushed to a remote repository. * * @param {String} project_id Id of project * * POST /projects/{project_id}/reset_to_production -> ByteArray */ fun reset_project_to_production( project_id: String ) : SDKResponse { val path_project_id = encodeParam(project_id) return this.post<ByteArray>("/projects/${path_project_id}/reset_to_production", mapOf()) } /** * ### Reset a project development branch to the revision of the project that is on the remote. * * **DANGER** this will delete any changes that have not been pushed to a remote repository. * * @param {String} project_id Id of project * * POST /projects/{project_id}/reset_to_remote -> ByteArray */ fun reset_project_to_remote( project_id: String ) : SDKResponse { val path_project_id = encodeParam(project_id) return this.post<ByteArray>("/projects/${path_project_id}/reset_to_remote", mapOf()) } /** * ### Get All Projects * * Returns all projects visible to the current user * * @param {String} fields Requested fields * * GET /projects -> ByteArray */ @JvmOverloads fun all_projects( fields: String? = null ) : SDKResponse { return this.get<ByteArray>("/projects", mapOf("fields" to fields)) } /** * ### Create A Project * * dev mode required. * - Call `update_session` to select the 'dev' workspace. * * `name` is required. * `git_remote_url` is not allowed. To configure Git for the newly created project, follow the instructions in `update_project`. * * @param {WriteProject} body * * POST /projects -> ByteArray */ fun create_project( body: WriteProject ) : SDKResponse { return this.post<ByteArray>("/projects", mapOf(), body) } /** * ### Get A Project * * Returns the project with the given project id * * @param {String} project_id Project Id * @param {String} fields Requested fields * * GET /projects/{project_id} -> ByteArray */ @JvmOverloads fun project( project_id: String, fields: String? = null ) : SDKResponse { val path_project_id = encodeParam(project_id) return this.get<ByteArray>("/projects/${path_project_id}", mapOf("fields" to fields)) } /** * ### Update Project Configuration * * Apply changes to a project's configuration. * * * #### Configuring Git for a Project * * To set up a Looker project with a remote git repository, follow these steps: * * 1. Call `update_session` to select the 'dev' workspace. * 1. Call `create_git_deploy_key` to create a new deploy key for the project * 1. Copy the deploy key text into the remote git repository's ssh key configuration * 1. Call `update_project` to set project's `git_remote_url` ()and `git_service_name`, if necessary). * * When you modify a project's `git_remote_url`, Looker connects to the remote repository to fetch * metadata. The remote git repository MUST be configured with the Looker-generated deploy * key for this project prior to setting the project's `git_remote_url`. * * To set up a Looker project with a git repository residing on the Looker server (a 'bare' git repo): * * 1. Call `update_session` to select the 'dev' workspace. * 1. Call `update_project` setting `git_remote_url` to null and `git_service_name` to "bare". * * @param {String} project_id Project Id * @param {WriteProject} body * @param {String} fields Requested fields * * PATCH /projects/{project_id} -> ByteArray */ @JvmOverloads fun update_project( project_id: String, body: WriteProject, fields: String? = null ) : SDKResponse { val path_project_id = encodeParam(project_id) return this.patch<ByteArray>("/projects/${path_project_id}", mapOf("fields" to fields), body) } /** * ### Get A Projects Manifest object * * Returns the project with the given project id * * @param {String} project_id Project Id * * GET /projects/{project_id}/manifest -> ByteArray */ fun manifest( project_id: String ) : SDKResponse { val path_project_id = encodeParam(project_id) return this.get<ByteArray>("/projects/${path_project_id}/manifest", mapOf()) } /** * ### Git Deploy Key * * Returns the ssh public key previously created for a project's git repository. * * @param {String} project_id Project Id * * GET /projects/{project_id}/git/deploy_key -> ByteArray */ fun git_deploy_key( project_id: String ) : SDKResponse { val path_project_id = encodeParam(project_id) return this.get<ByteArray>("/projects/${path_project_id}/git/deploy_key", mapOf()) } /** * ### Create Git Deploy Key * * Create a public/private key pair for authenticating ssh git requests from Looker to a remote git repository * for a particular Looker project. * * Returns the public key of the generated ssh key pair. * * Copy this public key to your remote git repository's ssh keys configuration so that the remote git service can * validate and accept git requests from the Looker server. * * @param {String} project_id Project Id * * POST /projects/{project_id}/git/deploy_key -> ByteArray */ fun create_git_deploy_key( project_id: String ) : SDKResponse { val path_project_id = encodeParam(project_id) return this.post<ByteArray>("/projects/${path_project_id}/git/deploy_key", mapOf()) } /** * ### Get Cached Project Validation Results * * Returns the cached results of a previous project validation calculation, if any. * Returns http status 204 No Content if no validation results exist. * * Validating the content of all the files in a project can be computationally intensive * for large projects. Use this API to simply fetch the results of the most recent * project validation rather than revalidating the entire project from scratch. * * A value of `"stale": true` in the response indicates that the project has changed since * the cached validation results were computed. The cached validation results may no longer * reflect the current state of the project. * * @param {String} project_id Project Id * @param {String} fields Requested fields * * GET /projects/{project_id}/validate -> ByteArray */ @JvmOverloads fun project_validation_results( project_id: String, fields: String? = null ) : SDKResponse { val path_project_id = encodeParam(project_id) return this.get<ByteArray>("/projects/${path_project_id}/validate", mapOf("fields" to fields)) } /** * ### Validate Project * * Performs lint validation of all lookml files in the project. * Returns a list of errors found, if any. * * Validating the content of all the files in a project can be computationally intensive * for large projects. For best performance, call `validate_project(project_id)` only * when you really want to recompute project validation. To quickly display the results of * the most recent project validation (without recomputing), use `project_validation_results(project_id)` * * @param {String} project_id Project Id * @param {String} fields Requested fields * * POST /projects/{project_id}/validate -> ByteArray */ @JvmOverloads fun validate_project( project_id: String, fields: String? = null ) : SDKResponse { val path_project_id = encodeParam(project_id) return this.post<ByteArray>("/projects/${path_project_id}/validate", mapOf("fields" to fields)) } /** * ### Get Project Workspace * * Returns information about the state of the project files in the currently selected workspace * * @param {String} project_id Project Id * @param {String} fields Requested fields * * GET /projects/{project_id}/current_workspace -> ByteArray */ @JvmOverloads fun project_workspace( project_id: String, fields: String? = null ) : SDKResponse { val path_project_id = encodeParam(project_id) return this.get<ByteArray>("/projects/${path_project_id}/current_workspace", mapOf("fields" to fields)) } /** * ### Get All Project Files * * Returns a list of the files in the project * * @param {String} project_id Project Id * @param {String} fields Requested fields * * GET /projects/{project_id}/files -> ByteArray */ @JvmOverloads fun all_project_files( project_id: String, fields: String? = null ) : SDKResponse { val path_project_id = encodeParam(project_id) return this.get<ByteArray>("/projects/${path_project_id}/files", mapOf("fields" to fields)) } /** * ### Get Project File Info * * Returns information about a file in the project * * @param {String} project_id Project Id * @param {String} file_id File Id * @param {String} fields Requested fields * * GET /projects/{project_id}/files/file -> ByteArray */ @JvmOverloads fun project_file( project_id: String, file_id: String, fields: String? = null ) : SDKResponse { val path_project_id = encodeParam(project_id) return this.get<ByteArray>("/projects/${path_project_id}/files/file", mapOf("file_id" to file_id, "fields" to fields)) } /** * ### Get All Git Connection Tests * * dev mode required. * - Call `update_session` to select the 'dev' workspace. * * Returns a list of tests which can be run against a project's (or the dependency project for the provided remote_url) git connection. Call [Run Git Connection Test](#!/Project/run_git_connection_test) to execute each test in sequence. * * Tests are ordered by increasing specificity. Tests should be run in the order returned because later tests require functionality tested by tests earlier in the test list. * * For example, a late-stage test for write access is meaningless if connecting to the git server (an early test) is failing. * * @param {String} project_id Project Id * @param {String} remote_url (Optional: leave blank for root project) The remote url for remote dependency to test. * * GET /projects/{project_id}/git_connection_tests -> ByteArray */ @JvmOverloads fun all_git_connection_tests( project_id: String, remote_url: String? = null ) : SDKResponse { val path_project_id = encodeParam(project_id) return this.get<ByteArray>("/projects/${path_project_id}/git_connection_tests", mapOf("remote_url" to remote_url)) } /** * ### Run a git connection test * * Run the named test on the git service used by this project (or the dependency project for the provided remote_url) and return the result. This * is intended to help debug git connections when things do not work properly, to give * more helpful information about why a git url is not working with Looker. * * Tests should be run in the order they are returned by [Get All Git Connection Tests](#!/Project/all_git_connection_tests). * * @param {String} project_id Project Id * @param {String} test_id Test Id * @param {String} remote_url (Optional: leave blank for root project) The remote url for remote dependency to test. * @param {String} use_production (Optional: leave blank for dev credentials) Whether to use git production credentials. * * GET /projects/{project_id}/git_connection_tests/{test_id} -> ByteArray */ @JvmOverloads fun run_git_connection_test( project_id: String, test_id: String, remote_url: String? = null, use_production: String? = null ) : SDKResponse { val path_project_id = encodeParam(project_id) val path_test_id = encodeParam(test_id) return this.get<ByteArray>("/projects/${path_project_id}/git_connection_tests/${path_test_id}", mapOf("remote_url" to remote_url, "use_production" to use_production)) } /** * ### Get All LookML Tests * * Returns a list of tests which can be run to validate a project's LookML code and/or the underlying data, * optionally filtered by the file id. * Call [Run LookML Test](#!/Project/run_lookml_test) to execute tests. * * @param {String} project_id Project Id * @param {String} file_id File Id * * GET /projects/{project_id}/lookml_tests -> ByteArray */ @JvmOverloads fun all_lookml_tests( project_id: String, file_id: String? = null ) : SDKResponse { val path_project_id = encodeParam(project_id) return this.get<ByteArray>("/projects/${path_project_id}/lookml_tests", mapOf("file_id" to file_id)) } /** * ### Run LookML Tests * * Runs all tests in the project, optionally filtered by file, test, and/or model. * * @param {String} project_id Project Id * @param {String} file_id File Name * @param {String} test Test Name * @param {String} model Model Name * * GET /projects/{project_id}/lookml_tests/run -> ByteArray */ @JvmOverloads fun run_lookml_test( project_id: String, file_id: String? = null, test: String? = null, model: String? = null ) : SDKResponse { val path_project_id = encodeParam(project_id) return this.get<ByteArray>("/projects/${path_project_id}/lookml_tests/run", mapOf("file_id" to file_id, "test" to test, "model" to model)) } /** * ### Creates a tag for the most recent commit, or a specific ref is a SHA is provided * * This is an internal-only, undocumented route. * * @param {String} project_id Project Id * @param {WriteProject} body * @param {String} commit_sha (Optional): Commit Sha to Tag * @param {String} tag_name Tag Name * @param {String} tag_message (Optional): Tag Message * * POST /projects/{project_id}/tag -> ByteArray */ @JvmOverloads fun tag_ref( project_id: String, body: WriteProject, commit_sha: String? = null, tag_name: String? = null, tag_message: String? = null ) : SDKResponse { val path_project_id = encodeParam(project_id) return this.post<ByteArray>("/projects/${path_project_id}/tag", mapOf("commit_sha" to commit_sha, "tag_name" to tag_name, "tag_message" to tag_message), body) } /** * ### Configure Repository Credential for a remote dependency * * Admin required. * * `root_project_id` is required. * `credential_id` is required. * * @param {String} root_project_id Root Project Id * @param {String} credential_id Credential Id * @param {WriteRepositoryCredential} body * * PUT /projects/{root_project_id}/credential/{credential_id} -> ByteArray */ fun update_repository_credential( root_project_id: String, credential_id: String, body: WriteRepositoryCredential ) : SDKResponse { val path_root_project_id = encodeParam(root_project_id) val path_credential_id = encodeParam(credential_id) return this.put<ByteArray>("/projects/${path_root_project_id}/credential/${path_credential_id}", mapOf(), body) } /** * ### Repository Credential for a remote dependency * * Admin required. * * `root_project_id` is required. * `credential_id` is required. * * @param {String} root_project_id Root Project Id * @param {String} credential_id Credential Id * * DELETE /projects/{root_project_id}/credential/{credential_id} -> ByteArray */ fun delete_repository_credential( root_project_id: String, credential_id: String ) : SDKResponse { val path_root_project_id = encodeParam(root_project_id) val path_credential_id = encodeParam(credential_id) return this.delete<ByteArray>("/projects/${path_root_project_id}/credential/${path_credential_id}", mapOf()) } /** * ### Get all Repository Credentials for a project * * `root_project_id` is required. * * @param {String} root_project_id Root Project Id * * GET /projects/{root_project_id}/credentials -> ByteArray */ fun get_all_repository_credentials( root_project_id: String ) : SDKResponse { val path_root_project_id = encodeParam(root_project_id) return this.get<ByteArray>("/projects/${path_root_project_id}/credentials", mapOf()) } //endregion Project: Manage Projects //region Query: Run and Manage Queries /** * ### Create an async query task * * Creates a query task (job) to run a previously created query asynchronously. Returns a Query Task ID. * * Use [query_task(query_task_id)](#!/Query/query_task) to check the execution status of the query task. * After the query task status reaches "Complete", use [query_task_results(query_task_id)](#!/Query/query_task_results) to fetch the results of the query. * * @param {WriteCreateQueryTask} body * @param {Long} limit Row limit (may override the limit in the saved query). * @param {Boolean} apply_formatting Apply model-specified formatting to each result. * @param {Boolean} apply_vis Apply visualization options to results. * @param {Boolean} cache Get results from cache if available. * @param {Boolean} generate_drill_links Generate drill links (only applicable to 'json_detail' format. * @param {Boolean} force_production Force use of production models even if the user is in development mode. Note that this flag being false does not guarantee development models will be used. * @param {Boolean} cache_only Retrieve any results from cache even if the results have expired. * @param {String} path_prefix Prefix to use for drill links (url encoded). * @param {Boolean} rebuild_pdts Rebuild PDTS used in query. * @param {Boolean} server_table_calcs Perform table calculations on query results * @param {Long} image_width DEPRECATED. Render width for image formats. Note that this parameter is always ignored by this method. * @param {Long} image_height DEPRECATED. Render height for image formats. Note that this parameter is always ignored by this method. * @param {String} fields Requested fields * * POST /query_tasks -> ByteArray */ @JvmOverloads fun create_query_task( body: WriteCreateQueryTask, limit: Long? = null, apply_formatting: Boolean? = null, apply_vis: Boolean? = null, cache: Boolean? = null, generate_drill_links: Boolean? = null, force_production: Boolean? = null, cache_only: Boolean? = null, path_prefix: String? = null, rebuild_pdts: Boolean? = null, server_table_calcs: Boolean? = null, image_width: Long? = null, image_height: Long? = null, fields: String? = null ) : SDKResponse { return this.post<ByteArray>("/query_tasks", mapOf("limit" to limit, "apply_formatting" to apply_formatting, "apply_vis" to apply_vis, "cache" to cache, "generate_drill_links" to generate_drill_links, "force_production" to force_production, "cache_only" to cache_only, "path_prefix" to path_prefix, "rebuild_pdts" to rebuild_pdts, "server_table_calcs" to server_table_calcs, "image_width" to image_width, "image_height" to image_height, "fields" to fields), body) } /** * ### Fetch results of multiple async queries * * Returns the results of multiple async queries in one request. * * For Query Tasks that are not completed, the response will include the execution status of the Query Task but will not include query results. * Query Tasks whose results have expired will have a status of 'expired'. * If the user making the API request does not have sufficient privileges to view a Query Task result, the result will have a status of 'missing' * * @param {DelimArray<String>} query_task_ids List of Query Task IDs * * GET /query_tasks/multi_results -> ByteArray */ fun query_task_multi_results( query_task_ids: DelimArray<String> ) : SDKResponse { return this.get<ByteArray>("/query_tasks/multi_results", mapOf("query_task_ids" to query_task_ids)) } /** * ### Get Query Task details * * Use this function to check the status of an async query task. After the status * reaches "Complete", you can call [query_task_results(query_task_id)](#!/Query/query_task_results) to * retrieve the results of the query. * * Use [create_query_task()](#!/Query/create_query_task) to create an async query task. * * @param {String} query_task_id ID of the Query Task * @param {String} fields Requested fields. * * GET /query_tasks/{query_task_id} -> ByteArray */ @JvmOverloads fun query_task( query_task_id: String, fields: String? = null ) : SDKResponse { val path_query_task_id = encodeParam(query_task_id) return this.get<ByteArray>("/query_tasks/${path_query_task_id}", mapOf("fields" to fields)) } /** * ### Get Async Query Results * * Returns the results of an async query task if the query has completed. * * If the query task is still running or waiting to run, this function returns 204 No Content. * * If the query task ID is invalid or the cached results of the query task have expired, this function returns 404 Not Found. * * Use [query_task(query_task_id)](#!/Query/query_task) to check the execution status of the query task * Call query_task_results only after the query task status reaches "Complete". * * You can also use [query_task_multi_results()](#!/Query/query_task_multi_results) retrieve the * results of multiple async query tasks at the same time. * * #### SQL Error Handling: * If the query fails due to a SQL db error, how this is communicated depends on the result_format you requested in `create_query_task()`. * * For `json_detail` result_format: `query_task_results()` will respond with HTTP status '200 OK' and db SQL error info * will be in the `errors` property of the response object. The 'data' property will be empty. * * For all other result formats: `query_task_results()` will respond with HTTP status `400 Bad Request` and some db SQL error info * will be in the message of the 400 error response, but not as detailed as expressed in `json_detail.errors`. * These data formats can only carry row data, and error info is not row data. * * @param {String} query_task_id ID of the Query Task * * GET /query_tasks/{query_task_id}/results -> ByteArray */ fun query_task_results( query_task_id: String ) : SDKResponse { val path_query_task_id = encodeParam(query_task_id) return this.get<ByteArray>("/query_tasks/${path_query_task_id}/results", mapOf()) } /** * ### Get a previously created query by id. * * A Looker query object includes the various parameters that define a database query that has been run or * could be run in the future. These parameters include: model, view, fields, filters, pivots, etc. * Query *results* are not part of the query object. * * Query objects are unique and immutable. Query objects are created automatically in Looker as users explore data. * Looker does not delete them; they become part of the query history. When asked to create a query for * any given set of parameters, Looker will first try to find an existing query object with matching * parameters and will only create a new object when an appropriate object can not be found. * * This 'get' method is used to get the details about a query for a given id. See the other methods here * to 'create' and 'run' queries. * * Note that some fields like 'filter_config' and 'vis_config' etc are specific to how the Looker UI * builds queries and visualizations and are not generally useful for API use. They are not required when * creating new queries and can usually just be ignored. * * @param {String} query_id Id of query * @param {String} fields Requested fields. * * GET /queries/{query_id} -> ByteArray */ @JvmOverloads fun query( query_id: String, fields: String? = null ) : SDKResponse { val path_query_id = encodeParam(query_id) return this.get<ByteArray>("/queries/${path_query_id}", mapOf("fields" to fields)) } /** * ### Get the query for a given query slug. * * This returns the query for the 'slug' in a query share URL. * * The 'slug' is a randomly chosen short string that is used as an alternative to the query's id value * for use in URLs etc. This method exists as a convenience to help you use the API to 'find' queries that * have been created using the Looker UI. * * You can use the Looker explore page to build a query and then choose the 'Share' option to * show the share url for the query. Share urls generally look something like 'https://looker.yourcompany/x/vwGSbfc'. * The trailing 'vwGSbfc' is the share slug. You can pass that string to this api method to get details about the query. * Those details include the 'id' that you can use to run the query. Or, you can copy the query body * (perhaps with your own modification) and use that as the basis to make/run new queries. * * This will also work with slugs from Looker explore urls like * 'https://looker.yourcompany/explore/ecommerce/orders?qid=aogBgL6o3cKK1jN3RoZl5s'. In this case * 'aogBgL6o3cKK1jN3RoZl5s' is the slug. * * @param {String} slug Slug of query * @param {String} fields Requested fields. * * GET /queries/slug/{slug} -> ByteArray */ @JvmOverloads fun query_for_slug( slug: String, fields: String? = null ) : SDKResponse { val path_slug = encodeParam(slug) return this.get<ByteArray>("/queries/slug/${path_slug}", mapOf("fields" to fields)) } /** * ### Create a query. * * This allows you to create a new query that you can later run. Looker queries are immutable once created * and are not deleted. If you create a query that is exactly like an existing query then the existing query * will be returned and no new query will be created. Whether a new query is created or not, you can use * the 'id' in the returned query with the 'run' method. * * The query parameters are passed as json in the body of the request. * * @param {WriteQuery} body * @param {String} fields Requested fields. * * POST /queries -> ByteArray */ @JvmOverloads fun create_query( body: WriteQuery, fields: String? = null ) : SDKResponse { return this.post<ByteArray>("/queries", mapOf("fields" to fields), body) } /** * ### Run a saved query. * * This runs a previously saved query. You can use this on a query that was generated in the Looker UI * or one that you have explicitly created using the API. You can also use a query 'id' from a saved 'Look'. * * The 'result_format' parameter specifies the desired structure and format of the response. * * Supported formats: * * | result_format | Description * | :-----------: | :--- | * | json | Plain json * | json_detail | Row data plus metadata describing the fields, pivots, table calcs, and other aspects of the query * | csv | Comma separated values with a header * | txt | Tab separated values with a header * | html | Simple html * | md | Simple markdown * | xlsx | MS Excel spreadsheet * | sql | Returns the generated SQL rather than running the query * | png | A PNG image of the visualization of the query * | jpg | A JPG image of the visualization of the query * * @param {String} query_id Id of query * @param {String} result_format Format of result * @param {Long} limit Row limit (may override the limit in the saved query). * @param {Boolean} apply_formatting Apply model-specified formatting to each result. * @param {Boolean} apply_vis Apply visualization options to results. * @param {Boolean} cache Get results from cache if available. * @param {Long} image_width Render width for image formats. * @param {Long} image_height Render height for image formats. * @param {Boolean} generate_drill_links Generate drill links (only applicable to 'json_detail' format. * @param {Boolean} force_production Force use of production models even if the user is in development mode. Note that this flag being false does not guarantee development models will be used. * @param {Boolean} cache_only Retrieve any results from cache even if the results have expired. * @param {String} path_prefix Prefix to use for drill links (url encoded). * @param {Boolean} rebuild_pdts Rebuild PDTS used in query. * @param {Boolean} server_table_calcs Perform table calculations on query results * @param {String} source Specifies the source of this call. * * GET /queries/{query_id}/run/{result_format} -> ByteArray * * **Note**: Binary content may be returned by this method. */ @JvmOverloads fun run_query( query_id: String, result_format: String, limit: Long? = null, apply_formatting: Boolean? = null, apply_vis: Boolean? = null, cache: Boolean? = null, image_width: Long? = null, image_height: Long? = null, generate_drill_links: Boolean? = null, force_production: Boolean? = null, cache_only: Boolean? = null, path_prefix: String? = null, rebuild_pdts: Boolean? = null, server_table_calcs: Boolean? = null, source: String? = null ) : SDKResponse { val path_query_id = encodeParam(query_id) val path_result_format = encodeParam(result_format) return this.get<ByteArray>("/queries/${path_query_id}/run/${path_result_format}", mapOf("limit" to limit, "apply_formatting" to apply_formatting, "apply_vis" to apply_vis, "cache" to cache, "image_width" to image_width, "image_height" to image_height, "generate_drill_links" to generate_drill_links, "force_production" to force_production, "cache_only" to cache_only, "path_prefix" to path_prefix, "rebuild_pdts" to rebuild_pdts, "server_table_calcs" to server_table_calcs, "source" to source)) } /** * ### Run the query that is specified inline in the posted body. * * This allows running a query as defined in json in the posted body. This combines * the two actions of posting & running a query into one step. * * Here is an example body in json: * ``` * { * "model":"thelook", * "view":"inventory_items", * "fields":["category.name","inventory_items.days_in_inventory_tier","products.count"], * "filters":{"category.name":"socks"}, * "sorts":["products.count desc 0"], * "limit":"500", * "query_timezone":"America/Los_Angeles" * } * ``` * * When using the Ruby SDK this would be passed as a Ruby hash like: * ``` * { * :model=>"thelook", * :view=>"inventory_items", * :fields=> * ["category.name", * "inventory_items.days_in_inventory_tier", * "products.count"], * :filters=>{:"category.name"=>"socks"}, * :sorts=>["products.count desc 0"], * :limit=>"500", * :query_timezone=>"America/Los_Angeles", * } * ``` * * This will return the result of running the query in the format specified by the 'result_format' parameter. * * Supported formats: * * | result_format | Description * | :-----------: | :--- | * | json | Plain json * | json_detail | Row data plus metadata describing the fields, pivots, table calcs, and other aspects of the query * | csv | Comma separated values with a header * | txt | Tab separated values with a header * | html | Simple html * | md | Simple markdown * | xlsx | MS Excel spreadsheet * | sql | Returns the generated SQL rather than running the query * | png | A PNG image of the visualization of the query * | jpg | A JPG image of the visualization of the query * * @param {String} result_format Format of result * @param {WriteQuery} body * @param {Long} limit Row limit (may override the limit in the saved query). * @param {Boolean} apply_formatting Apply model-specified formatting to each result. * @param {Boolean} apply_vis Apply visualization options to results. * @param {Boolean} cache Get results from cache if available. * @param {Long} image_width Render width for image formats. * @param {Long} image_height Render height for image formats. * @param {Boolean} generate_drill_links Generate drill links (only applicable to 'json_detail' format. * @param {Boolean} force_production Force use of production models even if the user is in development mode. Note that this flag being false does not guarantee development models will be used. * @param {Boolean} cache_only Retrieve any results from cache even if the results have expired. * @param {String} path_prefix Prefix to use for drill links (url encoded). * @param {Boolean} rebuild_pdts Rebuild PDTS used in query. * @param {Boolean} server_table_calcs Perform table calculations on query results * * POST /queries/run/{result_format} -> ByteArray * * **Note**: Binary content may be returned by this method. */ @JvmOverloads fun run_inline_query( result_format: String, body: WriteQuery, limit: Long? = null, apply_formatting: Boolean? = null, apply_vis: Boolean? = null, cache: Boolean? = null, image_width: Long? = null, image_height: Long? = null, generate_drill_links: Boolean? = null, force_production: Boolean? = null, cache_only: Boolean? = null, path_prefix: String? = null, rebuild_pdts: Boolean? = null, server_table_calcs: Boolean? = null ) : SDKResponse { val path_result_format = encodeParam(result_format) return this.post<ByteArray>("/queries/run/${path_result_format}", mapOf("limit" to limit, "apply_formatting" to apply_formatting, "apply_vis" to apply_vis, "cache" to cache, "image_width" to image_width, "image_height" to image_height, "generate_drill_links" to generate_drill_links, "force_production" to force_production, "cache_only" to cache_only, "path_prefix" to path_prefix, "rebuild_pdts" to rebuild_pdts, "server_table_calcs" to server_table_calcs), body) } /** * ### Run an URL encoded query. * * This requires the caller to encode the specifiers for the query into the URL query part using * Looker-specific syntax as explained below. * * Generally, you would want to use one of the methods that takes the parameters as json in the POST body * for creating and/or running queries. This method exists for cases where one really needs to encode the * parameters into the URL of a single 'GET' request. This matches the way that the Looker UI formats * 'explore' URLs etc. * * The parameters here are very similar to the json body formatting except that the filter syntax is * tricky. Unfortunately, this format makes this method not currently callable via the 'Try it out!' button * in this documentation page. But, this is callable when creating URLs manually or when using the Looker SDK. * * Here is an example inline query URL: * * ``` * https://looker.mycompany.com:19999/api/3.0/queries/models/thelook/views/inventory_items/run/json?fields=category.name,inventory_items.days_in_inventory_tier,products.count&f[category.name]=socks&sorts=products.count+desc+0&limit=500&query_timezone=America/Los_Angeles * ``` * * When invoking this endpoint with the Ruby SDK, pass the query parameter parts as a hash. The hash to match the above would look like: * * ```ruby * query_params = * { * fields: "category.name,inventory_items.days_in_inventory_tier,products.count", * :"f[category.name]" => "socks", * sorts: "products.count desc 0", * limit: "500", * query_timezone: "America/Los_Angeles" * } * response = ruby_sdk.run_url_encoded_query('thelook','inventory_items','json', query_params) * * ``` * * Again, it is generally easier to use the variant of this method that passes the full query in the POST body. * This method is available for cases where other alternatives won't fit the need. * * Supported formats: * * | result_format | Description * | :-----------: | :--- | * | json | Plain json * | json_detail | Row data plus metadata describing the fields, pivots, table calcs, and other aspects of the query * | csv | Comma separated values with a header * | txt | Tab separated values with a header * | html | Simple html * | md | Simple markdown * | xlsx | MS Excel spreadsheet * | sql | Returns the generated SQL rather than running the query * | png | A PNG image of the visualization of the query * | jpg | A JPG image of the visualization of the query * * @param {String} model_name Model name * @param {String} view_name View name * @param {String} result_format Format of result * * GET /queries/models/{model_name}/views/{view_name}/run/{result_format} -> ByteArray * * **Note**: Binary content may be returned by this method. */ fun run_url_encoded_query( model_name: String, view_name: String, result_format: String ) : SDKResponse { val path_model_name = encodeParam(model_name) val path_view_name = encodeParam(view_name) val path_result_format = encodeParam(result_format) return this.get<ByteArray>("/queries/models/${path_model_name}/views/${path_view_name}/run/${path_result_format}", mapOf()) } /** * ### Get Merge Query * * Returns a merge query object given its id. * * @param {String} merge_query_id Merge Query Id * @param {String} fields Requested fields * * GET /merge_queries/{merge_query_id} -> ByteArray */ @JvmOverloads fun merge_query( merge_query_id: String, fields: String? = null ) : SDKResponse { val path_merge_query_id = encodeParam(merge_query_id) return this.get<ByteArray>("/merge_queries/${path_merge_query_id}", mapOf("fields" to fields)) } /** * ### Create Merge Query * * Creates a new merge query object. * * A merge query takes the results of one or more queries and combines (merges) the results * according to field mapping definitions. The result is similar to a SQL left outer join. * * A merge query can merge results of queries from different SQL databases. * * The order that queries are defined in the source_queries array property is significant. The * first query in the array defines the primary key into which the results of subsequent * queries will be merged. * * Like model/view query objects, merge queries are immutable and have structural identity - if * you make a request to create a new merge query that is identical to an existing merge query, * the existing merge query will be returned instead of creating a duplicate. Conversely, any * change to the contents of a merge query will produce a new object with a new id. * * @param {WriteMergeQuery} body * @param {String} fields Requested fields * * POST /merge_queries -> ByteArray */ @JvmOverloads fun create_merge_query( body: WriteMergeQuery? = null, fields: String? = null ) : SDKResponse { return this.post<ByteArray>("/merge_queries", mapOf("fields" to fields), body) } /** * Get information about all running queries. * * GET /running_queries -> ByteArray */ fun all_running_queries( ) : SDKResponse { return this.get<ByteArray>("/running_queries", mapOf()) } /** * Kill a query with a specific query_task_id. * * @param {String} query_task_id Query task id. * * DELETE /running_queries/{query_task_id} -> ByteArray */ fun kill_query( query_task_id: String ) : SDKResponse { val path_query_task_id = encodeParam(query_task_id) return this.delete<ByteArray>("/running_queries/${path_query_task_id}", mapOf()) } /** * Get a SQL Runner query. * * @param {String} slug slug of query * * GET /sql_queries/{slug} -> ByteArray */ fun sql_query( slug: String ) : SDKResponse { val path_slug = encodeParam(slug) return this.get<ByteArray>("/sql_queries/${path_slug}", mapOf()) } /** * ### Create a SQL Runner Query * * Either the `connection_name` or `model_name` parameter MUST be provided. * * @param {SqlQueryCreate} body * * POST /sql_queries -> ByteArray */ fun create_sql_query( body: SqlQueryCreate ) : SDKResponse { return this.post<ByteArray>("/sql_queries", mapOf(), body) } /** * Execute a SQL Runner query in a given result_format. * * @param {String} slug slug of query * @param {String} result_format Format of result, options are: ["inline_json", "json", "json_detail", "json_fe", "csv", "html", "md", "txt", "xlsx", "gsxml", "json_label"] * @param {String} download Defaults to false. If set to true, the HTTP response will have content-disposition and other headers set to make the HTTP response behave as a downloadable attachment instead of as inline content. * * POST /sql_queries/{slug}/run/{result_format} -> ByteArray * * **Note**: Binary content may be returned by this method. */ @JvmOverloads fun run_sql_query( slug: String, result_format: String, download: String? = null ) : SDKResponse { val path_slug = encodeParam(slug) val path_result_format = encodeParam(result_format) return this.post<ByteArray>("/sql_queries/${path_slug}/run/${path_result_format}", mapOf("download" to download)) } //endregion Query: Run and Manage Queries //region RenderTask: Manage Render Tasks /** * ### Create a new task to render a look to an image. * * Returns a render task object. * To check the status of a render task, pass the render_task.id to [Get Render Task](#!/RenderTask/get_render_task). * Once the render task is complete, you can download the resulting document or image using [Get Render Task Results](#!/RenderTask/get_render_task_results). * * @param {String} look_id Id of look to render * @param {String} result_format Output type: png, or jpg * @param {Long} width Output width in pixels * @param {Long} height Output height in pixels * @param {String} fields Requested fields. * * POST /render_tasks/looks/{look_id}/{result_format} -> ByteArray */ @JvmOverloads fun create_look_render_task( look_id: String, result_format: String, width: Long, height: Long, fields: String? = null ) : SDKResponse { val path_look_id = encodeParam(look_id) val path_result_format = encodeParam(result_format) return this.post<ByteArray>("/render_tasks/looks/${path_look_id}/${path_result_format}", mapOf("width" to width, "height" to height, "fields" to fields)) } /** * ### Create a new task to render an existing query to an image. * * Returns a render task object. * To check the status of a render task, pass the render_task.id to [Get Render Task](#!/RenderTask/get_render_task). * Once the render task is complete, you can download the resulting document or image using [Get Render Task Results](#!/RenderTask/get_render_task_results). * * @param {String} query_id Id of the query to render * @param {String} result_format Output type: png or jpg * @param {Long} width Output width in pixels * @param {Long} height Output height in pixels * @param {String} fields Requested fields. * * POST /render_tasks/queries/{query_id}/{result_format} -> ByteArray */ @JvmOverloads fun create_query_render_task( query_id: String, result_format: String, width: Long, height: Long, fields: String? = null ) : SDKResponse { val path_query_id = encodeParam(query_id) val path_result_format = encodeParam(result_format) return this.post<ByteArray>("/render_tasks/queries/${path_query_id}/${path_result_format}", mapOf("width" to width, "height" to height, "fields" to fields)) } /** * ### Create a new task to render a dashboard to a document or image. * * Returns a render task object. * To check the status of a render task, pass the render_task.id to [Get Render Task](#!/RenderTask/get_render_task). * Once the render task is complete, you can download the resulting document or image using [Get Render Task Results](#!/RenderTask/get_render_task_results). * * @param {String} dashboard_id Id of dashboard to render. The ID can be a LookML dashboard also. * @param {String} result_format Output type: pdf, png, or jpg * @param {CreateDashboardRenderTask} body * @param {Long} width Output width in pixels * @param {Long} height Output height in pixels * @param {String} fields Requested fields. * @param {String} pdf_paper_size Paper size for pdf. Value can be one of: ["letter","legal","tabloid","a0","a1","a2","a3","a4","a5"] * @param {Boolean} pdf_landscape Whether to render pdf in landscape paper orientation * @param {Boolean} long_tables Whether or not to expand table vis to full length * * POST /render_tasks/dashboards/{dashboard_id}/{result_format} -> ByteArray */ @JvmOverloads fun create_dashboard_render_task( dashboard_id: String, result_format: String, body: CreateDashboardRenderTask, width: Long, height: Long, fields: String? = null, pdf_paper_size: String? = null, pdf_landscape: Boolean? = null, long_tables: Boolean? = null ) : SDKResponse { val path_dashboard_id = encodeParam(dashboard_id) val path_result_format = encodeParam(result_format) return this.post<ByteArray>("/render_tasks/dashboards/${path_dashboard_id}/${path_result_format}", mapOf("width" to width, "height" to height, "fields" to fields, "pdf_paper_size" to pdf_paper_size, "pdf_landscape" to pdf_landscape, "long_tables" to long_tables), body) } /** * ### Get information about a render task. * * Returns a render task object. * To check the status of a render task, pass the render_task.id to [Get Render Task](#!/RenderTask/get_render_task). * Once the render task is complete, you can download the resulting document or image using [Get Render Task Results](#!/RenderTask/get_render_task_results). * * @param {String} render_task_id Id of render task * @param {String} fields Requested fields. * * GET /render_tasks/{render_task_id} -> ByteArray */ @JvmOverloads fun render_task( render_task_id: String, fields: String? = null ) : SDKResponse { val path_render_task_id = encodeParam(render_task_id) return this.get<ByteArray>("/render_tasks/${path_render_task_id}", mapOf("fields" to fields)) } /** * ### Get the document or image produced by a completed render task. * * Note that the PDF or image result will be a binary blob in the HTTP response, as indicated by the * Content-Type in the response headers. This may require specialized (or at least different) handling than text * responses such as JSON. You may need to tell your HTTP client that the response is binary so that it does not * attempt to parse the binary data as text. * * If the render task exists but has not finished rendering the results, the response HTTP status will be * **202 Accepted**, the response body will be empty, and the response will have a Retry-After header indicating * that the caller should repeat the request at a later time. * * Returns 404 if the render task cannot be found, if the cached result has expired, or if the caller * does not have permission to view the results. * * For detailed information about the status of the render task, use [Render Task](#!/RenderTask/render_task). * Polling loops waiting for completion of a render task would be better served by polling **render_task(id)** until * the task status reaches completion (or error) instead of polling **render_task_results(id)** alone. * * @param {String} render_task_id Id of render task * * GET /render_tasks/{render_task_id}/results -> ByteArray * * **Note**: Binary content is returned by this method. */ fun render_task_results( render_task_id: String ) : SDKResponse { val path_render_task_id = encodeParam(render_task_id) return this.get<ByteArray>("/render_tasks/${path_render_task_id}/results", mapOf()) } /** * ### Create a new task to render a dashboard element to an image. * * Returns a render task object. * To check the status of a render task, pass the render_task.id to [Get Render Task](#!/RenderTask/get_render_task). * Once the render task is complete, you can download the resulting document or image using [Get Render Task Results](#!/RenderTask/get_render_task_results). * * @param {String} dashboard_element_id Id of dashboard element to render: UDD dashboard element would be numeric and LookML dashboard element would be model_name::dashboard_title::lookml_link_id * @param {String} result_format Output type: png or jpg * @param {Long} width Output width in pixels * @param {Long} height Output height in pixels * @param {String} fields Requested fields. * * POST /render_tasks/dashboard_elements/{dashboard_element_id}/{result_format} -> ByteArray */ @JvmOverloads fun create_dashboard_element_render_task( dashboard_element_id: String, result_format: String, width: Long, height: Long, fields: String? = null ) : SDKResponse { val path_dashboard_element_id = encodeParam(dashboard_element_id) val path_result_format = encodeParam(result_format) return this.post<ByteArray>("/render_tasks/dashboard_elements/${path_dashboard_element_id}/${path_result_format}", mapOf("width" to width, "height" to height, "fields" to fields)) } //endregion RenderTask: Manage Render Tasks //region Role: Manage Roles /** * ### Search model sets * Returns all model set records that match the given search criteria. * If multiple search params are given and `filter_or` is FALSE or not specified, * search params are combined in a logical AND operation. * Only rows that match *all* search param criteria will be returned. * * If `filter_or` is TRUE, multiple search params are combined in a logical OR operation. * Results will include rows that match **any** of the search criteria. * * String search params use case-insensitive matching. * String search params can contain `%` and '_' as SQL LIKE pattern match wildcard expressions. * example="dan%" will match "danger" and "Danzig" but not "David" * example="D_m%" will match "Damage" and "dump" * * Integer search params can accept a single value or a comma separated list of values. The multiple * values will be combined under a logical OR operation - results will match at least one of * the given values. * * Most search params can accept "IS NULL" and "NOT NULL" as special expressions to match * or exclude (respectively) rows where the column is null. * * Boolean search params accept only "true" and "false" as values. * * @param {String} fields Requested fields. * @param {Long} limit Number of results to return (used with `offset`). * @param {Long} offset Number of results to skip before returning any (used with `limit`). * @param {String} sorts Fields to sort by. * @param {String} id Match model set id. * @param {String} name Match model set name. * @param {Boolean} all_access Match model sets by all_access status. * @param {Boolean} built_in Match model sets by built_in status. * @param {Boolean} filter_or Combine given search criteria in a boolean OR expression. * * GET /model_sets/search -> ByteArray */ @JvmOverloads fun search_model_sets( fields: String? = null, limit: Long? = null, offset: Long? = null, sorts: String? = null, id: String? = null, name: String? = null, all_access: Boolean? = null, built_in: Boolean? = null, filter_or: Boolean? = null ) : SDKResponse { return this.get<ByteArray>("/model_sets/search", mapOf("fields" to fields, "limit" to limit, "offset" to offset, "sorts" to sorts, "id" to id, "name" to name, "all_access" to all_access, "built_in" to built_in, "filter_or" to filter_or)) } /** * ### Get information about the model set with a specific id. * * @param {String} model_set_id Id of model set * @param {String} fields Requested fields. * * GET /model_sets/{model_set_id} -> ByteArray */ @JvmOverloads fun model_set( model_set_id: String, fields: String? = null ) : SDKResponse { val path_model_set_id = encodeParam(model_set_id) return this.get<ByteArray>("/model_sets/${path_model_set_id}", mapOf("fields" to fields)) } /** * ### Update information about the model set with a specific id. * * @param {String} model_set_id id of model set * @param {WriteModelSet} body * * PATCH /model_sets/{model_set_id} -> ByteArray */ fun update_model_set( model_set_id: String, body: WriteModelSet ) : SDKResponse { val path_model_set_id = encodeParam(model_set_id) return this.patch<ByteArray>("/model_sets/${path_model_set_id}", mapOf(), body) } /** * ### Delete the model set with a specific id. * * @param {String} model_set_id id of model set * * DELETE /model_sets/{model_set_id} -> ByteArray */ fun delete_model_set( model_set_id: String ) : SDKResponse { val path_model_set_id = encodeParam(model_set_id) return this.delete<ByteArray>("/model_sets/${path_model_set_id}", mapOf()) } /** * ### Get information about all model sets. * * @param {String} fields Requested fields. * * GET /model_sets -> ByteArray */ @JvmOverloads fun all_model_sets( fields: String? = null ) : SDKResponse { return this.get<ByteArray>("/model_sets", mapOf("fields" to fields)) } /** * ### Create a model set with the specified information. Model sets are used by Roles. * * @param {WriteModelSet} body * * POST /model_sets -> ByteArray */ fun create_model_set( body: WriteModelSet ) : SDKResponse { return this.post<ByteArray>("/model_sets", mapOf(), body) } /** * ### Get all supported permissions. * * GET /permissions -> ByteArray */ fun all_permissions( ) : SDKResponse { return this.get<ByteArray>("/permissions", mapOf()) } /** * ### Search permission sets * Returns all permission set records that match the given search criteria. * If multiple search params are given and `filter_or` is FALSE or not specified, * search params are combined in a logical AND operation. * Only rows that match *all* search param criteria will be returned. * * If `filter_or` is TRUE, multiple search params are combined in a logical OR operation. * Results will include rows that match **any** of the search criteria. * * String search params use case-insensitive matching. * String search params can contain `%` and '_' as SQL LIKE pattern match wildcard expressions. * example="dan%" will match "danger" and "Danzig" but not "David" * example="D_m%" will match "Damage" and "dump" * * Integer search params can accept a single value or a comma separated list of values. The multiple * values will be combined under a logical OR operation - results will match at least one of * the given values. * * Most search params can accept "IS NULL" and "NOT NULL" as special expressions to match * or exclude (respectively) rows where the column is null. * * Boolean search params accept only "true" and "false" as values. * * @param {String} fields Requested fields. * @param {Long} limit Number of results to return (used with `offset`). * @param {Long} offset Number of results to skip before returning any (used with `limit`). * @param {String} sorts Fields to sort by. * @param {String} id Match permission set id. * @param {String} name Match permission set name. * @param {Boolean} all_access Match permission sets by all_access status. * @param {Boolean} built_in Match permission sets by built_in status. * @param {Boolean} filter_or Combine given search criteria in a boolean OR expression. * * GET /permission_sets/search -> ByteArray */ @JvmOverloads fun search_permission_sets( fields: String? = null, limit: Long? = null, offset: Long? = null, sorts: String? = null, id: String? = null, name: String? = null, all_access: Boolean? = null, built_in: Boolean? = null, filter_or: Boolean? = null ) : SDKResponse { return this.get<ByteArray>("/permission_sets/search", mapOf("fields" to fields, "limit" to limit, "offset" to offset, "sorts" to sorts, "id" to id, "name" to name, "all_access" to all_access, "built_in" to built_in, "filter_or" to filter_or)) } /** * ### Get information about the permission set with a specific id. * * @param {String} permission_set_id Id of permission set * @param {String} fields Requested fields. * * GET /permission_sets/{permission_set_id} -> ByteArray */ @JvmOverloads fun permission_set( permission_set_id: String, fields: String? = null ) : SDKResponse { val path_permission_set_id = encodeParam(permission_set_id) return this.get<ByteArray>("/permission_sets/${path_permission_set_id}", mapOf("fields" to fields)) } /** * ### Update information about the permission set with a specific id. * * @param {String} permission_set_id Id of permission set * @param {WritePermissionSet} body * * PATCH /permission_sets/{permission_set_id} -> ByteArray */ fun update_permission_set( permission_set_id: String, body: WritePermissionSet ) : SDKResponse { val path_permission_set_id = encodeParam(permission_set_id) return this.patch<ByteArray>("/permission_sets/${path_permission_set_id}", mapOf(), body) } /** * ### Delete the permission set with a specific id. * * @param {String} permission_set_id Id of permission set * * DELETE /permission_sets/{permission_set_id} -> ByteArray */ fun delete_permission_set( permission_set_id: String ) : SDKResponse { val path_permission_set_id = encodeParam(permission_set_id) return this.delete<ByteArray>("/permission_sets/${path_permission_set_id}", mapOf()) } /** * ### Get information about all permission sets. * * @param {String} fields Requested fields. * * GET /permission_sets -> ByteArray */ @JvmOverloads fun all_permission_sets( fields: String? = null ) : SDKResponse { return this.get<ByteArray>("/permission_sets", mapOf("fields" to fields)) } /** * ### Create a permission set with the specified information. Permission sets are used by Roles. * * @param {WritePermissionSet} body * * POST /permission_sets -> ByteArray */ fun create_permission_set( body: WritePermissionSet ) : SDKResponse { return this.post<ByteArray>("/permission_sets", mapOf(), body) } /** * ### Get information about all roles. * * @param {String} fields Requested fields. * @param {DelimArray<String>} ids Optional list of ids to get specific roles. * * GET /roles -> ByteArray */ @JvmOverloads fun all_roles( fields: String? = null, ids: DelimArray<String>? = null ) : SDKResponse { return this.get<ByteArray>("/roles", mapOf("fields" to fields, "ids" to ids)) } /** * ### Create a role with the specified information. * * @param {WriteRole} body * * POST /roles -> ByteArray */ fun create_role( body: WriteRole ) : SDKResponse { return this.post<ByteArray>("/roles", mapOf(), body) } /** * ### Search roles * * Returns all role records that match the given search criteria. * * If multiple search params are given and `filter_or` is FALSE or not specified, * search params are combined in a logical AND operation. * Only rows that match *all* search param criteria will be returned. * * If `filter_or` is TRUE, multiple search params are combined in a logical OR operation. * Results will include rows that match **any** of the search criteria. * * String search params use case-insensitive matching. * String search params can contain `%` and '_' as SQL LIKE pattern match wildcard expressions. * example="dan%" will match "danger" and "Danzig" but not "David" * example="D_m%" will match "Damage" and "dump" * * Integer search params can accept a single value or a comma separated list of values. The multiple * values will be combined under a logical OR operation - results will match at least one of * the given values. * * Most search params can accept "IS NULL" and "NOT NULL" as special expressions to match * or exclude (respectively) rows where the column is null. * * Boolean search params accept only "true" and "false" as values. * * @param {String} fields Requested fields. * @param {Long} limit Number of results to return (used with `offset`). * @param {Long} offset Number of results to skip before returning any (used with `limit`). * @param {String} sorts Fields to sort by. * @param {String} id Match role id. * @param {String} name Match role name. * @param {Boolean} built_in Match roles by built_in status. * @param {Boolean} filter_or Combine given search criteria in a boolean OR expression. * * GET /roles/search -> ByteArray */ @JvmOverloads fun search_roles( fields: String? = null, limit: Long? = null, offset: Long? = null, sorts: String? = null, id: String? = null, name: String? = null, built_in: Boolean? = null, filter_or: Boolean? = null ) : SDKResponse { return this.get<ByteArray>("/roles/search", mapOf("fields" to fields, "limit" to limit, "offset" to offset, "sorts" to sorts, "id" to id, "name" to name, "built_in" to built_in, "filter_or" to filter_or)) } /** * ### Search roles include user count * * Returns all role records that match the given search criteria, and attaches * associated user counts. * * If multiple search params are given and `filter_or` is FALSE or not specified, * search params are combined in a logical AND operation. * Only rows that match *all* search param criteria will be returned. * * If `filter_or` is TRUE, multiple search params are combined in a logical OR operation. * Results will include rows that match **any** of the search criteria. * * String search params use case-insensitive matching. * String search params can contain `%` and '_' as SQL LIKE pattern match wildcard expressions. * example="dan%" will match "danger" and "Danzig" but not "David" * example="D_m%" will match "Damage" and "dump" * * Integer search params can accept a single value or a comma separated list of values. The multiple * values will be combined under a logical OR operation - results will match at least one of * the given values. * * Most search params can accept "IS NULL" and "NOT NULL" as special expressions to match * or exclude (respectively) rows where the column is null. * * Boolean search params accept only "true" and "false" as values. * * @param {String} fields Requested fields. * @param {Long} limit Number of results to return (used with `offset`). * @param {Long} offset Number of results to skip before returning any (used with `limit`). * @param {String} sorts Fields to sort by. * @param {String} id Match role id. * @param {String} name Match role name. * @param {Boolean} built_in Match roles by built_in status. * @param {Boolean} filter_or Combine given search criteria in a boolean OR expression. * * GET /roles/search/with_user_count -> ByteArray */ @JvmOverloads fun search_roles_with_user_count( fields: String? = null, limit: Long? = null, offset: Long? = null, sorts: String? = null, id: String? = null, name: String? = null, built_in: Boolean? = null, filter_or: Boolean? = null ) : SDKResponse { return this.get<ByteArray>("/roles/search/with_user_count", mapOf("fields" to fields, "limit" to limit, "offset" to offset, "sorts" to sorts, "id" to id, "name" to name, "built_in" to built_in, "filter_or" to filter_or)) } /** * ### Get information about the role with a specific id. * * @param {String} role_id id of role * * GET /roles/{role_id} -> ByteArray */ fun role( role_id: String ) : SDKResponse { val path_role_id = encodeParam(role_id) return this.get<ByteArray>("/roles/${path_role_id}", mapOf()) } /** * ### Update information about the role with a specific id. * * @param {String} role_id id of role * @param {WriteRole} body * * PATCH /roles/{role_id} -> ByteArray */ fun update_role( role_id: String, body: WriteRole ) : SDKResponse { val path_role_id = encodeParam(role_id) return this.patch<ByteArray>("/roles/${path_role_id}", mapOf(), body) } /** * ### Delete the role with a specific id. * * @param {String} role_id id of role * * DELETE /roles/{role_id} -> ByteArray */ fun delete_role( role_id: String ) : SDKResponse { val path_role_id = encodeParam(role_id) return this.delete<ByteArray>("/roles/${path_role_id}", mapOf()) } /** * ### Get information about all the groups with the role that has a specific id. * * @param {String} role_id id of role * @param {String} fields Requested fields. * * GET /roles/{role_id}/groups -> ByteArray */ @JvmOverloads fun role_groups( role_id: String, fields: String? = null ) : SDKResponse { val path_role_id = encodeParam(role_id) return this.get<ByteArray>("/roles/${path_role_id}/groups", mapOf("fields" to fields)) } /** * ### Set all groups for a role, removing all existing group associations from that role. * * @param {String} role_id id of role * @param {Array<String>} body * * PUT /roles/{role_id}/groups -> ByteArray */ fun set_role_groups( role_id: String, body: Array<String> ) : SDKResponse { val path_role_id = encodeParam(role_id) return this.put<ByteArray>("/roles/${path_role_id}/groups", mapOf(), body) } /** * ### Get information about all the users with the role that has a specific id. * * @param {String} role_id id of role * @param {String} fields Requested fields. * @param {Boolean} direct_association_only Get only users associated directly with the role: exclude those only associated through groups. * * GET /roles/{role_id}/users -> ByteArray */ @JvmOverloads fun role_users( role_id: String, fields: String? = null, direct_association_only: Boolean? = null ) : SDKResponse { val path_role_id = encodeParam(role_id) return this.get<ByteArray>("/roles/${path_role_id}/users", mapOf("fields" to fields, "direct_association_only" to direct_association_only)) } /** * ### Set all the users of the role with a specific id. * * @param {String} role_id id of role * @param {Array<String>} body * * PUT /roles/{role_id}/users -> ByteArray */ fun set_role_users( role_id: String, body: Array<String> ) : SDKResponse { val path_role_id = encodeParam(role_id) return this.put<ByteArray>("/roles/${path_role_id}/users", mapOf(), body) } //endregion Role: Manage Roles //region ScheduledPlan: Manage Scheduled Plans /** * ### Get Scheduled Plans for a Space * * Returns scheduled plans owned by the caller for a given space id. * * @param {String} space_id Space Id * @param {String} fields Requested fields. * * GET /scheduled_plans/space/{space_id} -> ByteArray */ @JvmOverloads fun scheduled_plans_for_space( space_id: String, fields: String? = null ) : SDKResponse { val path_space_id = encodeParam(space_id) return this.get<ByteArray>("/scheduled_plans/space/${path_space_id}", mapOf("fields" to fields)) } /** * ### Get Information About a Scheduled Plan * * Admins can fetch information about other users' Scheduled Plans. * * @param {String} scheduled_plan_id Scheduled Plan Id * @param {String} fields Requested fields. * * GET /scheduled_plans/{scheduled_plan_id} -> ByteArray */ @JvmOverloads fun scheduled_plan( scheduled_plan_id: String, fields: String? = null ) : SDKResponse { val path_scheduled_plan_id = encodeParam(scheduled_plan_id) return this.get<ByteArray>("/scheduled_plans/${path_scheduled_plan_id}", mapOf("fields" to fields)) } /** * ### Update a Scheduled Plan * * Admins can update other users' Scheduled Plans. * * Note: Any scheduled plan destinations specified in an update will **replace** all scheduled plan destinations * currently defined for the scheduled plan. * * For Example: If a scheduled plan has destinations A, B, and C, and you call update on this scheduled plan * specifying only B in the destinations, then destinations A and C will be deleted by the update. * * Updating a scheduled plan to assign null or an empty array to the scheduled_plan_destinations property is an error, as a scheduled plan must always have at least one destination. * * If you omit the scheduled_plan_destinations property from the object passed to update, then the destinations * defined on the original scheduled plan will remain unchanged. * * #### Email Permissions: * * For details about permissions required to schedule delivery to email and the safeguards * Looker offers to protect against sending to unauthorized email destinations, see [Email Domain Whitelist for Scheduled Looks](https://docs.looker.com/r/api/embed-permissions). * * * #### Scheduled Plan Destination Formats * * Scheduled plan destinations must specify the data format to produce and send to the destination. * * Formats: * * | format | Description * | :-----------: | :--- | * | json | A JSON object containing a `data` property which contains an array of JSON objects, one per row. No metadata. * | json_detail | Row data plus metadata describing the fields, pivots, table calcs, and other aspects of the query * | inline_json | Same as the JSON format, except that the `data` property is a string containing JSON-escaped row data. Additional properties describe the data operation. This format is primarily used to send data to web hooks so that the web hook doesn't have to re-encode the JSON row data in order to pass it on to its ultimate destination. * | csv | Comma separated values with a header * | txt | Tab separated values with a header * | html | Simple html * | xlsx | MS Excel spreadsheet * | wysiwyg_pdf | Dashboard rendered in a tiled layout to produce a PDF document * | assembled_pdf | Dashboard rendered in a single column layout to produce a PDF document * | wysiwyg_png | Dashboard rendered in a tiled layout to produce a PNG image * || * * Valid formats vary by destination type and source object. `wysiwyg_pdf` is only valid for dashboards, for example. * * @param {String} scheduled_plan_id Scheduled Plan Id * @param {WriteScheduledPlan} body * * PATCH /scheduled_plans/{scheduled_plan_id} -> ByteArray */ fun update_scheduled_plan( scheduled_plan_id: String, body: WriteScheduledPlan ) : SDKResponse { val path_scheduled_plan_id = encodeParam(scheduled_plan_id) return this.patch<ByteArray>("/scheduled_plans/${path_scheduled_plan_id}", mapOf(), body) } /** * ### Delete a Scheduled Plan * * Normal users can only delete their own scheduled plans. * Admins can delete other users' scheduled plans. * This delete cannot be undone. * * @param {String} scheduled_plan_id Scheduled Plan Id * * DELETE /scheduled_plans/{scheduled_plan_id} -> ByteArray */ fun delete_scheduled_plan( scheduled_plan_id: String ) : SDKResponse { val path_scheduled_plan_id = encodeParam(scheduled_plan_id) return this.delete<ByteArray>("/scheduled_plans/${path_scheduled_plan_id}", mapOf()) } /** * ### List All Scheduled Plans * * Returns all scheduled plans which belong to the caller or given user. * * If no user_id is provided, this function returns the scheduled plans owned by the caller. * * * To list all schedules for all users, pass `all_users=true`. * * * The caller must have `see_schedules` permission to see other users' scheduled plans. * * @param {String} user_id Return scheduled plans belonging to this user_id. If not provided, returns scheduled plans owned by the caller. * @param {String} fields Comma delimited list of field names. If provided, only the fields specified will be included in the response * @param {Boolean} all_users Return scheduled plans belonging to all users (caller needs see_schedules permission) * * GET /scheduled_plans -> ByteArray */ @JvmOverloads fun all_scheduled_plans( user_id: String? = null, fields: String? = null, all_users: Boolean? = null ) : SDKResponse { return this.get<ByteArray>("/scheduled_plans", mapOf("user_id" to user_id, "fields" to fields, "all_users" to all_users)) } /** * ### Create a Scheduled Plan * * Create a scheduled plan to render a Look or Dashboard on a recurring schedule. * * To create a scheduled plan, you MUST provide values for the following fields: * `name` * and * `look_id`, `dashboard_id`, `lookml_dashboard_id`, or `query_id` * and * `cron_tab` or `datagroup` * and * at least one scheduled_plan_destination * * A scheduled plan MUST have at least one scheduled_plan_destination defined. * * When `look_id` is set, `require_no_results`, `require_results`, and `require_change` are all required. * * If `create_scheduled_plan` fails with a 422 error, be sure to look at the error messages in the response which will explain exactly what fields are missing or values that are incompatible. * * The queries that provide the data for the look or dashboard are run in the context of user account that owns the scheduled plan. * * When `run_as_recipient` is `false` or not specified, the queries that provide the data for the * look or dashboard are run in the context of user account that owns the scheduled plan. * * When `run_as_recipient` is `true` and all the email recipients are Looker user accounts, the * queries are run in the context of each recipient, so different recipients may see different * data from the same scheduled render of a look or dashboard. For more details, see [Run As Recipient](https://docs.looker.com/r/admin/run-as-recipient). * * Admins can create and modify scheduled plans on behalf of other users by specifying a user id. * Non-admin users may not create or modify scheduled plans by or for other users. * * #### Email Permissions: * * For details about permissions required to schedule delivery to email and the safeguards * Looker offers to protect against sending to unauthorized email destinations, see [Email Domain Whitelist for Scheduled Looks](https://docs.looker.com/r/api/embed-permissions). * * * #### Scheduled Plan Destination Formats * * Scheduled plan destinations must specify the data format to produce and send to the destination. * * Formats: * * | format | Description * | :-----------: | :--- | * | json | A JSON object containing a `data` property which contains an array of JSON objects, one per row. No metadata. * | json_detail | Row data plus metadata describing the fields, pivots, table calcs, and other aspects of the query * | inline_json | Same as the JSON format, except that the `data` property is a string containing JSON-escaped row data. Additional properties describe the data operation. This format is primarily used to send data to web hooks so that the web hook doesn't have to re-encode the JSON row data in order to pass it on to its ultimate destination. * | csv | Comma separated values with a header * | txt | Tab separated values with a header * | html | Simple html * | xlsx | MS Excel spreadsheet * | wysiwyg_pdf | Dashboard rendered in a tiled layout to produce a PDF document * | assembled_pdf | Dashboard rendered in a single column layout to produce a PDF document * | wysiwyg_png | Dashboard rendered in a tiled layout to produce a PNG image * || * * Valid formats vary by destination type and source object. `wysiwyg_pdf` is only valid for dashboards, for example. * * @param {WriteScheduledPlan} body * * POST /scheduled_plans -> ByteArray */ fun create_scheduled_plan( body: WriteScheduledPlan ) : SDKResponse { return this.post<ByteArray>("/scheduled_plans", mapOf(), body) } /** * ### Run a Scheduled Plan Immediately * * Create a scheduled plan that runs only once, and immediately. * * This can be useful for testing a Scheduled Plan before committing to a production schedule. * * Admins can create scheduled plans on behalf of other users by specifying a user id. * * This API is rate limited to prevent it from being used for relay spam or DoS attacks * * #### Email Permissions: * * For details about permissions required to schedule delivery to email and the safeguards * Looker offers to protect against sending to unauthorized email destinations, see [Email Domain Whitelist for Scheduled Looks](https://docs.looker.com/r/api/embed-permissions). * * * #### Scheduled Plan Destination Formats * * Scheduled plan destinations must specify the data format to produce and send to the destination. * * Formats: * * | format | Description * | :-----------: | :--- | * | json | A JSON object containing a `data` property which contains an array of JSON objects, one per row. No metadata. * | json_detail | Row data plus metadata describing the fields, pivots, table calcs, and other aspects of the query * | inline_json | Same as the JSON format, except that the `data` property is a string containing JSON-escaped row data. Additional properties describe the data operation. This format is primarily used to send data to web hooks so that the web hook doesn't have to re-encode the JSON row data in order to pass it on to its ultimate destination. * | csv | Comma separated values with a header * | txt | Tab separated values with a header * | html | Simple html * | xlsx | MS Excel spreadsheet * | wysiwyg_pdf | Dashboard rendered in a tiled layout to produce a PDF document * | assembled_pdf | Dashboard rendered in a single column layout to produce a PDF document * | wysiwyg_png | Dashboard rendered in a tiled layout to produce a PNG image * || * * Valid formats vary by destination type and source object. `wysiwyg_pdf` is only valid for dashboards, for example. * * @param {WriteScheduledPlan} body * * POST /scheduled_plans/run_once -> ByteArray */ fun scheduled_plan_run_once( body: WriteScheduledPlan ) : SDKResponse { return this.post<ByteArray>("/scheduled_plans/run_once", mapOf(), body) } /** * ### Get Scheduled Plans for a Look * * Returns all scheduled plans for a look which belong to the caller or given user. * * If no user_id is provided, this function returns the scheduled plans owned by the caller. * * * To list all schedules for all users, pass `all_users=true`. * * * The caller must have `see_schedules` permission to see other users' scheduled plans. * * @param {String} look_id Look Id * @param {String} user_id User Id (default is requesting user if not specified) * @param {String} fields Requested fields. * @param {Boolean} all_users Return scheduled plans belonging to all users for the look * * GET /scheduled_plans/look/{look_id} -> ByteArray */ @JvmOverloads fun scheduled_plans_for_look( look_id: String, user_id: String? = null, fields: String? = null, all_users: Boolean? = null ) : SDKResponse { val path_look_id = encodeParam(look_id) return this.get<ByteArray>("/scheduled_plans/look/${path_look_id}", mapOf("user_id" to user_id, "fields" to fields, "all_users" to all_users)) } /** * ### Get Scheduled Plans for a Dashboard * * Returns all scheduled plans for a dashboard which belong to the caller or given user. * * If no user_id is provided, this function returns the scheduled plans owned by the caller. * * * To list all schedules for all users, pass `all_users=true`. * * * The caller must have `see_schedules` permission to see other users' scheduled plans. * * @param {String} dashboard_id Dashboard Id * @param {String} user_id User Id (default is requesting user if not specified) * @param {Boolean} all_users Return scheduled plans belonging to all users for the dashboard * @param {String} fields Requested fields. * * GET /scheduled_plans/dashboard/{dashboard_id} -> ByteArray */ @JvmOverloads fun scheduled_plans_for_dashboard( dashboard_id: String, user_id: String? = null, all_users: Boolean? = null, fields: String? = null ) : SDKResponse { val path_dashboard_id = encodeParam(dashboard_id) return this.get<ByteArray>("/scheduled_plans/dashboard/${path_dashboard_id}", mapOf("user_id" to user_id, "all_users" to all_users, "fields" to fields)) } /** * ### Get Scheduled Plans for a LookML Dashboard * * Returns all scheduled plans for a LookML Dashboard which belong to the caller or given user. * * If no user_id is provided, this function returns the scheduled plans owned by the caller. * * * To list all schedules for all users, pass `all_users=true`. * * * The caller must have `see_schedules` permission to see other users' scheduled plans. * * @param {String} lookml_dashboard_id LookML Dashboard Id * @param {String} user_id User Id (default is requesting user if not specified) * @param {String} fields Requested fields. * @param {Boolean} all_users Return scheduled plans belonging to all users for the dashboard * * GET /scheduled_plans/lookml_dashboard/{lookml_dashboard_id} -> ByteArray */ @JvmOverloads fun scheduled_plans_for_lookml_dashboard( lookml_dashboard_id: String, user_id: String? = null, fields: String? = null, all_users: Boolean? = null ) : SDKResponse { val path_lookml_dashboard_id = encodeParam(lookml_dashboard_id) return this.get<ByteArray>("/scheduled_plans/lookml_dashboard/${path_lookml_dashboard_id}", mapOf("user_id" to user_id, "fields" to fields, "all_users" to all_users)) } /** * ### Run a Scheduled Plan By Id Immediately * This function creates a run-once schedule plan based on an existing scheduled plan, * applies modifications (if any) to the new scheduled plan, and runs the new schedule plan immediately. * This can be useful for testing modifications to an existing scheduled plan before committing to a production schedule. * * This function internally performs the following operations: * * 1. Copies the properties of the existing scheduled plan into a new scheduled plan * 2. Copies any properties passed in the JSON body of this request into the new scheduled plan (replacing the original values) * 3. Creates the new scheduled plan * 4. Runs the new scheduled plan * * The original scheduled plan is not modified by this operation. * Admins can create, modify, and run scheduled plans on behalf of other users by specifying a user id. * Non-admins can only create, modify, and run their own scheduled plans. * * #### Email Permissions: * * For details about permissions required to schedule delivery to email and the safeguards * Looker offers to protect against sending to unauthorized email destinations, see [Email Domain Whitelist for Scheduled Looks](https://docs.looker.com/r/api/embed-permissions). * * * #### Scheduled Plan Destination Formats * * Scheduled plan destinations must specify the data format to produce and send to the destination. * * Formats: * * | format | Description * | :-----------: | :--- | * | json | A JSON object containing a `data` property which contains an array of JSON objects, one per row. No metadata. * | json_detail | Row data plus metadata describing the fields, pivots, table calcs, and other aspects of the query * | inline_json | Same as the JSON format, except that the `data` property is a string containing JSON-escaped row data. Additional properties describe the data operation. This format is primarily used to send data to web hooks so that the web hook doesn't have to re-encode the JSON row data in order to pass it on to its ultimate destination. * | csv | Comma separated values with a header * | txt | Tab separated values with a header * | html | Simple html * | xlsx | MS Excel spreadsheet * | wysiwyg_pdf | Dashboard rendered in a tiled layout to produce a PDF document * | assembled_pdf | Dashboard rendered in a single column layout to produce a PDF document * | wysiwyg_png | Dashboard rendered in a tiled layout to produce a PNG image * || * * Valid formats vary by destination type and source object. `wysiwyg_pdf` is only valid for dashboards, for example. * * * * This API is rate limited to prevent it from being used for relay spam or DoS attacks * * @param {String} scheduled_plan_id Id of schedule plan to copy and run * @param {WriteScheduledPlan} body * * POST /scheduled_plans/{scheduled_plan_id}/run_once -> ByteArray */ @JvmOverloads fun scheduled_plan_run_once_by_id( scheduled_plan_id: String, body: WriteScheduledPlan? = null ) : SDKResponse { val path_scheduled_plan_id = encodeParam(scheduled_plan_id) return this.post<ByteArray>("/scheduled_plans/${path_scheduled_plan_id}/run_once", mapOf(), body) } //endregion ScheduledPlan: Manage Scheduled Plans //region Session: Session Information /** * ### Get API Session * * Returns information about the current API session, such as which workspace is selected for the session. * * GET /session -> ByteArray */ fun session( ) : SDKResponse { return this.get<ByteArray>("/session", mapOf()) } /** * ### Update API Session * * #### API Session Workspace * * You can use this endpoint to change the active workspace for the current API session. * * Only one workspace can be active in a session. The active workspace can be changed * any number of times in a session. * * The default workspace for API sessions is the "production" workspace. * * All Looker APIs that use projects or lookml models (such as running queries) will * use the version of project and model files defined by this workspace for the lifetime of the * current API session or until the session workspace is changed again. * * An API session has the same lifetime as the access_token used to authenticate API requests. Each successful * API login generates a new access_token and a new API session. * * If your Looker API client application needs to work in a dev workspace across multiple * API sessions, be sure to select the dev workspace after each login. * * @param {WriteApiSession} body * * PATCH /session -> ByteArray */ fun update_session( body: WriteApiSession ) : SDKResponse { return this.patch<ByteArray>("/session", mapOf(), body) } //endregion Session: Session Information //region Theme: Manage Themes /** * ### Get an array of all existing themes * * Get a **single theme** by id with [Theme](#!/Theme/theme) * * This method returns an array of all existing themes. The active time for the theme is not considered. * * **Note**: Custom themes needs to be enabled by Looker. Unless custom themes are enabled, only the automatically generated default theme can be used. Please contact your Account Manager or help.looker.com to update your license for this feature. * * @param {String} fields Requested fields. * * GET /themes -> ByteArray */ @JvmOverloads fun all_themes( fields: String? = null ) : SDKResponse { return this.get<ByteArray>("/themes", mapOf("fields" to fields)) } /** * ### Create a theme * * Creates a new theme object, returning the theme details, including the created id. * * If `settings` are not specified, the default theme settings will be copied into the new theme. * * The theme `name` can only contain alphanumeric characters or underscores. Theme names should not contain any confidential information, such as customer names. * * **Update** an existing theme with [Update Theme](#!/Theme/update_theme) * * **Permanently delete** an existing theme with [Delete Theme](#!/Theme/delete_theme) * * For more information, see [Creating and Applying Themes](https://docs.looker.com/r/admin/themes). * * **Note**: Custom themes needs to be enabled by Looker. Unless custom themes are enabled, only the automatically generated default theme can be used. Please contact your Account Manager or help.looker.com to update your license for this feature. * * @param {WriteTheme} body * * POST /themes -> ByteArray */ fun create_theme( body: WriteTheme ) : SDKResponse { return this.post<ByteArray>("/themes", mapOf(), body) } /** * ### Search all themes for matching criteria. * * Returns an **array of theme objects** that match the specified search criteria. * * | Search Parameters | Description * | :-------------------: | :------ | * | `begin_at` only | Find themes active at or after `begin_at` * | `end_at` only | Find themes active at or before `end_at` * | both set | Find themes with an active inclusive period between `begin_at` and `end_at` * * Note: Range matching requires boolean AND logic. * When using `begin_at` and `end_at` together, do not use `filter_or`=TRUE * * If multiple search params are given and `filter_or` is FALSE or not specified, * search params are combined in a logical AND operation. * Only rows that match *all* search param criteria will be returned. * * If `filter_or` is TRUE, multiple search params are combined in a logical OR operation. * Results will include rows that match **any** of the search criteria. * * String search params use case-insensitive matching. * String search params can contain `%` and '_' as SQL LIKE pattern match wildcard expressions. * example="dan%" will match "danger" and "Danzig" but not "David" * example="D_m%" will match "Damage" and "dump" * * Integer search params can accept a single value or a comma separated list of values. The multiple * values will be combined under a logical OR operation - results will match at least one of * the given values. * * Most search params can accept "IS NULL" and "NOT NULL" as special expressions to match * or exclude (respectively) rows where the column is null. * * Boolean search params accept only "true" and "false" as values. * * * Get a **single theme** by id with [Theme](#!/Theme/theme) * * **Note**: Custom themes needs to be enabled by Looker. Unless custom themes are enabled, only the automatically generated default theme can be used. Please contact your Account Manager or help.looker.com to update your license for this feature. * * @param {String} id Match theme id. * @param {String} name Match theme name. * @param {Date} begin_at Timestamp for activation. * @param {Date} end_at Timestamp for expiration. * @param {Long} limit Number of results to return (used with `offset`). * @param {Long} offset Number of results to skip before returning any (used with `limit`). * @param {String} sorts Fields to sort by. * @param {String} fields Requested fields. * @param {Boolean} filter_or Combine given search criteria in a boolean OR expression * * GET /themes/search -> ByteArray */ @JvmOverloads fun search_themes( id: String? = null, name: String? = null, begin_at: Date? = null, end_at: Date? = null, limit: Long? = null, offset: Long? = null, sorts: String? = null, fields: String? = null, filter_or: Boolean? = null ) : SDKResponse { return this.get<ByteArray>("/themes/search", mapOf("id" to id, "name" to name, "begin_at" to begin_at, "end_at" to end_at, "limit" to limit, "offset" to offset, "sorts" to sorts, "fields" to fields, "filter_or" to filter_or)) } /** * ### Get the default theme * * Returns the active theme object set as the default. * * The **default** theme name can be set in the UI on the Admin|Theme UI page * * The optional `ts` parameter can specify a different timestamp than "now." If specified, it returns the default theme at the time indicated. * * @param {Date} ts Timestamp representing the target datetime for the active period. Defaults to 'now' * * GET /themes/default -> ByteArray */ @JvmOverloads fun default_theme( ts: Date? = null ) : SDKResponse { return this.get<ByteArray>("/themes/default", mapOf("ts" to ts)) } /** * ### Set the global default theme by theme name * * Only Admin users can call this function. * * Only an active theme with no expiration (`end_at` not set) can be assigned as the default theme. As long as a theme has an active record with no expiration, it can be set as the default. * * [Create Theme](#!/Theme/create) has detailed information on rules for default and active themes * * Returns the new specified default theme object. * * **Note**: Custom themes needs to be enabled by Looker. Unless custom themes are enabled, only the automatically generated default theme can be used. Please contact your Account Manager or help.looker.com to update your license for this feature. * * @param {String} name Name of theme to set as default * * PUT /themes/default -> ByteArray */ fun set_default_theme( name: String ) : SDKResponse { return this.put<ByteArray>("/themes/default", mapOf("name" to name)) } /** * ### Get active themes * * Returns an array of active themes. * * If the `name` parameter is specified, it will return an array with one theme if it's active and found. * * The optional `ts` parameter can specify a different timestamp than "now." * * **Note**: Custom themes needs to be enabled by Looker. Unless custom themes are enabled, only the automatically generated default theme can be used. Please contact your Account Manager or help.looker.com to update your license for this feature. * * @param {String} name Name of theme * @param {Date} ts Timestamp representing the target datetime for the active period. Defaults to 'now' * @param {String} fields Requested fields. * * GET /themes/active -> ByteArray */ @JvmOverloads fun active_themes( name: String? = null, ts: Date? = null, fields: String? = null ) : SDKResponse { return this.get<ByteArray>("/themes/active", mapOf("name" to name, "ts" to ts, "fields" to fields)) } /** * ### Get the named theme if it's active. Otherwise, return the default theme * * The optional `ts` parameter can specify a different timestamp than "now." * Note: API users with `show` ability can call this function * * **Note**: Custom themes needs to be enabled by Looker. Unless custom themes are enabled, only the automatically generated default theme can be used. Please contact your Account Manager or help.looker.com to update your license for this feature. * * @param {String} name Name of theme * @param {Date} ts Timestamp representing the target datetime for the active period. Defaults to 'now' * * GET /themes/theme_or_default -> ByteArray */ @JvmOverloads fun theme_or_default( name: String, ts: Date? = null ) : SDKResponse { return this.get<ByteArray>("/themes/theme_or_default", mapOf("name" to name, "ts" to ts)) } /** * ### Validate a theme with the specified information * * Validates all values set for the theme, returning any errors encountered, or 200 OK if valid * * See [Create Theme](#!/Theme/create_theme) for constraints * * **Note**: Custom themes needs to be enabled by Looker. Unless custom themes are enabled, only the automatically generated default theme can be used. Please contact your Account Manager or help.looker.com to update your license for this feature. * * @param {WriteTheme} body * * POST /themes/validate -> ByteArray */ fun validate_theme( body: WriteTheme ) : SDKResponse { return this.post<ByteArray>("/themes/validate", mapOf(), body) } /** * ### Get a theme by ID * * Use this to retrieve a specific theme, whether or not it's currently active. * * **Note**: Custom themes needs to be enabled by Looker. Unless custom themes are enabled, only the automatically generated default theme can be used. Please contact your Account Manager or help.looker.com to update your license for this feature. * * @param {String} theme_id Id of theme * @param {String} fields Requested fields. * * GET /themes/{theme_id} -> ByteArray */ @JvmOverloads fun theme( theme_id: String, fields: String? = null ) : SDKResponse { val path_theme_id = encodeParam(theme_id) return this.get<ByteArray>("/themes/${path_theme_id}", mapOf("fields" to fields)) } /** * ### Update the theme by id. * * **Note**: Custom themes needs to be enabled by Looker. Unless custom themes are enabled, only the automatically generated default theme can be used. Please contact your Account Manager or help.looker.com to update your license for this feature. * * @param {String} theme_id Id of theme * @param {WriteTheme} body * * PATCH /themes/{theme_id} -> ByteArray */ fun update_theme( theme_id: String, body: WriteTheme ) : SDKResponse { val path_theme_id = encodeParam(theme_id) return this.patch<ByteArray>("/themes/${path_theme_id}", mapOf(), body) } /** * ### Delete a specific theme by id * * This operation permanently deletes the identified theme from the database. * * Because multiple themes can have the same name (with different activation time spans) themes can only be deleted by ID. * * All IDs associated with a theme name can be retrieved by searching for the theme name with [Theme Search](#!/Theme/search). * * **Note**: Custom themes needs to be enabled by Looker. Unless custom themes are enabled, only the automatically generated default theme can be used. Please contact your Account Manager or help.looker.com to update your license for this feature. * * @param {String} theme_id Id of theme * * DELETE /themes/{theme_id} -> ByteArray */ fun delete_theme( theme_id: String ) : SDKResponse { val path_theme_id = encodeParam(theme_id) return this.delete<ByteArray>("/themes/${path_theme_id}", mapOf()) } //endregion Theme: Manage Themes //region User: Manage Users /** * ### Search email credentials * * Returns all credentials_email records that match the given search criteria. * * If multiple search params are given and `filter_or` is FALSE or not specified, * search params are combined in a logical AND operation. * Only rows that match *all* search param criteria will be returned. * * If `filter_or` is TRUE, multiple search params are combined in a logical OR operation. * Results will include rows that match **any** of the search criteria. * * String search params use case-insensitive matching. * String search params can contain `%` and '_' as SQL LIKE pattern match wildcard expressions. * example="dan%" will match "danger" and "Danzig" but not "David" * example="D_m%" will match "Damage" and "dump" * * Integer search params can accept a single value or a comma separated list of values. The multiple * values will be combined under a logical OR operation - results will match at least one of * the given values. * * Most search params can accept "IS NULL" and "NOT NULL" as special expressions to match * or exclude (respectively) rows where the column is null. * * Boolean search params accept only "true" and "false" as values. * * @param {String} fields Requested fields. * @param {Long} limit Number of results to return (used with `offset`). * @param {Long} offset Number of results to skip before returning any (used with `limit`). * @param {String} sorts Fields to sort by. * @param {String} id Match credentials_email id. * @param {String} email Match credentials_email email. * @param {String} emails Find credentials_email that match given emails. * @param {Boolean} filter_or Combine given search criteria in a boolean OR expression. * * GET /credentials_email/search -> ByteArray */ @JvmOverloads fun search_credentials_email( fields: String? = null, limit: Long? = null, offset: Long? = null, sorts: String? = null, id: String? = null, email: String? = null, emails: String? = null, filter_or: Boolean? = null ) : SDKResponse { return this.get<ByteArray>("/credentials_email/search", mapOf("fields" to fields, "limit" to limit, "offset" to offset, "sorts" to sorts, "id" to id, "email" to email, "emails" to emails, "filter_or" to filter_or)) } /** * ### Get information about the current user; i.e. the user account currently calling the API. * * @param {String} fields Requested fields. * * GET /user -> ByteArray */ @JvmOverloads fun me( fields: String? = null ) : SDKResponse { return this.get<ByteArray>("/user", mapOf("fields" to fields)) } /** * ### Get information about all users. * * @param {String} fields Requested fields. * @param {Long} page DEPRECATED. Use limit and offset instead. Return only page N of paginated results * @param {Long} per_page DEPRECATED. Use limit and offset instead. Return N rows of data per page * @param {Long} limit Number of results to return. (used with offset and takes priority over page and per_page) * @param {Long} offset Number of results to skip before returning any. (used with limit and takes priority over page and per_page) * @param {String} sorts Fields to sort by. * @param {DelimArray<String>} ids Optional list of ids to get specific users. * * GET /users -> ByteArray */ @JvmOverloads fun all_users( fields: String? = null, page: Long? = null, per_page: Long? = null, limit: Long? = null, offset: Long? = null, sorts: String? = null, ids: DelimArray<String>? = null ) : SDKResponse { return this.get<ByteArray>("/users", mapOf("fields" to fields, "page" to page, "per_page" to per_page, "limit" to limit, "offset" to offset, "sorts" to sorts, "ids" to ids)) } /** * ### Create a user with the specified information. * * @param {WriteUser} body * @param {String} fields Requested fields. * * POST /users -> ByteArray */ @JvmOverloads fun create_user( body: WriteUser? = null, fields: String? = null ) : SDKResponse { return this.post<ByteArray>("/users", mapOf("fields" to fields), body) } /** * ### Search users * * Returns all<sup>*</sup> user records that match the given search criteria. * * If multiple search params are given and `filter_or` is FALSE or not specified, * search params are combined in a logical AND operation. * Only rows that match *all* search param criteria will be returned. * * If `filter_or` is TRUE, multiple search params are combined in a logical OR operation. * Results will include rows that match **any** of the search criteria. * * String search params use case-insensitive matching. * String search params can contain `%` and '_' as SQL LIKE pattern match wildcard expressions. * example="dan%" will match "danger" and "Danzig" but not "David" * example="D_m%" will match "Damage" and "dump" * * Integer search params can accept a single value or a comma separated list of values. The multiple * values will be combined under a logical OR operation - results will match at least one of * the given values. * * Most search params can accept "IS NULL" and "NOT NULL" as special expressions to match * or exclude (respectively) rows where the column is null. * * Boolean search params accept only "true" and "false" as values. * * * (<sup>*</sup>) Results are always filtered to the level of information the caller is permitted to view. * Looker admins can see all user details; normal users in an open system can see * names of other users but no details; normal users in a closed system can only see * names of other users who are members of the same group as the user. * * @param {String} fields Include only these fields in the response * @param {Long} page DEPRECATED. Use limit and offset instead. Return only page N of paginated results * @param {Long} per_page DEPRECATED. Use limit and offset instead. Return N rows of data per page * @param {Long} limit Number of results to return. (used with offset and takes priority over page and per_page) * @param {Long} offset Number of results to skip before returning any. (used with limit and takes priority over page and per_page) * @param {String} sorts Fields to sort by. * @param {String} id Match User Id. * @param {String} first_name Match First name. * @param {String} last_name Match Last name. * @param {Boolean} verified_looker_employee Search for user accounts associated with Looker employees * @param {Boolean} embed_user Search for only embed users * @param {String} email Search for the user with this email address * @param {Boolean} is_disabled Search for disabled user accounts * @param {Boolean} filter_or Combine given search criteria in a boolean OR expression * @param {String} content_metadata_id Search for users who have access to this content_metadata item * @param {String} group_id Search for users who are direct members of this group * * GET /users/search -> ByteArray */ @JvmOverloads fun search_users( fields: String? = null, page: Long? = null, per_page: Long? = null, limit: Long? = null, offset: Long? = null, sorts: String? = null, id: String? = null, first_name: String? = null, last_name: String? = null, verified_looker_employee: Boolean? = null, embed_user: Boolean? = null, email: String? = null, is_disabled: Boolean? = null, filter_or: Boolean? = null, content_metadata_id: String? = null, group_id: String? = null ) : SDKResponse { return this.get<ByteArray>("/users/search", mapOf("fields" to fields, "page" to page, "per_page" to per_page, "limit" to limit, "offset" to offset, "sorts" to sorts, "id" to id, "first_name" to first_name, "last_name" to last_name, "verified_looker_employee" to verified_looker_employee, "embed_user" to embed_user, "email" to email, "is_disabled" to is_disabled, "filter_or" to filter_or, "content_metadata_id" to content_metadata_id, "group_id" to group_id)) } /** * ### Search for user accounts by name * * Returns all user accounts where `first_name` OR `last_name` OR `email` field values match a pattern. * The pattern can contain `%` and `_` wildcards as in SQL LIKE expressions. * * Any additional search params will be combined into a logical AND expression. * * @param {String} pattern Pattern to match * @param {String} fields Include only these fields in the response * @param {Long} page DEPRECATED. Use limit and offset instead. Return only page N of paginated results * @param {Long} per_page DEPRECATED. Use limit and offset instead. Return N rows of data per page * @param {Long} limit Number of results to return. (used with offset and takes priority over page and per_page) * @param {Long} offset Number of results to skip before returning any. (used with limit and takes priority over page and per_page) * @param {String} sorts Fields to sort by * @param {String} id Match User Id * @param {String} first_name Match First name * @param {String} last_name Match Last name * @param {Boolean} verified_looker_employee Match Verified Looker employee * @param {String} email Match Email Address * @param {Boolean} is_disabled Include or exclude disabled accounts in the results * * GET /users/search/names/{pattern} -> ByteArray */ @JvmOverloads fun search_users_names( pattern: String, fields: String? = null, page: Long? = null, per_page: Long? = null, limit: Long? = null, offset: Long? = null, sorts: String? = null, id: String? = null, first_name: String? = null, last_name: String? = null, verified_looker_employee: Boolean? = null, email: String? = null, is_disabled: Boolean? = null ) : SDKResponse { val path_pattern = encodeParam(pattern) return this.get<ByteArray>("/users/search/names/${path_pattern}", mapOf("fields" to fields, "page" to page, "per_page" to per_page, "limit" to limit, "offset" to offset, "sorts" to sorts, "id" to id, "first_name" to first_name, "last_name" to last_name, "verified_looker_employee" to verified_looker_employee, "email" to email, "is_disabled" to is_disabled)) } /** * ### Get information about the user with a specific id. * * If the caller is an admin or the caller is the user being specified, then full user information will * be returned. Otherwise, a minimal 'public' variant of the user information will be returned. This contains * The user name and avatar url, but no sensitive information. * * @param {String} user_id Id of user * @param {String} fields Requested fields. * * GET /users/{user_id} -> ByteArray */ @JvmOverloads fun user( user_id: String, fields: String? = null ) : SDKResponse { val path_user_id = encodeParam(user_id) return this.get<ByteArray>("/users/${path_user_id}", mapOf("fields" to fields)) } /** * ### Update information about the user with a specific id. * * @param {String} user_id Id of user * @param {WriteUser} body * @param {String} fields Requested fields. * * PATCH /users/{user_id} -> ByteArray */ @JvmOverloads fun update_user( user_id: String, body: WriteUser, fields: String? = null ) : SDKResponse { val path_user_id = encodeParam(user_id) return this.patch<ByteArray>("/users/${path_user_id}", mapOf("fields" to fields), body) } /** * ### Delete the user with a specific id. * * **DANGER** this will delete the user and all looks and other information owned by the user. * * @param {String} user_id Id of user * * DELETE /users/{user_id} -> ByteArray */ fun delete_user( user_id: String ) : SDKResponse { val path_user_id = encodeParam(user_id) return this.delete<ByteArray>("/users/${path_user_id}", mapOf()) } /** * ### Get information about the user with a credential of given type with specific id. * * This is used to do things like find users by their embed external_user_id. Or, find the user with * a given api3 client_id, etc. The 'credential_type' matches the 'type' name of the various credential * types. It must be one of the values listed in the table below. The 'credential_id' is your unique Id * for the user and is specific to each type of credential. * * An example using the Ruby sdk might look like: * * `sdk.user_for_credential('embed', 'customer-4959425')` * * This table shows the supported 'Credential Type' strings. The right column is for reference; it shows * which field in the given credential type is actually searched when finding a user with the supplied * 'credential_id'. * * | Credential Types | Id Field Matched | * | ---------------- | ---------------- | * | email | email | * | google | google_user_id | * | saml | saml_user_id | * | oidc | oidc_user_id | * | ldap | ldap_id | * | api | token | * | api3 | client_id | * | embed | external_user_id | * | looker_openid | email | * * **NOTE**: The 'api' credential type was only used with the legacy Looker query API and is no longer supported. The credential type for API you are currently looking at is 'api3'. * * @param {String} credential_type Type name of credential * @param {String} credential_id Id of credential * @param {String} fields Requested fields. * * GET /users/credential/{credential_type}/{credential_id} -> ByteArray */ @JvmOverloads fun user_for_credential( credential_type: String, credential_id: String, fields: String? = null ) : SDKResponse { val path_credential_type = encodeParam(credential_type) val path_credential_id = encodeParam(credential_id) return this.get<ByteArray>("/users/credential/${path_credential_type}/${path_credential_id}", mapOf("fields" to fields)) } /** * ### Email/password login information for the specified user. * * @param {String} user_id Id of user * @param {String} fields Requested fields. * * GET /users/{user_id}/credentials_email -> ByteArray */ @JvmOverloads fun user_credentials_email( user_id: String, fields: String? = null ) : SDKResponse { val path_user_id = encodeParam(user_id) return this.get<ByteArray>("/users/${path_user_id}/credentials_email", mapOf("fields" to fields)) } /** * ### Email/password login information for the specified user. * * @param {String} user_id Id of user * @param {WriteCredentialsEmail} body * @param {String} fields Requested fields. * * POST /users/{user_id}/credentials_email -> ByteArray */ @JvmOverloads fun create_user_credentials_email( user_id: String, body: WriteCredentialsEmail, fields: String? = null ) : SDKResponse { val path_user_id = encodeParam(user_id) return this.post<ByteArray>("/users/${path_user_id}/credentials_email", mapOf("fields" to fields), body) } /** * ### Email/password login information for the specified user. * * @param {String} user_id Id of user * @param {WriteCredentialsEmail} body * @param {String} fields Requested fields. * * PATCH /users/{user_id}/credentials_email -> ByteArray */ @JvmOverloads fun update_user_credentials_email( user_id: String, body: WriteCredentialsEmail, fields: String? = null ) : SDKResponse { val path_user_id = encodeParam(user_id) return this.patch<ByteArray>("/users/${path_user_id}/credentials_email", mapOf("fields" to fields), body) } /** * ### Email/password login information for the specified user. * * @param {String} user_id Id of user * * DELETE /users/{user_id}/credentials_email -> ByteArray */ fun delete_user_credentials_email( user_id: String ) : SDKResponse { val path_user_id = encodeParam(user_id) return this.delete<ByteArray>("/users/${path_user_id}/credentials_email", mapOf()) } /** * ### Two-factor login information for the specified user. * * @param {String} user_id Id of user * @param {String} fields Requested fields. * * GET /users/{user_id}/credentials_totp -> ByteArray */ @JvmOverloads fun user_credentials_totp( user_id: String, fields: String? = null ) : SDKResponse { val path_user_id = encodeParam(user_id) return this.get<ByteArray>("/users/${path_user_id}/credentials_totp", mapOf("fields" to fields)) } /** * ### Two-factor login information for the specified user. * * @param {String} user_id Id of user * @param {CredentialsTotp} body WARNING: no writeable properties found for POST, PUT, or PATCH * @param {String} fields Requested fields. * * POST /users/{user_id}/credentials_totp -> ByteArray */ @JvmOverloads fun create_user_credentials_totp( user_id: String, body: CredentialsTotp? = null, fields: String? = null ) : SDKResponse { val path_user_id = encodeParam(user_id) return this.post<ByteArray>("/users/${path_user_id}/credentials_totp", mapOf("fields" to fields), body) } /** * ### Two-factor login information for the specified user. * * @param {String} user_id Id of user * * DELETE /users/{user_id}/credentials_totp -> ByteArray */ fun delete_user_credentials_totp( user_id: String ) : SDKResponse { val path_user_id = encodeParam(user_id) return this.delete<ByteArray>("/users/${path_user_id}/credentials_totp", mapOf()) } /** * ### LDAP login information for the specified user. * * @param {String} user_id Id of user * @param {String} fields Requested fields. * * GET /users/{user_id}/credentials_ldap -> ByteArray */ @JvmOverloads fun user_credentials_ldap( user_id: String, fields: String? = null ) : SDKResponse { val path_user_id = encodeParam(user_id) return this.get<ByteArray>("/users/${path_user_id}/credentials_ldap", mapOf("fields" to fields)) } /** * ### LDAP login information for the specified user. * * @param {String} user_id Id of user * * DELETE /users/{user_id}/credentials_ldap -> ByteArray */ fun delete_user_credentials_ldap( user_id: String ) : SDKResponse { val path_user_id = encodeParam(user_id) return this.delete<ByteArray>("/users/${path_user_id}/credentials_ldap", mapOf()) } /** * ### Google authentication login information for the specified user. * * @param {String} user_id Id of user * @param {String} fields Requested fields. * * GET /users/{user_id}/credentials_google -> ByteArray */ @JvmOverloads fun user_credentials_google( user_id: String, fields: String? = null ) : SDKResponse { val path_user_id = encodeParam(user_id) return this.get<ByteArray>("/users/${path_user_id}/credentials_google", mapOf("fields" to fields)) } /** * ### Google authentication login information for the specified user. * * @param {String} user_id Id of user * * DELETE /users/{user_id}/credentials_google -> ByteArray */ fun delete_user_credentials_google( user_id: String ) : SDKResponse { val path_user_id = encodeParam(user_id) return this.delete<ByteArray>("/users/${path_user_id}/credentials_google", mapOf()) } /** * ### Saml authentication login information for the specified user. * * @param {String} user_id Id of user * @param {String} fields Requested fields. * * GET /users/{user_id}/credentials_saml -> ByteArray */ @JvmOverloads fun user_credentials_saml( user_id: String, fields: String? = null ) : SDKResponse { val path_user_id = encodeParam(user_id) return this.get<ByteArray>("/users/${path_user_id}/credentials_saml", mapOf("fields" to fields)) } /** * ### Saml authentication login information for the specified user. * * @param {String} user_id Id of user * * DELETE /users/{user_id}/credentials_saml -> ByteArray */ fun delete_user_credentials_saml( user_id: String ) : SDKResponse { val path_user_id = encodeParam(user_id) return this.delete<ByteArray>("/users/${path_user_id}/credentials_saml", mapOf()) } /** * ### OpenID Connect (OIDC) authentication login information for the specified user. * * @param {String} user_id Id of user * @param {String} fields Requested fields. * * GET /users/{user_id}/credentials_oidc -> ByteArray */ @JvmOverloads fun user_credentials_oidc( user_id: String, fields: String? = null ) : SDKResponse { val path_user_id = encodeParam(user_id) return this.get<ByteArray>("/users/${path_user_id}/credentials_oidc", mapOf("fields" to fields)) } /** * ### OpenID Connect (OIDC) authentication login information for the specified user. * * @param {String} user_id Id of user * * DELETE /users/{user_id}/credentials_oidc -> ByteArray */ fun delete_user_credentials_oidc( user_id: String ) : SDKResponse { val path_user_id = encodeParam(user_id) return this.delete<ByteArray>("/users/${path_user_id}/credentials_oidc", mapOf()) } /** * ### API 3 login information for the specified user. This is for the newer API keys that can be added for any user. * * @param {String} user_id Id of user * @param {String} credentials_api3_id Id of API 3 Credential * @param {String} fields Requested fields. * * GET /users/{user_id}/credentials_api3/{credentials_api3_id} -> ByteArray */ @JvmOverloads fun user_credentials_api3( user_id: String, credentials_api3_id: String, fields: String? = null ) : SDKResponse { val path_user_id = encodeParam(user_id) val path_credentials_api3_id = encodeParam(credentials_api3_id) return this.get<ByteArray>("/users/${path_user_id}/credentials_api3/${path_credentials_api3_id}", mapOf("fields" to fields)) } /** * ### API 3 login information for the specified user. This is for the newer API keys that can be added for any user. * * @param {String} user_id Id of user * @param {String} credentials_api3_id Id of API 3 Credential * * DELETE /users/{user_id}/credentials_api3/{credentials_api3_id} -> ByteArray */ fun delete_user_credentials_api3( user_id: String, credentials_api3_id: String ) : SDKResponse { val path_user_id = encodeParam(user_id) val path_credentials_api3_id = encodeParam(credentials_api3_id) return this.delete<ByteArray>("/users/${path_user_id}/credentials_api3/${path_credentials_api3_id}", mapOf()) } /** * ### API 3 login information for the specified user. This is for the newer API keys that can be added for any user. * * @param {String} user_id Id of user * @param {String} fields Requested fields. * * GET /users/{user_id}/credentials_api3 -> ByteArray */ @JvmOverloads fun all_user_credentials_api3s( user_id: String, fields: String? = null ) : SDKResponse { val path_user_id = encodeParam(user_id) return this.get<ByteArray>("/users/${path_user_id}/credentials_api3", mapOf("fields" to fields)) } /** * ### API 3 login information for the specified user. This is for the newer API keys that can be added for any user. * * @param {String} user_id Id of user * @param {String} fields Requested fields. * * POST /users/{user_id}/credentials_api3 -> ByteArray */ @JvmOverloads fun create_user_credentials_api3( user_id: String, fields: String? = null ) : SDKResponse { val path_user_id = encodeParam(user_id) return this.post<ByteArray>("/users/${path_user_id}/credentials_api3", mapOf("fields" to fields)) } /** * ### Embed login information for the specified user. * * @param {String} user_id Id of user * @param {String} credentials_embed_id Id of Embedding Credential * @param {String} fields Requested fields. * * GET /users/{user_id}/credentials_embed/{credentials_embed_id} -> ByteArray */ @JvmOverloads fun user_credentials_embed( user_id: String, credentials_embed_id: String, fields: String? = null ) : SDKResponse { val path_user_id = encodeParam(user_id) val path_credentials_embed_id = encodeParam(credentials_embed_id) return this.get<ByteArray>("/users/${path_user_id}/credentials_embed/${path_credentials_embed_id}", mapOf("fields" to fields)) } /** * ### Embed login information for the specified user. * * @param {String} user_id Id of user * @param {String} credentials_embed_id Id of Embedding Credential * * DELETE /users/{user_id}/credentials_embed/{credentials_embed_id} -> ByteArray */ fun delete_user_credentials_embed( user_id: String, credentials_embed_id: String ) : SDKResponse { val path_user_id = encodeParam(user_id) val path_credentials_embed_id = encodeParam(credentials_embed_id) return this.delete<ByteArray>("/users/${path_user_id}/credentials_embed/${path_credentials_embed_id}", mapOf()) } /** * ### Embed login information for the specified user. * * @param {String} user_id Id of user * @param {String} fields Requested fields. * * GET /users/{user_id}/credentials_embed -> ByteArray */ @JvmOverloads fun all_user_credentials_embeds( user_id: String, fields: String? = null ) : SDKResponse { val path_user_id = encodeParam(user_id) return this.get<ByteArray>("/users/${path_user_id}/credentials_embed", mapOf("fields" to fields)) } /** * ### Looker Openid login information for the specified user. Used by Looker Analysts. * * @param {String} user_id Id of user * @param {String} fields Requested fields. * * GET /users/{user_id}/credentials_looker_openid -> ByteArray */ @JvmOverloads fun user_credentials_looker_openid( user_id: String, fields: String? = null ) : SDKResponse { val path_user_id = encodeParam(user_id) return this.get<ByteArray>("/users/${path_user_id}/credentials_looker_openid", mapOf("fields" to fields)) } /** * ### Looker Openid login information for the specified user. Used by Looker Analysts. * * @param {String} user_id Id of user * * DELETE /users/{user_id}/credentials_looker_openid -> ByteArray */ fun delete_user_credentials_looker_openid( user_id: String ) : SDKResponse { val path_user_id = encodeParam(user_id) return this.delete<ByteArray>("/users/${path_user_id}/credentials_looker_openid", mapOf()) } /** * ### Web login session for the specified user. * * @param {String} user_id Id of user * @param {String} session_id Id of Web Login Session * @param {String} fields Requested fields. * * GET /users/{user_id}/sessions/{session_id} -> ByteArray */ @JvmOverloads fun user_session( user_id: String, session_id: String, fields: String? = null ) : SDKResponse { val path_user_id = encodeParam(user_id) val path_session_id = encodeParam(session_id) return this.get<ByteArray>("/users/${path_user_id}/sessions/${path_session_id}", mapOf("fields" to fields)) } /** * ### Web login session for the specified user. * * @param {String} user_id Id of user * @param {String} session_id Id of Web Login Session * * DELETE /users/{user_id}/sessions/{session_id} -> ByteArray */ fun delete_user_session( user_id: String, session_id: String ) : SDKResponse { val path_user_id = encodeParam(user_id) val path_session_id = encodeParam(session_id) return this.delete<ByteArray>("/users/${path_user_id}/sessions/${path_session_id}", mapOf()) } /** * ### Web login session for the specified user. * * @param {String} user_id Id of user * @param {String} fields Requested fields. * * GET /users/{user_id}/sessions -> ByteArray */ @JvmOverloads fun all_user_sessions( user_id: String, fields: String? = null ) : SDKResponse { val path_user_id = encodeParam(user_id) return this.get<ByteArray>("/users/${path_user_id}/sessions", mapOf("fields" to fields)) } /** * ### Create a password reset token. * This will create a cryptographically secure random password reset token for the user. * If the user already has a password reset token then this invalidates the old token and creates a new one. * The token is expressed as the 'password_reset_url' of the user's email/password credential object. * This takes an optional 'expires' param to indicate if the new token should be an expiring token. * Tokens that expire are typically used for self-service password resets for existing users. * Invitation emails for new users typically are not set to expire. * The expire period is always 60 minutes when expires is enabled. * This method can be called with an empty body. * * @param {String} user_id Id of user * @param {Boolean} expires Expiring token. * @param {String} fields Requested fields. * * POST /users/{user_id}/credentials_email/password_reset -> ByteArray */ @JvmOverloads fun create_user_credentials_email_password_reset( user_id: String, expires: Boolean? = null, fields: String? = null ) : SDKResponse { val path_user_id = encodeParam(user_id) return this.post<ByteArray>("/users/${path_user_id}/credentials_email/password_reset", mapOf("expires" to expires, "fields" to fields)) } /** * ### Get information about roles of a given user * * @param {String} user_id Id of user * @param {String} fields Requested fields. * @param {Boolean} direct_association_only Get only roles associated directly with the user: exclude those only associated through groups. * * GET /users/{user_id}/roles -> ByteArray */ @JvmOverloads fun user_roles( user_id: String, fields: String? = null, direct_association_only: Boolean? = null ) : SDKResponse { val path_user_id = encodeParam(user_id) return this.get<ByteArray>("/users/${path_user_id}/roles", mapOf("fields" to fields, "direct_association_only" to direct_association_only)) } /** * ### Set roles of the user with a specific id. * * @param {String} user_id Id of user * @param {Array<String>} body * @param {String} fields Requested fields. * * PUT /users/{user_id}/roles -> ByteArray */ @JvmOverloads fun set_user_roles( user_id: String, body: Array<String>, fields: String? = null ) : SDKResponse { val path_user_id = encodeParam(user_id) return this.put<ByteArray>("/users/${path_user_id}/roles", mapOf("fields" to fields), body) } /** * ### Get user attribute values for a given user. * * Returns the values of specified user attributes (or all user attributes) for a certain user. * * A value for each user attribute is searched for in the following locations, in this order: * * 1. in the user's account information * 1. in groups that the user is a member of * 1. the default value of the user attribute * * If more than one group has a value defined for a user attribute, the group with the lowest rank wins. * * The response will only include user attributes for which values were found. Use `include_unset=true` to include * empty records for user attributes with no value. * * The value of all hidden user attributes will be blank. * * @param {String} user_id Id of user * @param {String} fields Requested fields. * @param {DelimArray<String>} user_attribute_ids Specific user attributes to request. Omit or leave blank to request all user attributes. * @param {Boolean} all_values If true, returns all values in the search path instead of just the first value found. Useful for debugging group precedence. * @param {Boolean} include_unset If true, returns an empty record for each requested attribute that has no user, group, or default value. * * GET /users/{user_id}/attribute_values -> ByteArray */ @JvmOverloads fun user_attribute_user_values( user_id: String, fields: String? = null, user_attribute_ids: DelimArray<String>? = null, all_values: Boolean? = null, include_unset: Boolean? = null ) : SDKResponse { val path_user_id = encodeParam(user_id) return this.get<ByteArray>("/users/${path_user_id}/attribute_values", mapOf("fields" to fields, "user_attribute_ids" to user_attribute_ids, "all_values" to all_values, "include_unset" to include_unset)) } /** * ### Store a custom value for a user attribute in a user's account settings. * * Per-user user attribute values take precedence over group or default values. * * @param {String} user_id Id of user * @param {String} user_attribute_id Id of user attribute * @param {WriteUserAttributeWithValue} body * * PATCH /users/{user_id}/attribute_values/{user_attribute_id} -> ByteArray */ fun set_user_attribute_user_value( user_id: String, user_attribute_id: String, body: WriteUserAttributeWithValue ) : SDKResponse { val path_user_id = encodeParam(user_id) val path_user_attribute_id = encodeParam(user_attribute_id) return this.patch<ByteArray>("/users/${path_user_id}/attribute_values/${path_user_attribute_id}", mapOf(), body) } /** * ### Delete a user attribute value from a user's account settings. * * After the user attribute value is deleted from the user's account settings, subsequent requests * for the user attribute value for this user will draw from the user's groups or the default * value of the user attribute. See [Get User Attribute Values](#!/User/user_attribute_user_values) for more * information about how user attribute values are resolved. * * @param {String} user_id Id of user * @param {String} user_attribute_id Id of user attribute * * DELETE /users/{user_id}/attribute_values/{user_attribute_id} -> ByteArray */ fun delete_user_attribute_user_value( user_id: String, user_attribute_id: String ) : SDKResponse { val path_user_id = encodeParam(user_id) val path_user_attribute_id = encodeParam(user_attribute_id) return this.delete<ByteArray>("/users/${path_user_id}/attribute_values/${path_user_attribute_id}", mapOf()) } /** * ### Send a password reset token. * This will send a password reset email to the user. If a password reset token does not already exist * for this user, it will create one and then send it. * If the user has not yet set up their account, it will send a setup email to the user. * The URL sent in the email is expressed as the 'password_reset_url' of the user's email/password credential object. * Password reset URLs will expire in 60 minutes. * This method can be called with an empty body. * * @param {String} user_id Id of user * @param {String} fields Requested fields. * * POST /users/{user_id}/credentials_email/send_password_reset -> ByteArray */ @JvmOverloads fun send_user_credentials_email_password_reset( user_id: String, fields: String? = null ) : SDKResponse { val path_user_id = encodeParam(user_id) return this.post<ByteArray>("/users/${path_user_id}/credentials_email/send_password_reset", mapOf("fields" to fields)) } /** * ### Change a disabled user's email addresses * * Allows the admin to change the email addresses for all the user's * associated credentials. Will overwrite all associated email addresses with * the value supplied in the 'email' body param. * The user's 'is_disabled' status must be true. * * @param {String} user_id Id of user * @param {UserEmailOnly} body * @param {String} fields Requested fields. * * POST /users/{user_id}/update_emails -> ByteArray */ @JvmOverloads fun wipeout_user_emails( user_id: String, body: UserEmailOnly, fields: String? = null ) : SDKResponse { val path_user_id = encodeParam(user_id) return this.post<ByteArray>("/users/${path_user_id}/update_emails", mapOf("fields" to fields), body) } /** * Create an embed user from an external user ID * * @param {CreateEmbedUserRequest} body * * POST /users/embed_user -> ByteArray */ fun create_embed_user( body: CreateEmbedUserRequest ) : SDKResponse { return this.post<ByteArray>("/users/embed_user", mapOf(), body) } //endregion User: Manage Users //region UserAttribute: Manage User Attributes /** * ### Get information about all user attributes. * * @param {String} fields Requested fields. * @param {String} sorts Fields to order the results by. Sortable fields include: name, label * * GET /user_attributes -> ByteArray */ @JvmOverloads fun all_user_attributes( fields: String? = null, sorts: String? = null ) : SDKResponse { return this.get<ByteArray>("/user_attributes", mapOf("fields" to fields, "sorts" to sorts)) } /** * ### Create a new user attribute * * Permission information for a user attribute is conveyed through the `can` and `user_can_edit` fields. * The `user_can_edit` field indicates whether an attribute is user-editable _anywhere_ in the application. * The `can` field gives more granular access information, with the `set_value` child field indicating whether * an attribute's value can be set by [Setting the User Attribute User Value](#!/User/set_user_attribute_user_value). * * Note: `name` and `label` fields must be unique across all user attributes in the Looker instance. * Attempting to create a new user attribute with a name or label that duplicates an existing * user attribute will fail with a 422 error. * * @param {WriteUserAttribute} body * @param {String} fields Requested fields. * * POST /user_attributes -> ByteArray */ @JvmOverloads fun create_user_attribute( body: WriteUserAttribute, fields: String? = null ) : SDKResponse { return this.post<ByteArray>("/user_attributes", mapOf("fields" to fields), body) } /** * ### Get information about a user attribute. * * @param {String} user_attribute_id Id of user attribute * @param {String} fields Requested fields. * * GET /user_attributes/{user_attribute_id} -> ByteArray */ @JvmOverloads fun user_attribute( user_attribute_id: String, fields: String? = null ) : SDKResponse { val path_user_attribute_id = encodeParam(user_attribute_id) return this.get<ByteArray>("/user_attributes/${path_user_attribute_id}", mapOf("fields" to fields)) } /** * ### Update a user attribute definition. * * @param {String} user_attribute_id Id of user attribute * @param {WriteUserAttribute} body * @param {String} fields Requested fields. * * PATCH /user_attributes/{user_attribute_id} -> ByteArray */ @JvmOverloads fun update_user_attribute( user_attribute_id: String, body: WriteUserAttribute, fields: String? = null ) : SDKResponse { val path_user_attribute_id = encodeParam(user_attribute_id) return this.patch<ByteArray>("/user_attributes/${path_user_attribute_id}", mapOf("fields" to fields), body) } /** * ### Delete a user attribute (admin only). * * @param {String} user_attribute_id Id of user attribute * * DELETE /user_attributes/{user_attribute_id} -> ByteArray */ fun delete_user_attribute( user_attribute_id: String ) : SDKResponse { val path_user_attribute_id = encodeParam(user_attribute_id) return this.delete<ByteArray>("/user_attributes/${path_user_attribute_id}", mapOf()) } /** * ### Returns all values of a user attribute defined by user groups, in precedence order. * * A user may be a member of multiple groups which define different values for a given user attribute. * The order of group-values in the response determines precedence for selecting which group-value applies * to a given user. For more information, see [Set User Attribute Group Values](#!/UserAttribute/set_user_attribute_group_values). * * Results will only include groups that the caller's user account has permission to see. * * @param {String} user_attribute_id Id of user attribute * @param {String} fields Requested fields. * * GET /user_attributes/{user_attribute_id}/group_values -> ByteArray */ @JvmOverloads fun all_user_attribute_group_values( user_attribute_id: String, fields: String? = null ) : SDKResponse { val path_user_attribute_id = encodeParam(user_attribute_id) return this.get<ByteArray>("/user_attributes/${path_user_attribute_id}/group_values", mapOf("fields" to fields)) } /** * ### Define values for a user attribute across a set of groups, in priority order. * * This function defines all values for a user attribute defined by user groups. This is a global setting, potentially affecting * all users in the system. This function replaces any existing group value definitions for the indicated user attribute. * * The value of a user attribute for a given user is determined by searching the following locations, in this order: * * 1. the user's account settings * 2. the groups that the user is a member of * 3. the default value of the user attribute, if any * * The user may be a member of multiple groups which define different values for that user attribute. The order of items in the group_values parameter * determines which group takes priority for that user. Lowest array index wins. * * An alternate method to indicate the selection precedence of group-values is to assign numbers to the 'rank' property of each * group-value object in the array. Lowest 'rank' value wins. If you use this technique, you must assign a * rank value to every group-value object in the array. * * To set a user attribute value for a single user, see [Set User Attribute User Value](#!/User/set_user_attribute_user_value). * To set a user attribute value for all members of a group, see [Set User Attribute Group Value](#!/Group/update_user_attribute_group_value). * * @param {String} user_attribute_id Id of user attribute * @param {Array<UserAttributeGroupValue>} body * * POST /user_attributes/{user_attribute_id}/group_values -> ByteArray */ fun set_user_attribute_group_values( user_attribute_id: String, body: Array<UserAttributeGroupValue> ) : SDKResponse { val path_user_attribute_id = encodeParam(user_attribute_id) return this.post<ByteArray>("/user_attributes/${path_user_attribute_id}/group_values", mapOf(), body) } //endregion UserAttribute: Manage User Attributes //region Workspace: Manage Workspaces /** * ### Get All Workspaces * * Returns all workspaces available to the calling user. * * GET /workspaces -> ByteArray */ fun all_workspaces( ) : SDKResponse { return this.get<ByteArray>("/workspaces", mapOf()) } /** * ### Get A Workspace * * Returns information about a workspace such as the git status and selected branches * of all projects available to the caller's user account. * * A workspace defines which versions of project files will be used to evaluate expressions * and operations that use model definitions - operations such as running queries or rendering dashboards. * Each project has its own git repository, and each project in a workspace may be configured to reference * particular branch or revision within their respective repositories. * * There are two predefined workspaces available: "production" and "dev". * * The production workspace is shared across all Looker users. Models in the production workspace are read-only. * Changing files in production is accomplished by modifying files in a git branch and using Pull Requests * to merge the changes from the dev branch into the production branch, and then telling * Looker to sync with production. * * The dev workspace is local to each Looker user. Changes made to project/model files in the dev workspace only affect * that user, and only when the dev workspace is selected as the active workspace for the API session. * (See set_session_workspace()). * * The dev workspace is NOT unique to an API session. Two applications accessing the Looker API using * the same user account will see the same files in the dev workspace. To avoid collisions between * API clients it's best to have each client login with API3 credentials for a different user account. * * Changes made to files in a dev workspace are persistent across API sessions. It's a good * idea to commit any changes you've made to the git repository, but not strictly required. Your modified files * reside in a special user-specific directory on the Looker server and will still be there when you login in again * later and use update_session(workspace_id: "dev") to select the dev workspace for the new API session. * * @param {String} workspace_id Id of the workspace * * GET /workspaces/{workspace_id} -> ByteArray */ fun workspace( workspace_id: String ) : SDKResponse { val path_workspace_id = encodeParam(workspace_id) return this.get<ByteArray>("/workspaces/${path_workspace_id}", mapOf()) } //endregion Workspace: Manage Workspaces }
mit
6e8e868a0cd01b67614fa7e6f9e29676
36.592926
381
0.615949
4.256843
false
false
false
false
kysersozelee/KotlinStudy
JsonParser/bin/main.kt
1
1165
fun main(args: Array<String>) { var writer: JsonWriter = JsonWriter() var jobj = JsonObject() jobj.add("õÁ¤ÇÊ", 29) jobj.add("½ÉÇö¿ì", 30) jobj.write(writer) println("json array serialize ==> ${writer.string}") var jobj3 = JsonObject() jobj3.add("À̵¿¿ì", 99) var writer2: JsonWriter = JsonWriter() var jobj2 = JsonObject() jobj2.add("idiots", jobj) jobj2.add("genius", jobj3) jobj2.add("null test", null) jobj2.write(writer2) println("nested json object serialize ==> ${writer2.string}") var writer4: JsonWriter = JsonWriter() var jarr = JsonArray() jarr.add(123) jarr.add("asd") jarr.add(0.323) jarr.add(true) jarr.write(writer4) println("json array serialize ==> ${writer4.string}") var parser: JsonParser = JsonParser() var parsedJobj: JsonObject = parser.parse(writer2.string).asObject() var genius: JsonObject? = parsedJobj.get("genius")?.asObject() var writer5: JsonWriter = JsonWriter() var writer6: JsonWriter = JsonWriter() println("json object deserialize jsonstr : ${writer2.string} parsedJobj : ${parsedJobj.write(writer6)} genius : ==> ${genius?.write(writer5)}") }
bsd-2-clause
431cb186c005ee1cbd1ec6f9297ea134
27.923077
146
0.672103
3.049738
false
false
false
false
spark/photon-tinker-android
devicesetup/src/main/java/io/particle/android/sdk/devicesetup/apconnector/ApConnector.kt
1
1832
package io.particle.android.sdk.devicesetup.apconnector import android.net.wifi.WifiConfiguration import android.net.wifi.WifiConfiguration.KeyMgmt import io.particle.android.sdk.devicesetup.apconnector.ApConnector.Client import io.particle.android.sdk.utils.SSID import java.util.concurrent.TimeUnit.SECONDS interface ApConnector { interface Client { fun onApConnectionSuccessful(config: WifiConfiguration) fun onApConnectionFailed(config: WifiConfiguration) } /** * Connect this Android device to the specified AP. * * @param config the WifiConfiguration defining which AP to connect to */ fun connectToAP(config: WifiConfiguration, client: Client) /** * Stop attempting to connect */ fun stop() companion object { @JvmStatic fun buildUnsecuredConfig(ssid: SSID): WifiConfiguration { val config = WifiConfiguration() config.SSID = ssid.inQuotes() config.hiddenSSID = false config.allowedKeyManagement.set(KeyMgmt.NONE) // have to set a very high number in order to ensure that Android doesn't // immediately drop this connection and reconnect to the a different AP config.priority = 999999 return config } @JvmField val CONNECT_TO_DEVICE_TIMEOUT_MILLIS = SECONDS.toMillis(20) } } class DecoratingClient( private val onClearState: () -> Unit ) : Client { var wrappedClient: Client? = null override fun onApConnectionSuccessful(config: WifiConfiguration) { onClearState() wrappedClient?.onApConnectionSuccessful(config) } override fun onApConnectionFailed(config: WifiConfiguration) { onClearState() wrappedClient?.onApConnectionFailed(config) } }
apache-2.0
62bfef9222554d8248e24cc0a30be6b4
27.625
85
0.68559
4.709512
false
true
false
false
google/horologist
media-ui/src/debug/java/com/google/android/horologist/media/ui/components/controls/SeekToNextButtonPreview.kt
1
1298
/* * Copyright 2022 The Android Open Source Project * * 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 * * https://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. */ @file:OptIn(ExperimentalHorologistMediaUiApi::class) package com.google.android.horologist.media.ui.components.controls import androidx.compose.runtime.Composable import androidx.compose.ui.tooling.preview.Preview import com.google.android.horologist.media.ui.ExperimentalHorologistMediaUiApi @Preview( name = "Enabled", backgroundColor = 0xff000000, showBackground = true ) @Composable fun SeekToNextButtonPreviewEnabled() { SeekToNextButton(onClick = {}) } @Preview( name = "Disabled", backgroundColor = 0xff000000, showBackground = true ) @Composable fun SeekToNextButtonPreviewDisabled() { SeekToNextButton(onClick = {}, enabled = false) }
apache-2.0
ecf1255630d340a1093c4f755c265d78
29.186047
78
0.756549
4.228013
false
false
false
false
wasabeef/recyclerview-animators
example/src/main/java/jp/wasabeef/example/recyclerview/AdapterSampleActivity.kt
1
3624
package jp.wasabeef.example.recyclerview import android.content.Context import android.os.Bundle import android.view.View import android.view.animation.OvershootInterpolator import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.Spinner import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import jp.wasabeef.recyclerview.adapters.AlphaInAnimationAdapter import jp.wasabeef.recyclerview.adapters.AnimationAdapter import jp.wasabeef.recyclerview.adapters.ScaleInAnimationAdapter import jp.wasabeef.recyclerview.adapters.SlideInBottomAnimationAdapter import jp.wasabeef.recyclerview.adapters.SlideInLeftAnimationAdapter import jp.wasabeef.recyclerview.adapters.SlideInRightAnimationAdapter import jp.wasabeef.recyclerview.animators.FadeInAnimator /** * Created by Daichi Furiya / Wasabeef on 2020/08/26. */ class AdapterSampleActivity : AppCompatActivity() { internal enum class Type { AlphaIn { override operator fun get(context: Context): AnimationAdapter { return AlphaInAnimationAdapter(MainAdapter(context, SampleData.LIST.toMutableList())) } }, ScaleIn { override operator fun get(context: Context): AnimationAdapter { return ScaleInAnimationAdapter(MainAdapter(context, SampleData.LIST.toMutableList())) } }, SlideInBottom { override operator fun get(context: Context): AnimationAdapter { return SlideInBottomAnimationAdapter(MainAdapter(context, SampleData.LIST.toMutableList())) } }, SlideInLeft { override operator fun get(context: Context): AnimationAdapter { return SlideInLeftAnimationAdapter(MainAdapter(context, SampleData.LIST.toMutableList())) } }, SlideInRight { override operator fun get(context: Context): AnimationAdapter { return SlideInRightAnimationAdapter(MainAdapter(context, SampleData.LIST.toMutableList())) } }; abstract operator fun get(context: Context): AnimationAdapter } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_adapter_sample) setSupportActionBar(findViewById(R.id.tool_bar)) supportActionBar?.setDisplayShowTitleEnabled(false) val recyclerView = findViewById<RecyclerView>(R.id.list) recyclerView.layoutManager = if (intent.getBooleanExtra(MainActivity.KEY_GRID, true)) { GridLayoutManager(this, 2) } else { LinearLayoutManager(this) } val spinner = findViewById<Spinner>(R.id.spinner) spinner.adapter = ArrayAdapter<String>(this, android.R.layout.simple_list_item_1).apply { for (type in Type.values()) add(type.name) } spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) { recyclerView.adapter = Type.values()[position][view.context].apply { setFirstOnly(true) setDuration(500) setInterpolator(OvershootInterpolator(.5f)) } } override fun onNothingSelected(parent: AdapterView<*>) { // no-op } } recyclerView.itemAnimator = FadeInAnimator() val adapter = MainAdapter(this, SampleData.LIST.toMutableList()) recyclerView.adapter = AlphaInAnimationAdapter(adapter).apply { setFirstOnly(true) setDuration(500) setInterpolator(OvershootInterpolator(.5f)) } } }
apache-2.0
de593d523a741e246f9961b86e0f7906
36.360825
99
0.749172
4.768421
false
false
false
false
Shynixn/BlockBall
blockball-core/src/main/java/com/github/shynixn/blockball/core/logic/business/commandexecutor/ArenaCommandExecutor.kt
1
9755
package com.github.shynixn.blockball.core.logic.business.commandexecutor import com.github.shynixn.blockball.api.business.enumeration.ChatClickAction import com.github.shynixn.blockball.api.business.enumeration.ChatColor import com.github.shynixn.blockball.api.business.enumeration.MenuCommand import com.github.shynixn.blockball.api.business.enumeration.MenuCommandResult import com.github.shynixn.blockball.api.business.executor.CommandExecutor import com.github.shynixn.blockball.api.business.service.ConfigurationService import com.github.shynixn.blockball.api.business.service.LoggingService import com.github.shynixn.blockball.api.business.service.ProxyService import com.github.shynixn.blockball.core.logic.business.commandmenu.* import com.github.shynixn.blockball.core.logic.persistence.entity.ChatBuilderEntity import com.google.inject.Inject /** * Created by Shynixn 2018. * <p> * Version 1.2 * <p> * MIT License * <p> * Copyright (c) 2018 by Shynixn * <p> * 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: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * 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. */ class ArenaCommandExecutor @Inject constructor( private val configurationService: ConfigurationService, private val proxyService: ProxyService, private val loggingService: LoggingService, openPage: OpenPage, mainConfigurationPage: MainConfigurationPage, spectatePage: SpectatePage, mainSettingsPage: MainSettingsPage, ballSettingsPage: BallSettingsPage, ballModifierPage: BallModifierSettingsPage, listablePage: ListablePage, teamSettingsPage: TeamSettingsPage, effectsSettingsPage: EffectsSettingsPage, multipleLinesPage: MultipleLinesPage, hologramsPage: HologramPage, scoreboardPage: ScoreboardPage, bossbarPage: BossbarPage, templatePage: TemplateSettingsPage, signSettingsPage: SignSettingsPage, rewardsPage: RewardsPage, particlesPage: ParticleEffectPage, soundsPage: SoundEffectPage, abilitiesPage: AbilitiesSettingsPage, doubleJumpPage: DoubleJumpPage, miscPage: MiscSettingsPage, gamePropertiesPage: GamePropertiesPage, areaProtectionPage: AreaProtectionPage, teamTextBookPage: TeamTextBookPage, gameSettingsPage: GameSettingsPage, spectatingSettingsPage: SpectatingSettingsPage, notificationPage: NotificationPage, matchtimesPage : MatchTimesPage ) : CommandExecutor { companion object { private val HEADER_STANDARD = ChatColor.WHITE.toString() + "" + ChatColor.BOLD + "" + ChatColor.UNDERLINE + " BlockBall " private val FOOTER_STANDARD = ChatColor.WHITE.toString() + "" + ChatColor.BOLD + "" + ChatColor.UNDERLINE + " ┌1/1┐ " } private val cache = HashMap<Any, Array<Any?>>() private var pageCache: MutableList<Page> = arrayListOf( openPage, mainConfigurationPage, spectatePage, mainSettingsPage, ballSettingsPage , ballModifierPage, listablePage, teamSettingsPage, effectsSettingsPage, multipleLinesPage, hologramsPage, scoreboardPage, bossbarPage , templatePage, signSettingsPage, rewardsPage, particlesPage, soundsPage, abilitiesPage, doubleJumpPage, miscPage, gamePropertiesPage , areaProtectionPage, teamTextBookPage, gameSettingsPage, spectatingSettingsPage, notificationPage, matchtimesPage ) /** * Gets called when the given [source] executes the defined command with the given [args]. */ override fun <S> onExecuteCommand(source: S, args: Array<out String>): Boolean { try { if (source !is Any) { return false } for (i in 0..19) { proxyService.sendMessage(source, "") } proxyService.sendMessage(source, HEADER_STANDARD) proxyService.sendMessage(source, "\n") if (!this.cache.containsKey(source)) { val anyArray = arrayOfNulls<Any>(8) this.cache[source] = anyArray } val cache: Array<Any?>? = this.cache[source] val command = MenuCommand.from(args) ?: throw IllegalArgumentException("Command is not registered!") var usedPage: Page? = null for (page in this.pageCache) { if (page.getCommandKey() === command.key) { usedPage = page if (command == MenuCommand.BACK) { val newPage = this.getPageById(Integer.parseInt(args[2])) val b = newPage.buildPage(cache!!)!! proxyService.sendMessage(source, b) } else if (command == MenuCommand.CLOSE) { this.cache.remove(source) for (i in 0..19) { proxyService.sendMessage(source, "") } return true } else { @Suppress("UNCHECKED_CAST") val result = page.execute(source, command, cache!!, args as Array<String>) if (result == MenuCommandResult.BACK) { proxyService.performPlayerCommand(source, "blockball open back " + usedPage.getPreviousIdFrom(cache)) return true } if (result != MenuCommandResult.SUCCESS && result != MenuCommandResult.CANCEL_MESSAGE) { val b = ChatBuilderEntity() .component(ChatColor.WHITE.toString() + "" + ChatColor.BOLD + "[" + ChatColor.RED + ChatColor.BOLD + "!" + ChatColor.WHITE + ChatColor.BOLD + "] " + ChatColor.RED + "Error (Hover me)") .setHoverText(result.message!!).builder() proxyService.sendMessage(source, b) } if (result != MenuCommandResult.CANCEL_MESSAGE) { val b = page.buildPage(cache)!! proxyService.sendMessage(source, b) } } break } } if (usedPage == null) throw IllegalArgumentException("Cannot find page with key " + command.key) val builder = ChatBuilderEntity() .text(ChatColor.STRIKETHROUGH.toString() + "----------------------------------------------------").nextLine() .component(" >>Save<< ") .setColor(ChatColor.GREEN) .setClickAction(ChatClickAction.RUN_COMMAND, MenuCommand.ARENA_SAVE.command) .setHoverText("Saves the current arena if possible.") .builder() if (usedPage is ListablePage) { builder.component(">>Back<<") .setColor(ChatColor.RED) .setClickAction(ChatClickAction.RUN_COMMAND, (cache!![3] as MenuCommand).command) .setHoverText("Goes back to the previous page.") .builder() } else { builder.component(">>Back<<") .setColor(ChatColor.RED) .setClickAction(ChatClickAction.RUN_COMMAND, MenuCommand.BACK.command + usedPage.getPreviousIdFrom(cache!!)) .setHoverText("Goes back to the previous page.") .builder() } val b = builder.component(" >>Save and reload<<") .setColor(ChatColor.BLUE) .setClickAction(ChatClickAction.RUN_COMMAND, MenuCommand.ARENA_RELOAD.command) .setHoverText("Saves the current arena and reloads all games on the server.") .builder() proxyService.sendMessage(source, b) proxyService.sendMessage(source, FOOTER_STANDARD) } catch (e: Exception) { loggingService.debug("Command completion failed.", e) val prefix = configurationService.findValue<String>("messages.prefix") proxyService.sendMessage(source, prefix + "Cannot find command.") val data = StringBuilder() args.map { d -> data.append(d).append(" ") } loggingService.info("Cannot find command for args $data.") } return true } /** * Returns the [Page] with the given [id] and throws * a [RuntimeException] if the page is not found. */ private fun getPageById(id: Int): Page { for (page in this.pageCache) { if (page.id == id) { return page } } throw RuntimeException("Page does not exist!") } }
apache-2.0
fa14dbf47ed9298e06e071d55f700c50
47.512438
216
0.618501
4.969929
false
false
false
false
chrisbanes/tivi
data/src/main/java/app/tivi/data/repositories/episodes/EpisodeWatchStore.kt
1
3523
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.tivi.data.repositories.episodes import app.tivi.data.DatabaseTransactionRunner import app.tivi.data.daos.EpisodeWatchEntryDao import app.tivi.data.entities.EpisodeWatchEntry import app.tivi.data.entities.PendingAction import app.tivi.data.syncers.syncerForEntity import app.tivi.util.Logger import kotlinx.coroutines.flow.Flow import javax.inject.Inject class EpisodeWatchStore @Inject constructor( private val transactionRunner: DatabaseTransactionRunner, private val episodeWatchEntryDao: EpisodeWatchEntryDao, logger: Logger ) { private val episodeWatchSyncer = syncerForEntity( episodeWatchEntryDao, { it.traktId }, { entity, id -> entity.copy(id = id ?: 0) }, logger ) fun observeEpisodeWatches(episodeId: Long): Flow<List<EpisodeWatchEntry>> { return episodeWatchEntryDao.watchesForEpisodeObservable(episodeId) } suspend fun save(watch: EpisodeWatchEntry) = episodeWatchEntryDao.insertOrUpdate(watch) suspend fun save(watches: List<EpisodeWatchEntry>) = episodeWatchEntryDao.insertOrUpdate(watches) suspend fun getEpisodeWatchesForShow(showId: Long) = episodeWatchEntryDao.entriesForShowId(showId) suspend fun getWatchesForEpisode(episodeId: Long) = episodeWatchEntryDao.watchesForEpisode(episodeId) suspend fun getEpisodeWatch(watchId: Long) = episodeWatchEntryDao.entryWithId(watchId) suspend fun hasEpisodeBeenWatched(episodeId: Long) = episodeWatchEntryDao.watchCountForEpisode(episodeId) > 0 suspend fun getEntriesWithAddAction(showId: Long) = episodeWatchEntryDao.entriesForShowIdWithSendPendingActions(showId) suspend fun getEntriesWithDeleteAction(showId: Long) = episodeWatchEntryDao.entriesForShowIdWithDeletePendingActions(showId) suspend fun deleteEntriesWithIds(ids: List<Long>) = episodeWatchEntryDao.deleteWithIds(ids) suspend fun updateEntriesWithAction(ids: List<Long>, action: PendingAction): Int { return episodeWatchEntryDao.updateEntriesToPendingAction(ids, action.value) } suspend fun addNewShowWatchEntries( showId: Long, watches: List<EpisodeWatchEntry> ) = transactionRunner { val currentWatches = episodeWatchEntryDao.entriesForShowIdWithNoPendingAction(showId) episodeWatchSyncer.sync(currentWatches, watches, removeNotMatched = false) } suspend fun syncShowWatchEntries( showId: Long, watches: List<EpisodeWatchEntry> ) = transactionRunner { val currentWatches = episodeWatchEntryDao.entriesForShowIdWithNoPendingAction(showId) episodeWatchSyncer.sync(currentWatches, watches) } suspend fun syncEpisodeWatchEntries( episodeId: Long, watches: List<EpisodeWatchEntry> ) = transactionRunner { val currentWatches = episodeWatchEntryDao.watchesForEpisode(episodeId) episodeWatchSyncer.sync(currentWatches, watches) } }
apache-2.0
f5b194ce7f3f0588e8b29c40a851eeb4
38.58427
128
0.765257
4.354759
false
false
false
false
dataloom/conductor-client
src/main/kotlin/com/openlattice/organizations/ExternalDatabaseManagementService.kt
1
36412
package com.openlattice.organizations import com.google.common.base.Preconditions.checkState import com.hazelcast.core.HazelcastInstance import com.hazelcast.query.Predicate import com.hazelcast.query.Predicates import com.hazelcast.query.QueryConstants import com.openlattice.assembler.AssemblerConnectionManager.Companion.OPENLATTICE_SCHEMA import com.openlattice.assembler.AssemblerConnectionManager.Companion.STAGING_SCHEMA import com.openlattice.assembler.PostgresRoles.Companion.getSecurablePrincipalIdFromUserName import com.openlattice.assembler.PostgresRoles.Companion.isPostgresUserName import com.openlattice.assembler.dropAllConnectionsToDatabaseSql import com.openlattice.authorization.* import com.openlattice.authorization.processors.PermissionMerger import com.openlattice.authorization.securable.SecurableObjectType import com.openlattice.edm.processors.GetEntityTypeFromEntitySetEntryProcessor import com.openlattice.edm.processors.GetFqnFromPropertyTypeEntryProcessor import com.openlattice.edm.requests.MetadataUpdate import com.openlattice.hazelcast.HazelcastMap import com.openlattice.hazelcast.processors.GetMembersOfOrganizationEntryProcessor import com.openlattice.hazelcast.processors.organizations.UpdateOrganizationExternalDatabaseColumnEntryProcessor import com.openlattice.hazelcast.processors.organizations.UpdateOrganizationExternalDatabaseTableEntryProcessor import com.openlattice.organization.OrganizationExternalDatabaseColumn import com.openlattice.organization.OrganizationExternalDatabaseTable import com.openlattice.organization.OrganizationExternalDatabaseTableColumnsPair import com.openlattice.organizations.mapstores.ORGANIZATION_ID_INDEX import com.openlattice.organizations.mapstores.TABLE_ID_INDEX import com.openlattice.organizations.roles.SecurePrincipalsManager import com.openlattice.postgres.* import com.openlattice.postgres.DataTables.quote import com.openlattice.postgres.ResultSetAdapters.* import com.openlattice.postgres.external.ExternalDatabaseConnectionManager import com.openlattice.postgres.streams.BasePostgresIterable import com.openlattice.postgres.streams.StatementHolderSupplier import com.openlattice.transporter.processors.DestroyTransportedEntitySetEntryProcessor import com.openlattice.transporter.processors.GetPropertyTypesFromTransporterColumnSetEntryProcessor import com.openlattice.transporter.processors.TransportEntitySetEntryProcessor import com.openlattice.transporter.types.TransporterDatastore import com.zaxxer.hikari.HikariDataSource import org.apache.olingo.commons.api.edm.FullQualifiedName import org.slf4j.LoggerFactory import org.springframework.stereotype.Service import java.io.BufferedOutputStream import java.io.IOException import java.nio.file.Files import java.nio.file.Paths import java.nio.file.StandardCopyOption import java.nio.file.StandardOpenOption import java.time.OffsetDateTime import java.util.* import kotlin.collections.HashMap import kotlin.streams.toList @Service class ExternalDatabaseManagementService( hazelcastInstance: HazelcastInstance, private val externalDbManager: ExternalDatabaseConnectionManager, private val securePrincipalsManager: SecurePrincipalsManager, private val aclKeyReservations: HazelcastAclKeyReservationService, private val authorizationManager: AuthorizationManager, private val organizationExternalDatabaseConfiguration: OrganizationExternalDatabaseConfiguration, private val transporterDatastore: TransporterDatastore, private val dbCredentialService: DbCredentialService, private val hds: HikariDataSource ) { private val organizationExternalDatabaseColumns = HazelcastMap.ORGANIZATION_EXTERNAL_DATABASE_COLUMN.getMap(hazelcastInstance) private val organizationExternalDatabaseTables = HazelcastMap.ORGANIZATION_EXTERNAL_DATABASE_TABLE.getMap(hazelcastInstance) private val securableObjectTypes = HazelcastMap.SECURABLE_OBJECT_TYPES.getMap(hazelcastInstance) private val aces = HazelcastMap.PERMISSIONS.getMap(hazelcastInstance) private val logger = LoggerFactory.getLogger(ExternalDatabaseManagementService::class.java) private val primaryKeyConstraint = "PRIMARY KEY" private val FETCH_SIZE = 100_000 /** * Only needed for materialize entity set, which should move elsewhere eventually */ private val entitySets = HazelcastMap.ENTITY_SETS.getMap(hazelcastInstance) private val entityTypes = HazelcastMap.ENTITY_TYPES.getMap(hazelcastInstance) private val propertyTypes = HazelcastMap.PROPERTY_TYPES.getMap(hazelcastInstance) private val organizations = HazelcastMap.ORGANIZATIONS.getMap(hazelcastInstance) private val transporterState = HazelcastMap.TRANSPORTER_DB_COLUMNS.getMap(hazelcastInstance) /*CREATE*/ fun createOrganizationExternalDatabaseTable(orgId: UUID, table: OrganizationExternalDatabaseTable): UUID { val tableFQN = FullQualifiedName(orgId.toString(), table.name) checkState(organizationExternalDatabaseTables.putIfAbsent(table.id, table) == null, "OrganizationExternalDatabaseTable ${tableFQN.fullQualifiedNameAsString} already exists") aclKeyReservations.reserveIdAndValidateType(table, tableFQN::getFullQualifiedNameAsString) val tableAclKey = AclKey(table.id) authorizationManager.setSecurableObjectType(tableAclKey, SecurableObjectType.OrganizationExternalDatabaseTable) return table.id } fun createOrganizationExternalDatabaseColumn(orgId: UUID, column: OrganizationExternalDatabaseColumn): UUID { checkState(organizationExternalDatabaseTables[column.tableId] != null, "OrganizationExternalDatabaseColumn ${column.name} belongs to " + "a table with id ${column.tableId} that does not exist") val columnFQN = FullQualifiedName(column.tableId.toString(), column.name) checkState(organizationExternalDatabaseColumns.putIfAbsent(column.id, column) == null, "OrganizationExternalDatabaseColumn $columnFQN already exists") aclKeyReservations.reserveIdAndValidateType(column, columnFQN::getFullQualifiedNameAsString) val columnAclKey = AclKey(column.tableId, column.id) authorizationManager.setSecurableObjectType(columnAclKey, SecurableObjectType.OrganizationExternalDatabaseColumn) return column.id } fun getColumnMetadata(tableName: String, tableId: UUID, orgId: UUID, columnName: Optional<String>): BasePostgresIterable< OrganizationExternalDatabaseColumn> { var columnCondition = "" columnName.ifPresent { columnCondition = "AND information_schema.columns.column_name = '$it'" } val sql = getColumnMetadataSql(tableName, columnCondition) return BasePostgresIterable( StatementHolderSupplier(externalDbManager.connectToOrg(orgId), sql) ) { rs -> val storedColumnName = columnName(rs) val dataType = sqlDataType(rs) val position = ordinalPosition(rs) val isPrimaryKey = constraintType(rs) == primaryKeyConstraint OrganizationExternalDatabaseColumn( Optional.empty(), storedColumnName, storedColumnName, Optional.empty(), tableId, orgId, dataType, isPrimaryKey, position) } } fun destroyTransportedEntitySet(entitySetId: UUID) { entitySets.executeOnKey(entitySetId, DestroyTransportedEntitySetEntryProcessor().init(transporterDatastore)) } fun transportEntitySet(organizationId: UUID, entitySetId: UUID) { val userToPrincipalsCompletion = organizations.submitToKey( organizationId, GetMembersOfOrganizationEntryProcessor() ).thenApplyAsync { members -> securePrincipalsManager.bulkGetUnderlyingPrincipals( securePrincipalsManager.getSecurablePrincipals(members).toSet() ).mapKeys { dbCredentialService.getDbUsername(it.key) } } val entityTypeId = entitySets.submitToKey( entitySetId, GetEntityTypeFromEntitySetEntryProcessor() ) val accessCheckCompletion = entityTypeId.thenCompose { etid -> entityTypes.getAsync(etid!!) }.thenApplyAsync { entityType -> entityType.properties.mapTo(mutableSetOf()) { ptid -> AccessCheck(AclKey(entitySetId, ptid), EnumSet.of(Permission.READ)) } } val transporterColumnsCompletion = entityTypeId.thenCompose { etid -> requireNotNull(etid) { "Entity set $entitySetId has no entity type" } transporterState.submitToKey(etid, GetPropertyTypesFromTransporterColumnSetEntryProcessor()) }.thenCompose { transporterPtIds -> propertyTypes.submitToKeys(transporterPtIds, GetFqnFromPropertyTypeEntryProcessor()) } val userToPermissionsCompletion = userToPrincipalsCompletion.thenCombine(accessCheckCompletion) { userToPrincipals, accessChecks -> userToPrincipals.mapValues { (_, principals) -> authorizationManager.accessChecksForPrincipals(accessChecks, principals).filter { it.permissions[Permission.READ]!! }.map { it.aclKey[1] }.toList() } } userToPermissionsCompletion.thenCombine(transporterColumnsCompletion) { userToPtCols, transporterColumns -> val userToEntitySetColumnNames = userToPtCols.mapValues { (_, columns) -> columns.map { transporterColumns.get(it).toString() } } entitySets.submitToKey(entitySetId, TransportEntitySetEntryProcessor(transporterColumns, organizationId, userToEntitySetColumnNames) .init(transporterDatastore) ) }.toCompletableFuture().get().toCompletableFuture().get() } /*GET*/ fun getExternalDatabaseTables(orgId: UUID): Set<Map.Entry<UUID, OrganizationExternalDatabaseTable>> { return organizationExternalDatabaseTables.entrySet(belongsToOrganization(orgId)) } fun getExternalDatabaseTablesWithColumns(orgId: UUID): Map<Pair<UUID, OrganizationExternalDatabaseTable>, Set<Map.Entry<UUID, OrganizationExternalDatabaseColumn>>> { val tables = getExternalDatabaseTables(orgId) return tables.map { Pair(it.key, it.value) to (organizationExternalDatabaseColumns.entrySet(belongsToTable(it.key))) }.toMap() } fun getExternalDatabaseTableWithColumns(tableId: UUID): OrganizationExternalDatabaseTableColumnsPair { val table = getOrganizationExternalDatabaseTable(tableId) return OrganizationExternalDatabaseTableColumnsPair(table, organizationExternalDatabaseColumns.values(belongsToTable(tableId)).toSet()) } fun getExternalDatabaseTableData( orgId: UUID, tableId: UUID, authorizedColumns: Set<OrganizationExternalDatabaseColumn>, rowCount: Int): Map<UUID, List<Any?>> { val tableName = organizationExternalDatabaseTables.getValue(tableId).name val columnNamesSql = authorizedColumns.joinToString(", ") { it.name } val dataByColumnId = mutableMapOf<UUID, MutableList<Any?>>() val sql = "SELECT $columnNamesSql FROM $tableName LIMIT $rowCount" BasePostgresIterable( StatementHolderSupplier(externalDbManager.connectToOrg(orgId), sql) ) { rs -> val pairsList = mutableListOf<Pair<UUID, Any?>>() authorizedColumns.forEach { pairsList.add(it.id to rs.getObject(it.name)) } return@BasePostgresIterable pairsList }.forEach { pairsList -> pairsList.forEach { dataByColumnId.getOrPut(it.first) { mutableListOf() }.add(it.second) } } return dataByColumnId } fun getOrganizationExternalDatabaseTable(tableId: UUID): OrganizationExternalDatabaseTable { return organizationExternalDatabaseTables.getValue(tableId) } fun getOrganizationExternalDatabaseColumn(columnId: UUID): OrganizationExternalDatabaseColumn { return organizationExternalDatabaseColumns.getValue(columnId) } fun getColumnNamesByTableName(dbName: String): Map<String, TableSchemaInfo> { val columnNamesByTableName = mutableMapOf<String, TableSchemaInfo>() val sql = getCurrentTableAndColumnNamesSql() BasePostgresIterable( StatementHolderSupplier(externalDbManager.connect(dbName), sql, FETCH_SIZE) ) { rs -> TableInfo(oid(rs), name(rs) , columnName(rs)) } .forEach { columnNamesByTableName .getOrPut(it.tableName) { TableSchemaInfo(it.oid, mutableSetOf()) }.columnNames.add(it.columnName) } return columnNamesByTableName } /*UPDATE*/ fun updateOrganizationExternalDatabaseTable(orgId: UUID, tableFqnToId: Pair<String, UUID>, update: MetadataUpdate) { update.name.ifPresent { val newTableFqn = FullQualifiedName(orgId.toString(), it) val oldTableName = getNameFromFqnString(tableFqnToId.first) externalDbManager.connectToOrg(orgId).connection.use { conn -> val stmt = conn.createStatement() stmt.execute("ALTER TABLE $oldTableName RENAME TO $it") } aclKeyReservations.renameReservation(tableFqnToId.second, newTableFqn.fullQualifiedNameAsString) } organizationExternalDatabaseTables.submitToKey(tableFqnToId.second, UpdateOrganizationExternalDatabaseTableEntryProcessor(update)) } fun updateOrganizationExternalDatabaseColumn(orgId: UUID, tableFqnToId: Pair<String, UUID>, columnFqnToId: Pair<String, UUID>, update: MetadataUpdate) { update.name.ifPresent { val tableName = getNameFromFqnString(tableFqnToId.first) val newColumnFqn = FullQualifiedName(tableFqnToId.second.toString(), it) val oldColumnName = getNameFromFqnString(columnFqnToId.first) externalDbManager.connectToOrg(orgId).connection.use { conn -> val stmt = conn.createStatement() stmt.execute("ALTER TABLE $tableName RENAME COLUMN $oldColumnName to $it") } aclKeyReservations.renameReservation(columnFqnToId.second, newColumnFqn.fullQualifiedNameAsString) } organizationExternalDatabaseColumns.submitToKey(columnFqnToId.second, UpdateOrganizationExternalDatabaseColumnEntryProcessor(update)) } /*DELETE*/ fun deleteOrganizationExternalDatabaseTables(orgId: UUID, tableIdByFqn: Map<String, UUID>) { tableIdByFqn.forEach { (tableFqn, tableId) -> val tableName = getNameFromFqnString(tableFqn) //delete columns from tables val tableFqnToId = Pair(tableFqn, tableId) val columnIdByFqn = organizationExternalDatabaseColumns .entrySet(belongsToTable(tableId)) .map { FullQualifiedName(tableId.toString(), it.value.name).toString() to it.key } .toMap() val columnsByTable = mapOf(tableFqnToId to columnIdByFqn) deleteOrganizationExternalDatabaseColumns(orgId, columnsByTable) //delete tables from postgres externalDbManager.connectToOrg(orgId).connection.use { conn -> val stmt = conn.createStatement() stmt.execute("DROP TABLE $tableName") } } //delete securable object val tableIds = tableIdByFqn.values.toSet() deleteOrganizationExternalDatabaseTableObjects(tableIds) } fun deleteOrganizationExternalDatabaseTableObjects(tableIds: Set<UUID>) { tableIds.forEach { val aclKey = AclKey(it) authorizationManager.deletePermissions(aclKey) securableObjectTypes.remove(aclKey) aclKeyReservations.release(it) } organizationExternalDatabaseTables.removeAll(idsPredicate(tableIds)) } fun deleteOrganizationExternalDatabaseColumns(orgId: UUID, columnsByTable: Map<Pair<String, UUID>, Map<String, UUID>>) { columnsByTable.forEach { (tableFqnToId, columnIdsByFqn) -> if (columnIdsByFqn.isEmpty()) return@forEach val tableName = getNameFromFqnString(tableFqnToId.first) val tableId = tableFqnToId.second val columnNames = columnIdsByFqn.keys.map { getNameFromFqnString(it) }.toSet() val columnIds = columnIdsByFqn.values.toSet() //delete columns from postgres val dropColumnsSql = createDropColumnSql(columnNames) externalDbManager.connectToOrg(orgId).connection.use { conn -> val stmt = conn.createStatement() stmt.execute("ALTER TABLE $tableName $dropColumnsSql") } deleteOrganizationExternalDatabaseColumnObjects(mapOf(tableId to columnIds)) } } fun deleteOrganizationExternalDatabaseColumnObjects(columnIdsByTableId: Map<UUID, Set<UUID>>) { columnIdsByTableId.forEach { (tableId, columnIds) -> columnIds.forEach { columnId -> val aclKey = AclKey(tableId, columnId) authorizationManager.deletePermissions(aclKey) securableObjectTypes.remove(aclKey) aclKeyReservations.release(columnId) } organizationExternalDatabaseColumns.removeAll(idsPredicate(columnIds)) } } /** * Deletes an organization's entire database. * Is called when an organization is deleted. */ fun deleteOrganizationExternalDatabase(orgId: UUID) { //remove all tables/columns within org val tableIdByFqn = organizationExternalDatabaseTables .entrySet(belongsToOrganization(orgId)) .map { FullQualifiedName(orgId.toString(), it.value.name).toString() to it.key } .toMap() deleteOrganizationExternalDatabaseTables(orgId, tableIdByFqn) //drop db from schema val dbName = externalDbManager.getOrganizationDatabaseName(orgId) externalDbManager.connect(dbName).connection.use { conn -> val stmt = conn.createStatement() stmt.execute(dropAllConnectionsToDatabaseSql(dbName)) stmt.execute("DROP DATABASE $dbName") } } /*PERMISSIONS*/ fun addHBARecord(orgId: UUID, userPrincipal: Principal, connectionType: PostgresConnectionType, ipAddress: String) { val dbName = externalDbManager.getOrganizationDatabaseName(orgId) val username = getDBUser(userPrincipal.id) val record = PostgresAuthenticationRecord( connectionType, dbName, username, ipAddress, organizationExternalDatabaseConfiguration.authMethod) hds.connection.use { connection -> connection.createStatement().use { stmt -> val hbaTable = PostgresTable.HBA_AUTHENTICATION_RECORDS val columns = hbaTable.columns.joinToString(", ", "(", ")") { it.name } val pkey = hbaTable.primaryKey.joinToString(", ", "(", ")") { it.name } val insertRecordSql = getInsertRecordSql(hbaTable, columns, pkey, record) stmt.executeUpdate(insertRecordSql) } } updateHBARecords(dbName) } fun removeHBARecord(orgId: UUID, userPrincipal: Principal, connectionType: PostgresConnectionType, ipAddress: String) { val dbName = externalDbManager.getOrganizationDatabaseName(orgId) val username = getDBUser(userPrincipal.id) val record = PostgresAuthenticationRecord( connectionType, dbName, username, ipAddress, organizationExternalDatabaseConfiguration.authMethod) hds.connection.use { val stmt = it.createStatement() val hbaTable = PostgresTable.HBA_AUTHENTICATION_RECORDS val deleteRecordSql = getDeleteRecordSql(hbaTable, record) stmt.executeUpdate(deleteRecordSql) } updateHBARecords(dbName) } fun getOrganizationOwners(orgId: UUID): Set<SecurablePrincipal> { val principals = securePrincipalsManager.getAuthorizedPrincipalsOnSecurableObject(AclKey(orgId), EnumSet.of(Permission.OWNER)) return securePrincipalsManager.getSecurablePrincipals(principals).toSet() } /** * Sets privileges for a user on an organization's column */ fun executePrivilegesUpdate(action: Action, columnAcls: List<Acl>) { val columnIds = columnAcls.map { it.aclKey[1] }.toSet() val columnsById = organizationExternalDatabaseColumns.getAll(columnIds) val columnAclsByOrg = columnAcls.groupBy { columnsById.getValue(it.aclKey[1]).organizationId } columnAclsByOrg.forEach { (orgId, columnAcls) -> externalDbManager.connectToOrg(orgId).connection.use { conn -> conn.autoCommit = false val stmt = conn.createStatement() columnAcls.forEach { val tableAndColumnNames = getTableAndColumnNames(AclKey(it.aclKey)) val tableName = tableAndColumnNames.first val columnName = tableAndColumnNames.second it.aces.forEach { ace -> if (!areValidPermissions(ace.permissions)) { throw IllegalStateException("Permissions ${ace.permissions} are not valid") } val dbUser = getDBUser(ace.principal.id) //revoke any previous privileges before setting specified ones if (action == Action.SET) { val revokeSql = createPrivilegesUpdateSql(Action.REMOVE, listOf("ALL"), tableName, columnName, dbUser) stmt.addBatch(revokeSql) } val privileges = getPrivilegesFromPermissions(ace.permissions) val grantSql = createPrivilegesUpdateSql(action, privileges, tableName, columnName, dbUser) stmt.addBatch(grantSql) } stmt.executeBatch() conn.commit() } } } } /** * Revokes all privileges for a user on an organization's database * when that user is removed from an organization. */ fun revokeAllPrivilegesFromMember(orgId: UUID, userId: String) { val dbName = externalDbManager.getOrganizationDatabaseName(orgId) val userName = getDBUser(userId) externalDbManager.connect(dbName).connection.use { conn -> val stmt = conn.createStatement() stmt.execute("REVOKE ALL ON DATABASE $dbName FROM $userName") } } fun syncPermissions( orgOwnerIds: List<UUID>, orgId: UUID, tableId: UUID, tableName: String, maybeColumnId: Optional<UUID>, maybeColumnName: Optional<String> ): List<Acl> { val privilegesByUser = HashMap<UUID, MutableSet<PostgresPrivileges>>() val aclKeyUUIDs = mutableListOf(tableId) var objectType = SecurableObjectType.OrganizationExternalDatabaseTable var aclKey = AclKey(aclKeyUUIDs) val ownerPrivileges = PostgresPrivileges.values().toMutableSet() ownerPrivileges.remove(PostgresPrivileges.ALL) //if column objects, sync postgres privileges maybeColumnId.ifPresent { columnId -> aclKeyUUIDs.add(columnId) aclKey = AclKey(aclKeyUUIDs) val privilegesFields = getPrivilegesFields(tableName, maybeColumnName) val sql = privilegesFields.first objectType = privilegesFields.second BasePostgresIterable( StatementHolderSupplier(externalDbManager.connectToOrg(orgId), sql) ) { rs -> user(rs) to PostgresPrivileges.valueOf(privilegeType(rs).toUpperCase()) } .filter { isPostgresUserName(it.first) } .forEach { val securablePrincipalId = getSecurablePrincipalIdFromUserName(it.first) privilegesByUser.getOrPut(securablePrincipalId) { mutableSetOf() }.add(it.second) } } //give organization owners all privileges orgOwnerIds.forEach { orgOwnerId -> privilegesByUser.getOrPut(orgOwnerId) { mutableSetOf() }.addAll(ownerPrivileges) } return privilegesByUser.map { (securablePrincipalId, privileges) -> val principal = securePrincipalsManager.getSecurablePrincipalById(securablePrincipalId).principal val aceKey = AceKey(aclKey, principal) val permissions = EnumSet.noneOf(Permission::class.java) if (privileges == ownerPrivileges) { permissions.addAll(setOf(Permission.OWNER, Permission.READ, Permission.WRITE)) } else { if (privileges.contains(PostgresPrivileges.SELECT)) { permissions.add(Permission.READ) } if (privileges.contains(PostgresPrivileges.INSERT) || privileges.contains(PostgresPrivileges.UPDATE)) permissions.add(Permission.WRITE) } aces.executeOnKey(aceKey, PermissionMerger(permissions, objectType, OffsetDateTime.MAX)) return@map Acl(aclKeyUUIDs, setOf(Ace(principal, permissions, Optional.empty()))) } } /*PRIVATE FUNCTIONS*/ private fun getNameFromFqnString(fqnString: String): String { return FullQualifiedName(fqnString).name } private fun createDropColumnSql(columnNames: Set<String>): String { return columnNames.joinToString(", ") { "DROP COLUMN ${quote(it)}" } } private fun createPrivilegesUpdateSql(action: Action, privileges: List<String>, tableName: String, columnName: String, dbUser: String): String { val privilegesAsString = privileges.joinToString(separator = ", ") checkState(action == Action.REMOVE || action == Action.ADD || action == Action.SET, "Invalid action $action specified") return if (action == Action.REMOVE) { "REVOKE $privilegesAsString (${quote(columnName)}) ON $tableName FROM $dbUser" } else { "GRANT $privilegesAsString (${quote(columnName)}) ON $tableName TO $dbUser" } } private fun getTableAndColumnNames(aclKey: AclKey): Pair<String, String> { val securableObjectId = aclKey[1] val organizationAtlasColumn = organizationExternalDatabaseColumns.getValue(securableObjectId) val tableName = organizationExternalDatabaseTables.getValue(organizationAtlasColumn.tableId).name val columnName = organizationAtlasColumn.name return Pair(tableName, columnName) } private fun getDBUser(principalId: String): String { val securePrincipal = securePrincipalsManager.getPrincipal(principalId) checkState(securePrincipal.principalType == PrincipalType.USER, "Principal must be of type USER") return dbCredentialService.getDbUsername(securePrincipal) } private fun areValidPermissions(permissions: Set<Permission>): Boolean { if (!(permissions.contains(Permission.OWNER) || permissions.contains(Permission.READ) || permissions.contains(Permission.WRITE))) { return false } else if (permissions.isEmpty()) { return false } return true } private fun getPrivilegesFromPermissions(permissions: Set<Permission>): List<String> { val privileges = mutableListOf<String>() if (permissions.contains(Permission.OWNER)) { privileges.add(PostgresPrivileges.ALL.toString()) } else { if (permissions.contains(Permission.WRITE)) { privileges.addAll(listOf( PostgresPrivileges.INSERT.toString(), PostgresPrivileges.UPDATE.toString())) } if (permissions.contains(Permission.READ)) { privileges.add(PostgresPrivileges.SELECT.toString()) } } return privileges } private fun getPrivilegesFields(tableName: String, maybeColumnName: Optional<String>): Pair<String, SecurableObjectType> { var columnCondition = "" var grantsTableName = "information_schema.role_table_grants" var objectType = SecurableObjectType.OrganizationExternalDatabaseTable if (maybeColumnName.isPresent) { val columnName = maybeColumnName.get() columnCondition = "AND column_name = '$columnName'" grantsTableName = "information_schema.role_column_grants" objectType = SecurableObjectType.OrganizationExternalDatabaseColumn } val sql = getCurrentUsersPrivilegesSql(tableName, grantsTableName, columnCondition) return Pair(sql, objectType) } private fun updateHBARecords(dbName: String) { val originalHBAPath = Paths.get(organizationExternalDatabaseConfiguration.path + organizationExternalDatabaseConfiguration.fileName) val tempHBAPath = Paths.get(organizationExternalDatabaseConfiguration.path + "/temp_hba.conf") //create hba file with new records val records = getHBARecords(PostgresTable.HBA_AUTHENTICATION_RECORDS.name) .map { it.buildHBAConfRecord() }.toSet() try { val out = BufferedOutputStream( Files.newOutputStream(tempHBAPath, StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING) ) records.forEach { val recordAsByteArray = it.toByteArray() out.write(recordAsByteArray) } out.close() //reload config externalDbManager.connect(dbName).connection.use { conn -> val stmt = conn.createStatement() stmt.executeQuery(getReloadConfigSql()) } } catch (ex: IOException) { logger.info("IO exception while creating new hba config") } //replace old hba with new hba try { Files.move(tempHBAPath, originalHBAPath, StandardCopyOption.REPLACE_EXISTING) } catch (ex: IOException) { logger.info("IO exception while updating hba config") } } private fun getHBARecords(tableName: String): BasePostgresIterable<PostgresAuthenticationRecord> { return BasePostgresIterable( StatementHolderSupplier(hds, getSelectRecordsSql(tableName)) ) { rs -> postgresAuthenticationRecord(rs) } } /** * Moves a table from the [OPENLATTICE_SCHEMA] schema to the [STAGING_SCHEMA] schema */ fun promoteStagingTable(organizationId: UUID, tableName: String) { externalDbManager.connectToOrg(organizationId).use { hds -> hds.connection.use { conn -> conn.createStatement().use { stmt -> stmt.execute(publishStagingTableSql(tableName)) } } } } /*INTERNAL SQL QUERIES*/ private fun getCurrentTableAndColumnNamesSql(): String { return selectExpression + fromExpression + leftJoinColumnsExpression + "WHERE information_schema.tables.table_schema=ANY('{$OPENLATTICE_SCHEMA,$STAGING_SCHEMA}') " + "AND table_type='BASE TABLE'" } private fun getColumnMetadataSql(tableName: String, columnCondition: String): String { return selectExpression + ", information_schema.columns.data_type AS datatype, " + "information_schema.columns.ordinal_position, " + "information_schema.table_constraints.constraint_type " + fromExpression + leftJoinColumnsExpression + "LEFT OUTER JOIN information_schema.constraint_column_usage ON " + "information_schema.columns.column_name = information_schema.constraint_column_usage.column_name " + "AND information_schema.columns.table_name = information_schema.constraint_column_usage.table_name " + "LEFT OUTER JOIN information_schema.table_constraints " + "ON information_schema.constraint_column_usage.constraint_name = " + "information_schema.table_constraints.constraint_name " + "WHERE information_schema.columns.table_name = '$tableName' " + "AND (information_schema.table_constraints.constraint_type = 'PRIMARY KEY' " + "OR information_schema.table_constraints.constraint_type IS NULL)" + columnCondition } private fun getCurrentUsersPrivilegesSql(tableName: String, grantsTableName: String, columnCondition: String): String { return "SELECT grantee AS user, privilege_type " + "FROM $grantsTableName " + "WHERE table_name = '$tableName' " + columnCondition } private fun getReloadConfigSql(): String { return "SELECT pg_reload_conf()" } private val selectExpression = "SELECT oid, information_schema.tables.table_name AS name, information_schema.columns.column_name " private val fromExpression = "FROM information_schema.tables " private val leftJoinColumnsExpression0 = "LEFT JOIN pg_class ON relname = information_schema.tables.table_name " private val leftJoinColumnsExpression = "LEFT JOIN information_schema.columns ON information_schema.tables.table_name = information_schema.columns.table_name $leftJoinColumnsExpression0" private fun getInsertRecordSql(table: PostgresTableDefinition, columns: String, pkey: String, record: PostgresAuthenticationRecord): String { return "INSERT INTO ${table.name} $columns VALUES(${record.buildPostgresRecord()}) " + "ON CONFLICT $pkey DO UPDATE SET ${PostgresColumn.AUTHENTICATION_METHOD.name}=EXCLUDED.${PostgresColumn.AUTHENTICATION_METHOD.name}" } private fun getDeleteRecordSql(table: PostgresTableDefinition, record: PostgresAuthenticationRecord): String { return "DELETE FROM ${table.name} WHERE ${PostgresColumn.USERNAME.name} = '${record.username}' " + "AND ${PostgresColumn.DATABASE.name} = '${record.database}' " + "AND ${PostgresColumn.CONNECTION_TYPE.name} = '${record.connectionType}' " + "AND ${PostgresColumn.IP_ADDRESS.name} = '${record.ipAddress}'" } private fun getSelectRecordsSql(tableName: String): String { return "SELECT * FROM $tableName" } /*PREDICATES*/ private fun <T> idsPredicate(ids: Set<UUID>): Predicate<UUID, T> { return Predicates.`in`(QueryConstants.KEY_ATTRIBUTE_NAME.value(), *ids.toTypedArray()) } private fun belongsToOrganization(orgId: UUID): Predicate<UUID, OrganizationExternalDatabaseTable> { return Predicates.equal(ORGANIZATION_ID_INDEX, orgId) } private fun belongsToTable(tableId: UUID): Predicate<UUID, OrganizationExternalDatabaseColumn> { return Predicates.equal(TABLE_ID_INDEX, tableId) } private fun publishStagingTableSql(tableName: String): String { return "ALTER TABLE ${quote(tableName)} SET SCHEMA $OPENLATTICE_SCHEMA" } } data class TableSchemaInfo( val oid: Int, val columnNames: MutableSet<String> ) data class TableInfo( val oid : Int, val tableName: String, val columnName: String )
gpl-3.0
b8707ea974aa1ce6cc0bcc3a0b990a9c
46.786089
190
0.677524
5.071309
false
false
false
false
MyDogTom/detekt
detekt-rules/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/style/naming/VariableMinLength.kt
1
1208
package io.gitlab.arturbosch.detekt.rules.style.naming import io.gitlab.arturbosch.detekt.api.CodeSmell import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.api.Debt import io.gitlab.arturbosch.detekt.api.Entity import io.gitlab.arturbosch.detekt.api.Issue import io.gitlab.arturbosch.detekt.api.Severity import io.gitlab.arturbosch.detekt.rules.SubRule import org.jetbrains.kotlin.psi.KtVariableDeclaration class VariableMinLength(config: Config = Config.empty) : SubRule<KtVariableDeclaration>(config) { override val issue = Issue(javaClass.simpleName, Severity.Style, debt = Debt.FIVE_MINS) private val minimumVariableNameLength = valueOrDefault(MINIMUM_VARIABLE_NAME_LENGTH, DEFAULT_MINIMUM_VARIABLE_NAME_LENGTH) override fun apply(element: KtVariableDeclaration) { if (element.identifierName().length < minimumVariableNameLength) { report(CodeSmell( issue.copy(description = "Variable names should be at least $minimumVariableNameLength characters long."), Entity.from(element))) } } companion object { const val MINIMUM_VARIABLE_NAME_LENGTH = "minimumVariableNameLength" private const val DEFAULT_MINIMUM_VARIABLE_NAME_LENGTH = 3 } }
apache-2.0
e3501ec4efe7742625c96e3fca9da99c
37.967742
111
0.798841
3.847134
false
true
false
false
Vakosta/Chapper
app/src/main/java/org/chapper/chapper/presentation/screen/intro/ImagePickSlide.kt
1
2801
package org.chapper.chapper.presentation.screen.intro import agency.tango.materialintroscreen.SlideFragment import android.Manifest import android.app.Activity.RESULT_OK import android.content.Intent import android.content.pm.PackageManager import android.graphics.Bitmap import android.os.Bundle import android.support.v4.app.ActivityCompat import android.support.v4.content.ContextCompat import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import com.mvc.imagepicker.ImagePicker import de.hdodenhof.circleimageview.CircleImageView import org.chapper.chapper.R import org.chapper.chapper.data.Constants import org.chapper.chapper.data.repository.SettingsRepository import kotlin.properties.Delegates class ImagePickSlide : SlideFragment() { private var mPhoto: CircleImageView by Delegates.notNull() private var mPickButton: Button by Delegates.notNull() override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.fragment_image_pick_slide, container, false) mPhoto = view.findViewById(R.id.selectedPhotoImageView) mPickButton = view.findViewById(R.id.pickButton) mPickButton.setOnClickListener { pick() } return view } override fun backgroundColor(): Int = R.color.colorPrimary override fun buttonsColor(): Int = R.color.colorAccent override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (resultCode == RESULT_OK && data != null) { val bitmap: Bitmap = ImagePicker.getImageFromResult(activity!!.applicationContext, requestCode, resultCode, data)!! mPhoto.setImageBitmap(bitmap) SettingsRepository.setProfilePhoto(activity!!.applicationContext, bitmap) } } private fun pick() { val permissionCheck = ContextCompat.checkSelfPermission(activity!!.applicationContext, Manifest.permission.WRITE_EXTERNAL_STORAGE) if (permissionCheck != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(activity!!, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), Constants.WRITE_EXTERNAL_STORAGE_PERMISSIONS) return } ImagePicker.pickImage(this) } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { when (requestCode) { Constants.WRITE_EXTERNAL_STORAGE_PERMISSIONS -> { if ((grantResults.isNotEmpty()) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) { pick() } } } } }
gpl-2.0
2aaf52039cacf454921ef1f2f6b7c717
35.868421
138
0.715459
4.820998
false
false
false
false
sangcomz/FishBun
FishBun/src/main/java/com/sangcomz/fishbun/permission/PermissionCheck.kt
1
3229
package com.sangcomz.fishbun.permission import android.Manifest.permission.* import android.annotation.TargetApi import android.app.Activity import android.content.Context import android.content.pm.PackageManager import android.os.Build import android.widget.Toast import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import com.sangcomz.fishbun.R /** * Created by sangc on 2015-10-12. */ class PermissionCheck(private val context: Context) { private fun checkPermission(permissionList: List<String>, requestCode: Int): Boolean { if (context !is Activity) return false val needRequestPermissionList = permissionList .map { it to ContextCompat.checkSelfPermission(context, it) } .filter { it.second != PackageManager.PERMISSION_GRANTED } .map { it.first } .toTypedArray() return if (needRequestPermissionList.isEmpty()) { true } else { if (ActivityCompat.shouldShowRequestPermissionRationale( context, needRequestPermissionList.first() ) ) { ActivityCompat.requestPermissions(context, needRequestPermissionList, requestCode) } else { ActivityCompat.requestPermissions(context, needRequestPermissionList, requestCode) } false } } fun checkStoragePermission(requestCode: Int): Boolean { return when { Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU -> { checkStoragePermissionUnderAPI33(requestCode) } Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU -> { checkStoragePermissionOrHigherAPI33(requestCode) } else -> true } } @TargetApi(Build.VERSION_CODES.M) fun checkStoragePermissionUnderAPI33(requestCode: Int): Boolean { return checkPermission( arrayListOf(READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE), requestCode ) } @TargetApi(Build.VERSION_CODES.TIRAMISU) fun checkStoragePermissionOrHigherAPI33(requestCode: Int): Boolean { return checkPermission( arrayListOf(READ_MEDIA_IMAGES), requestCode ) } @TargetApi(Build.VERSION_CODES.M) fun checkCameraPermission(requestCode: Int): Boolean { try { val info = context.packageManager.getPackageInfo( context.packageName, PackageManager.GET_PERMISSIONS ) //This array contains the requested permissions. val permissions = info.requestedPermissions return if (permissions?.contains(CAMERA) == true) { checkPermission(listOf(CAMERA), requestCode) } else { false } } catch (e: PackageManager.NameNotFoundException) { e.printStackTrace() return false } } fun showPermissionDialog() { Toast.makeText(context, R.string.msg_permission, Toast.LENGTH_SHORT).show() } }
apache-2.0
cca263e04afe7f070e3578fffca706f8
32.298969
98
0.624032
5.208065
false
false
false
false
jjoller/foxinabox
src/jjoller/foxinabox/FiveCardValue.kt
1
16337
package jjoller.foxinabox import java.util.Arrays import java.util.EnumSet import jjoller.foxinabox.Card.CardValue /** * Try all combinations of five cards and find out which has the highest * value. * @param hand * * A Hand of at least five cards. * * * * * @param flush * * If set to false do not look at the suit of the cards. */ public class FiveCardValue(hand: EnumSet<Card>, flush: Boolean = true) : Comparable<FiveCardValue> { // private EnumSet<Card> hand; val hand: EnumSet<Card> val rank: Int init { // precondition if (hand.size < 5) throw IllegalArgumentException( "the Hand contains less than five Cards.") var bestRank = Integer.MIN_VALUE var bestCombination: EnumSet<Card>? = null; val numCards = hand.size var iter = hand.iterator(); val cards = Array(numCards, { iter.next() }) //var cards = hand.toArray() // array elements are sorted by index, starting with the lowest index. // Card[] cards = hand.toArray(new Card[numCards]); for (p in 0..numCards - 4 - 1) { for (o in p + 1..numCards - 3 - 1) { for (k in o + 1..numCards - 2 - 1) { for (e in k + 1..numCards - 1 - 1) { for (r in e + 1..numCards - 1) { val c0 = cards[p] val c1 = cards[o] val c2 = cards[k] val c3 = cards[e] val c4 = cards[r] val v0: Int val v1: Int val v2: Int val v3: Int val v4: Int v0 = c0.value.ordinal v1 = c1.value.ordinal v2 = c2.value.ordinal v3 = c3.value.ordinal v4 = c4.value.ordinal var rank = RANKING.rank[v0][v1][v2][v3][v4] if (flush) { if (isFlush(c0, c1, c2, c3, c4)) { if (RANKING.isStraight(v0, v1, v2, v3, v4)) { // straight flush rank = rank - RANKING.straightRank + RANKING.straightFlushRank } else { // normal flush rank = RANKING.flushRank + (rank - RANKING.minRank) } } } if (rank > bestRank) { bestRank = rank bestCombination = EnumSet.of(c0, c1, c2, c3, c4) } } } } } } this.hand = bestCombination!! this.rank = bestRank } val handValue: HandValueType get() { var iter = hand.iterator(); return getHandValueType(iter.next(), iter.next(), iter.next(), iter.next(), iter.next()) } /** * returns a positive number if this Value is better than the given * FiveCardValue. Returns 0 if the given value is equal this value. */ override fun compareTo(o: FiveCardValue): Int { return rank - o.rank } fun isBetterThan(o: FiveCardValue): Boolean { return rank > o.rank } fun isEqual(o: FiveCardValue): Boolean { return rank == o.rank } override fun toString(): String { var s = "" val v = handValue val fiveCardValues = arrayOfNulls<CardValue>(5) var i = 0 for (c in hand!!) { fiveCardValues[i++] = c.value } s += v when (v) { FiveCardValue.HandValueType.HIGH_CARD -> s += " " + fiveCardValues[0] + " " + fiveCardValues[1] + " " + fiveCardValues[2] + " " + fiveCardValues[3] + " " + fiveCardValues[4] FiveCardValue.HandValueType.PAIR -> s += " " + fiveCardValues[0] + " " + fiveCardValues[1] + " " + fiveCardValues[2] + " " + fiveCardValues[3] + " " + fiveCardValues[4] FiveCardValue.HandValueType.TWO_PAIR -> s += " " + fiveCardValues[0] + " " + fiveCardValues[1] + " " + fiveCardValues[2] + " " + fiveCardValues[3] + " " + fiveCardValues[4] FiveCardValue.HandValueType.THREE_OF_A_KIND -> s += " " + fiveCardValues[0] + " " + fiveCardValues[1] + " " + fiveCardValues[2] + " " + fiveCardValues[3] + " " + fiveCardValues[4] FiveCardValue.HandValueType.STRAIGHT -> if (fiveCardValues[0] === CardValue.ACE && fiveCardValues[1] === CardValue.FIVE) { s += " " + fiveCardValues[1] + " high" } else { s += " " + fiveCardValues[0] + " high" } FiveCardValue.HandValueType.FLUSH -> s += " " + fiveCardValues[0] + " " + fiveCardValues[1] + " " + fiveCardValues[2] + " " + fiveCardValues[3] + " " + fiveCardValues[4] FiveCardValue.HandValueType.FULL_HOUSE -> if (fiveCardValues[0] === fiveCardValues[2]) { s += " " + fiveCardValues[0] + "s, full of " + fiveCardValues[3] + "s" } else { s += " " + fiveCardValues[3] + "s, full of " + fiveCardValues[0] + "s" } FiveCardValue.HandValueType.FOUR_OF_A_KIND -> if (fiveCardValues[0] === fiveCardValues[1]) { s += " " + fiveCardValues[0] + "s, " + fiveCardValues[4] + " kicker" } else { s += " " + fiveCardValues[1] + "s, " + fiveCardValues[0] + " kicker" } FiveCardValue.HandValueType.STRAIGHT_FLUSH -> if (fiveCardValues[0] === CardValue.ACE && fiveCardValues[1] === CardValue.FIVE) { s += " " + fiveCardValues[1] + " high" } else { s += " " + fiveCardValues[0] + " high" } } return s } internal class HandValueRanking constructor() { val rank = Array(13) { Array(13) { Array(13) { Array(13) { IntArray(13) } } } } private var count: Int = 0 var flushRank: Int = 0 var straightRank: Int = 0 var fullHouseRank: Int = 0 var fourOfAKindRank: Int = 0 var straightFlushRank: Int = 0 var maxRank: Int = 0 var minRank: Int = 0 init { count = Integer.MAX_VALUE / 2 maxRank = count + 9 // the number of different straight flushs straightFlushRank = count putFourOfAKind() fourOfAKindRank = count putFullHouse() fullHouseRank = count count -= 13 * 12 * 11 * 10 * 9 flushRank = count count-- putStraight() straightRank = count putThreeOfAKind() putTwoPair() putPair() putHighCard() minRank = count } // private void fill() { // // // // } private fun putFourOfAKind() { for (p in 0..12) { for (o in 0..12) { if (areDifferent(p, o)) { put(p, p, p, p, o, count--) } } } } private fun putFullHouse() { for (p in 0..12) { for (o in 0..12) { if (areDifferent(p, o)) { put(p, p, p, o, o, count--) } } } } private fun putStraight() { // straight five high for (p in 0..8) { rank[p][p + 1][p + 2][p + 3][p + 4] = count-- } rank[0][9][10][11][12] = count-- } private fun putThreeOfAKind() { for (p in 0..12) { for (o in 0..12) { for (k in o..12) { if (areDifferent(p, o, k)) { put(p, p, p, o, k, count--) } } } } } private fun putTwoPair() { for (p in 0..12) { for (o in p..12) { for (k in 0..12) { if (areDifferent(p, o, k)) { put(p, p, o, o, k, count--) } } } } } private fun putPair() { for (p in 0..12) { for (o in 0..12) { for (k in o..12) { for (e in k..12) { if (areDifferent(p, o, k, e)) { put(p, p, o, k, e, count--) } } } } } } private fun putHighCard() { for (p in 0..12) { for (o in p + 1..12) { for (k in o + 1..12) { for (e in k + 1..12) { for (r in e + 1..12) { if (areDifferent(p, o, k, e, r) && !isStraight(p, o, k, e, r)) { put(p, o, k, e, r, count--) } } } } } } } private fun put(p: Int, o: Int, k: Int, e: Int, r: Int, count: Int) { val i = IntArray(5) i[0] = p i[1] = o i[2] = k i[3] = e i[4] = r Arrays.sort(i) rank[i[0]][i[1]][i[2]][i[3]][i[4]] = count } private fun areDifferent(vararg a: Int): Boolean { val n = a.size for (i in 0..n - 1) { for (j in 0..n - 1) { if (i != j) { if (a[i] == a[j]) { return false } } } } return true } fun isPair(p: Int, o: Int, k: Int, e: Int, r: Int): Boolean { val pairs = BooleanArray(10) pairs[0] = p == o pairs[1] = p == k pairs[2] = p == e pairs[3] = p == r pairs[4] = o == k pairs[5] = o == e pairs[6] = o == r pairs[7] = k == e pairs[8] = k == r pairs[9] = e == r var result = false for (b in pairs) { if (b) { result = true break } } return result } fun isTwoPair(p: Int, o: Int, k: Int, e: Int, r: Int): Boolean { val pairs = BooleanArray(10) pairs[0] = p == o pairs[1] = p == k pairs[2] = p == e pairs[3] = p == r pairs[4] = o == k pairs[5] = o == e pairs[6] = o == r pairs[7] = k == e pairs[8] = k == r pairs[9] = e == r var numPairs = 0 for (b in pairs) { if (b) { numPairs++ } } var result = false if (numPairs == 2) { result = true } return result } fun isThreeOfAKind(p: Int, o: Int, k: Int, e: Int, r: Int): Boolean { var result = false for (i in 0..12) { var count = 0 if (p == i) { count++ } if (o == i) { count++ } if (k == i) { count++ } if (e == i) { count++ } if (r == i) { count++ } if (count == 3) { result = true break } } return result } fun isFourOfAKind(p: Int, o: Int, k: Int, e: Int, r: Int): Boolean { var result = false for (i in 0..12) { var count = 0 if (p == i) { count++ } if (o == i) { count++ } if (k == i) { count++ } if (e == i) { count++ } if (r == i) { count++ } if (count == 4) { result = true break } } return result } fun isFullHouse(p: Int, o: Int, k: Int, e: Int, r: Int): Boolean { var result: Boolean result = p == o && o == k && k != e && e == r result = result or (p == o) && o != k && k == e && e == r return result } fun isStraight(p: Int, o: Int, k: Int, e: Int, r: Int): Boolean { var isStraight = false if (o - p == 1 && k - o == 1 && e - k == 1 && r - e == 1) { isStraight = true } else if (p == 0 && o == 9 && k == 10 && e == 11 && r == 12) { isStraight = true } // // int[] a = new int[5]; // a[0] = p; // a[1] = o; // a[2] = k; // a[3] = e; // a[4] = r; // Arrays.sort(a); // boolean isStraight = true; // for (int i = 1; i < 5; i++) { // if (a[i] - a[i - 1] != 1) { // isStraight = false; // break; // } // } // straight ace to 5 // if (isStraight) // log.info("is straight: " + p + " " + o + " " + k + " " + e // + " " + r + " " + isStraight); return isStraight } } enum class HandValueType { HIGH_CARD, PAIR, TWO_PAIR, THREE_OF_A_KIND, STRAIGHT, FLUSH, FULL_HOUSE, FOUR_OF_A_KIND, STRAIGHT_FLUSH } companion object { private val RANKING = HandValueRanking() private fun getHandValueType(c0: Card, c1: Card, c2: Card, c3: Card, c4: Card): HandValueType { val p: Int val o: Int val k: Int val e: Int val r: Int p = c0.value.ordinal o = c1.value.ordinal k = c2.value.ordinal e = c3.value.ordinal r = c4.value.ordinal val flush = isFlush(c0, c1, c2, c3, c4) val isStraight = RANKING.isStraight(p, o, k, e, r) if (flush && isStraight) return HandValueType.STRAIGHT_FLUSH if (RANKING.isFourOfAKind(p, o, k, e, r)) return HandValueType.FOUR_OF_A_KIND if (RANKING.isFullHouse(p, o, k, e, r)) return HandValueType.FULL_HOUSE if (flush) return HandValueType.FLUSH if (isStraight) return HandValueType.STRAIGHT if (RANKING.isThreeOfAKind(p, o, k, e, r)) return HandValueType.THREE_OF_A_KIND if (RANKING.isTwoPair(p, o, k, e, r)) return HandValueType.TWO_PAIR if (RANKING.isPair(p, o, k, e, r)) return HandValueType.PAIR return HandValueType.HIGH_CARD } private fun isFlush(c1: Card, c2: Card, c3: Card, c4: Card, c5: Card): Boolean { return c1.suit == c2.suit && c2.suit == c3.suit && c3.suit == c4.suit && c4.suit == c5.suit } } }
mit
09e5f5924554294863cde6ac344bc00d
29.142066
191
0.378833
4.068991
false
false
false
false
LordAkkarin/Beacon
core/src/main/kotlin/tv/dotstart/beacon/core/upnp/ActionExtensions.kt
1
4149
/* * Copyright 2020 Johannes Donath <[email protected]> * and other copyright owners as documented in the project's IP log. * * 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. */ package tv.dotstart.beacon.core.upnp import kotlinx.coroutines.future.await import net.mm2d.upnp.Action import tv.dotstart.beacon.core.upnp.error.* import java.util.concurrent.CancellationException import java.util.concurrent.CompletableFuture import java.util.concurrent.CompletionException /** * Provides functions which simplify the interaction with devices. * * @author [Johannes Donath](mailto:[email protected]) * @date 02/12/2020 */ private const val errorCodeFieldName = "UPnPError/errorCode" private const val errorDescriptionFieldName = "UPnPError/errorDescription" /** * Invokes a given UPnP operation with a given set of parameters and synchronously returns a * converted response. * * @throws ActionFailedException when the action failed to execute as desired. * @throws DeviceOutOfMemoryException when the device ran out of memory while processing the action. * @throws HumanInterventionRequiredException when the action requires human intervention. * @throws InvalidActionArgumentException when the given set of arguments has been rejected. * @throws UnknownActionErrorException when an unknown error occurs. * @throws CancellationException when the thread is interrupted while awaiting the action result. */ suspend operator fun <T> Action.invoke(parameters: Map<String, String?> = emptyMap(), converter: (Map<String, String>) -> T): T { val future = CompletableFuture<T>() try { this.invoke( parameters, onResult = actionInvocation@{ if (errorCodeFieldName in it) { val errorDescription = it[errorDescriptionFieldName] ?.takeIf(String::isNotBlank) ?: "No additional information given" val errorCodeStr = it[errorCodeFieldName] val errorCode = errorCodeStr ?.toIntOrNull() ?: throw UnknownActionErrorException( "Device responded with malformed error code \"$errorCodeStr\": $errorDescription") val ex = when (errorCode) { 401, 602 -> InvalidActionException("Device rejected action: $errorDescription") 402, 600, 601, 605 -> InvalidActionArgumentException( "Device rejected arguments: $errorDescription") 501 -> ActionFailedException("Device failed to perform action: $errorDescription") 603 -> DeviceOutOfMemoryException("Device ran out of memory: $errorDescription") 604 -> HumanInterventionRequiredException( "Device requested human intervention: $errorDescription") else -> UnknownActionErrorException( "Device responded with unknown error code $errorCode: $errorDescription") } future.completeExceptionally(ex) return@actionInvocation } val result = converter(it) future.complete(result) }, onError = future::completeExceptionally, returnErrorResponse = true, ) } catch (ex: Exception) { throw UnknownActionErrorException("Unknown error occurred while invoking device action", ex) } return try { future.await() } catch (ex: CompletionException) { val cause = ex.cause if (cause is ActionException) { throw cause } throw UnknownActionErrorException( "Unknown error occurred while invoking device action", cause ?: ex) } }
apache-2.0
604afaff3dedc373b3e7e396797b7e8c
39.281553
102
0.692938
4.980792
false
false
false
false
JetBrains/anko
anko/library/static/commons/src/main/java/dialogs/AlertDialogBuilder.kt
4
9394
/* * Copyright 2016 JetBrains s.r.o. * * 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. */ @file:Suppress("unused") package org.jetbrains.anko import android.R import android.app.AlertDialog import android.content.Context import android.content.DialogInterface import android.database.Cursor import android.graphics.drawable.Drawable import android.view.KeyEvent import android.view.View import android.view.ViewManager import android.widget.ListAdapter @Deprecated("Use AlertBuilder class instead.") class AlertDialogBuilder(val ctx: Context) { private var builder: AlertDialog.Builder? = AlertDialog.Builder(ctx) /** * Returns the [AlertDialog] instance if created. * Returns null until the [show] function is called. */ var dialog: AlertDialog? = null private set constructor(ankoContext: AnkoContext<*>) : this(ankoContext.ctx) fun dismiss() { dialog?.dismiss() } private fun checkBuilder() { if (builder == null) { throw IllegalStateException("show() was already called for this AlertDialogBuilder") } } /** * Create the [AlertDialog] and display it on screen. * */ fun show(): AlertDialogBuilder { checkBuilder() dialog = builder!!.create() builder = null dialog!!.show() return this } /** * Set the [title] displayed in the dialog. */ fun title(title: CharSequence) { checkBuilder() builder!!.setTitle(title) } /** * Set the title using the given [title] resource id. */ fun title(title: Int) { checkBuilder() builder!!.setTitle(title) } /** * Set the [message] to display. */ fun message(message: CharSequence) { checkBuilder() builder!!.setMessage(message) } /** * Set the message to display using the given [message] resource id. */ fun message(message: Int) { checkBuilder() builder!!.setMessage(message) } /** * Set the resource id of the [Drawable] to be used in the title. */ fun icon(icon: Int) { checkBuilder() builder!!.setIcon(icon) } /** * Set the [icon] Drawable to be used in the title. */ fun icon(icon: Drawable) { checkBuilder() builder!!.setIcon(icon) } /** * Set the title using the custom [view]. */ fun customTitle(view: View) { checkBuilder() builder!!.setCustomTitle(view) } /** * Set the title using the custom DSL view. */ fun customTitle(dsl: ViewManager.() -> Unit) { checkBuilder() val view = ctx.UI(dsl).view builder!!.setCustomTitle(view) } /** * Set a custom [view] to be the contents of the Dialog. */ fun customView(view: View) { checkBuilder() builder!!.setView(view) } /** * Set a custom DSL view to be the contents of the Dialog. */ fun customView(dsl: ViewManager.() -> Unit) { checkBuilder() val view = ctx.UI(dsl).view builder!!.setView(view) } /** * Set if the dialog is cancellable. * * @param cancellable if true, the created dialog will be cancellable. */ fun cancellable(cancellable: Boolean = true) { checkBuilder() builder!!.setCancelable(cancellable) } /** * Sets the [callback] that will be called if the dialog is canceled. */ fun onCancel(callback: () -> Unit) { checkBuilder() builder!!.setOnCancelListener { callback() } } /** * Sets the [callback] that will be called if a key is dispatched to the dialog. */ fun onKey(callback: (keyCode: Int, e: KeyEvent) -> Boolean) { checkBuilder() builder!!.setOnKeyListener({ dialog, keyCode, event -> callback(keyCode, event) }) } /** * Set a listener to be invoked when the neutral button of the dialog is pressed. * * @param neutralText the text resource to display in the neutral button. * @param callback the callback that will be called if the neutral button is pressed. */ fun neutralButton(neutralText: Int = R.string.ok, callback: DialogInterface.() -> Unit = { dismiss() }) { neutralButton(ctx.getString(neutralText), callback) } /** * Set a listener to be invoked when the neutral button of the dialog is pressed. * * @param neutralText the text to display in the neutral button. * @param callback the callback that will be called if the neutral button is pressed. */ fun neutralButton(neutralText: CharSequence, callback: DialogInterface.() -> Unit = { dismiss() }) { checkBuilder() builder!!.setNeutralButton(neutralText, { dialog, which -> dialog.callback() }) } /** * Set a listener to be invoked when the positive button of the dialog is pressed. * * @param positiveText the text to display in the positive button. * @param callback the callback that will be called if the positive button is pressed. */ fun positiveButton(positiveText: Int, callback: DialogInterface.() -> Unit) { positiveButton(ctx.getString(positiveText), callback) } /** * Set a listener to be invoked when the positive button of the dialog is pressed. * * @param callback the callback that will be called if the positive button is pressed. */ fun okButton(callback: DialogInterface.() -> Unit) { positiveButton(ctx.getString(R.string.ok), callback) } /** * Set a listener to be invoked when the positive button of the dialog is pressed. * * @param callback the callback that will be called if the positive button is pressed. */ fun yesButton(callback: DialogInterface.() -> Unit) { positiveButton(ctx.getString(R.string.yes), callback) } /** * Set a listener to be invoked when the positive button of the dialog is pressed. * * @param positiveText the text to display in the positive button. * @param callback the callback that will be called if the positive button is pressed. */ fun positiveButton(positiveText: CharSequence, callback: DialogInterface.() -> Unit) { checkBuilder() builder!!.setPositiveButton(positiveText, { dialog, which -> dialog.callback() }) } /** * Set a listener to be invoked when the negative button of the dialog is pressed. * * @param negativeText the text to display in the negative button. * @param callback the callback that will be called if the negative button is pressed. */ fun negativeButton(negativeText: Int, callback: DialogInterface.() -> Unit = { dismiss() }) { negativeButton(ctx.getString(negativeText), callback) } /** * Set a listener to be invoked when the negative button of the dialog is pressed. * * @param callback the callback that will be called if the negative button is pressed. */ fun cancelButton(callback: DialogInterface.() -> Unit = { dismiss() }) { negativeButton(ctx.getString(R.string.cancel), callback) } /** * Set a listener to be invoked when the negative button of the dialog is pressed. * * @param callback the callback that will be called if the negative button is pressed. */ fun noButton(callback: DialogInterface.() -> Unit = { dismiss() }) { negativeButton(ctx.getString(R.string.no), callback) } /** * Set a listener to be invoked when the negative button of the dialog is pressed. * * @param negativeText the text to display in the negative button. * @param callback the callback that will be called if the negative button is pressed. */ fun negativeButton(negativeText: CharSequence, callback: DialogInterface.() -> Unit = { dismiss() }) { checkBuilder() builder!!.setNegativeButton(negativeText, { dialog, which -> dialog.callback() }) } fun items(itemsId: Int, callback: (which: Int) -> Unit) { items(ctx.resources!!.getTextArray(itemsId), callback) } fun items(items: List<CharSequence>, callback: (which: Int) -> Unit) { items(items.toTypedArray(), callback) } fun items(items: Array<CharSequence>, callback: (which: Int) -> Unit) { checkBuilder() builder!!.setItems(items, { dialog, which -> callback(which) }) } fun adapter(adapter: ListAdapter, callback: (which: Int) -> Unit) { checkBuilder() builder!!.setAdapter(adapter, { dialog, which -> callback(which) }) } fun adapter(cursor: Cursor, labelColumn: String, callback: (which: Int) -> Unit) { checkBuilder() builder!!.setCursor(cursor, { dialog, which -> callback(which) }, labelColumn) } }
apache-2.0
19283f13529bd3481c9d8e939556f38e
30.736486
109
0.636044
4.512008
false
false
false
false
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/quests/camera_type/AddCameraType.kt
1
1101
package de.westnordost.streetcomplete.quests.camera_type import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder import de.westnordost.streetcomplete.data.osm.osmquests.OsmFilterQuestType import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.CITIZEN class AddCameraType : OsmFilterQuestType<CameraType>() { override val elementFilter = """ nodes with surveillance:type = camera and surveillance ~ public|outdoor|traffic and !camera:type """ override val commitMessage = "Add camera type" override val wikiLink = "Tag:surveillance:type" override val icon = R.drawable.ic_quest_surveillance_camera override val questTypeAchievements = listOf(CITIZEN) override fun getTitle(tags: Map<String, String>) = R.string.quest_camera_type_title override fun createForm() = AddCameraTypeForm() override fun applyAnswerTo(answer: CameraType, changes: StringMapChangesBuilder) { changes.add("camera:type", answer.osmValue) } }
gpl-3.0
7532a29abc9efcbab190405af4e7f3c1
35.7
88
0.757493
4.47561
false
false
false
false
shkschneider/android_Skeleton
core/src/main/kotlin/me/shkschneider/skeleton/ui/widget/AutoImageViewHeight.kt
1
947
package me.shkschneider.skeleton.ui.widget import android.content.Context import android.util.AttributeSet import android.view.View import androidx.appcompat.widget.AppCompatImageView // <http://stackoverflow.com/a/12283909> class AutoImageViewHeight : AppCompatImageView { var ratio = 1.1.toFloat() constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : super(context, attrs, defStyleAttr) override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { drawable?.let { drawable -> val height = View.MeasureSpec.getSize(heightMeasureSpec) val width = Math.ceil((height.toFloat() * drawable.intrinsicHeight.toFloat() / drawable.intrinsicWidth.toFloat()).toDouble()).toInt() setMeasuredDimension((ratio * width).toInt(), (ratio * height).toInt()) } ?: run { super.onMeasure(widthMeasureSpec, heightMeasureSpec) } } }
apache-2.0
1d6b37c7b765ba548b8a6ec36976174a
36.88
145
0.705385
4.642157
false
false
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/extensions/FloatingActionButton.kt
1
1020
package com.boardgamegeek.extensions import android.annotation.TargetApi import android.content.res.ColorStateList import android.graphics.Color import android.os.Build import com.google.android.material.floatingactionbutton.FloatingActionButton fun FloatingActionButton.colorize(color: Int): Boolean { val colorStateList = ColorStateList.valueOf(color) if (color != Color.TRANSPARENT && backgroundTintList != colorStateList) { backgroundTintList = colorStateList colorImageTint(color) return true } return false } @TargetApi(Build.VERSION_CODES.LOLLIPOP) private fun FloatingActionButton.colorImageTint(backgroundColor: Int) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { imageTintList = ColorStateList.valueOf( if (backgroundColor.isColorDark()) { Color.WHITE } else { Color.BLACK } ) } } fun FloatingActionButton.ensureShown() { postDelayed({ show() }, 2000) }
gpl-3.0
8e60a37019be43c1063edd139ff8adcd
29
77
0.7
4.811321
false
false
false
false
Nearsoft/nearbooks-android
app/src/main/java/com/nearsoft/nearbooks/util/ViewUtil.kt
2
9449
package com.nearsoft.nearbooks.util import android.annotation.SuppressLint import android.app.Activity import android.content.Context import android.databinding.ViewDataBinding import android.graphics.Bitmap import android.graphics.PorterDuff import android.graphics.PorterDuffColorFilter import android.os.Build import android.support.design.widget.Snackbar import android.support.v4.content.ContextCompat import android.support.v7.graphics.Palette import android.support.v7.view.menu.ActionMenuItemView import android.support.v7.widget.ActionMenuView import android.view.View import android.view.ViewGroup import android.view.ViewTreeObserver import android.widget.ImageButton import android.widget.ImageView import android.widget.Toast import com.nearsoft.nearbooks.R import com.nearsoft.nearbooks.view.helpers.ColorsWrapper import com.squareup.picasso.Callback import com.squareup.picasso.Picasso import rx.Observable import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers import java.io.IOException import java.util.* /** * Utilities related with views. * Created by epool on 1/8/16. */ object ViewUtil { fun loadBitmapFromUrlImage(context: Context, url: String): Observable<Bitmap> { return Observable.create { subscriber -> try { val bitmap = Picasso.with(context).load(url).get() subscriber.onNext(bitmap) subscriber.onCompleted() } catch (e: IOException) { e.printStackTrace() subscriber.onError(e) } } } fun getPaletteFromUrlImage(context: Context, url: String): Observable<Palette> { return loadBitmapFromUrlImage(context, url).map { Palette.from(it).generate() } } fun getColorsWrapperFromUrlImage(context: Context, url: String): Observable<ColorsWrapper> { return getPaletteFromUrlImage(context, url).map { val defaultColor = ContextCompat.getColor(context, R.color.colorPrimary) ViewUtil.getVibrantPriorityColorSwatchPair(it, defaultColor) } } fun loadImageFromUrl(imageView: ImageView, url: String): Observable<ColorsWrapper> { val context = imageView.context return Observable.create { subscriber -> val requestCreator = Picasso.with(context).load(url) requestCreator.placeholder(R.drawable.ic_launcher) requestCreator.error(R.drawable.ic_launcher) requestCreator.into(imageView, object : Callback { override fun onSuccess() { if (subscriber.isUnsubscribed) return ViewUtil.getColorsWrapperFromUrlImage(context, url).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe { colorsWrapper -> subscriber.onNext(colorsWrapper) subscriber.onCompleted() } } override fun onError() { subscriber.onCompleted() } }) } } fun getVibrantPriorityColorSwatchPair( palette: Palette?, defaultColor: Int): ColorsWrapper? { if (palette == null) return null if (palette.vibrantSwatch != null) { return ColorsWrapper(palette.getVibrantColor(defaultColor), palette.vibrantSwatch!!) } else if (palette.lightVibrantSwatch != null) { return ColorsWrapper(palette.getLightVibrantColor(defaultColor), palette.lightVibrantSwatch!!) } else if (palette.darkVibrantSwatch != null) { return ColorsWrapper(palette.getDarkVibrantColor(defaultColor), palette.darkVibrantSwatch!!) } else if (palette.mutedSwatch != null) { return ColorsWrapper(palette.getMutedColor(defaultColor), palette.mutedSwatch!!) } else if (palette.lightMutedSwatch != null) { return ColorsWrapper(palette.getLightMutedColor(defaultColor), palette.lightMutedSwatch!!) } else if (palette.darkMutedSwatch != null) { return ColorsWrapper(palette.getDarkMutedColor(defaultColor), palette.darkMutedSwatch!!) } return null } fun showSnackbarMessage(viewDataBinding: ViewDataBinding, message: String): Snackbar { val snackbar = Snackbar.make(viewDataBinding.root, message, Snackbar.LENGTH_LONG) snackbar.show() return snackbar } fun showToastMessage(context: Context, message: String): Toast { val toast = Toast.makeText(context, message, Toast.LENGTH_LONG) toast.show() return toast } fun showToastMessage(context: Context, messageRes: Int, vararg formatArgs: Any): Toast { val toast = Toast.makeText(context, context.getString(messageRes, *formatArgs), Toast.LENGTH_LONG) toast.show() return toast } object Toolbar { /** * Use this method to colorize toolbar icons to the desired target color * @param toolbarView toolbar view being colored * * * @param toolbarIconsColor the target color of toolbar icons * * * @param activity reference to activity needed to register observers */ fun colorizeToolbar(toolbarView: android.support.v7.widget.Toolbar, toolbarIconsColor: Int, activity: Activity) { val colorFilter = PorterDuffColorFilter(toolbarIconsColor, PorterDuff.Mode.MULTIPLY) for (i in 0..toolbarView.childCount - 1) { val v = toolbarView.getChildAt(i) //Step 1 : Changing the color of back button (or open drawer button). if (v is ImageButton) { //Action Bar back button v.drawable.colorFilter = colorFilter } if (v is ActionMenuView) { for (j in 0..v.childCount - 1) { //Step 2: Changing the color of any ActionMenuViews - icons that //are not back button, nor text, nor overflow menu icon. val innerView = v.getChildAt(j) if (innerView is ActionMenuItemView) { val drawablesCount = innerView.compoundDrawables.size for (k in 0..drawablesCount - 1) { if (innerView.compoundDrawables[k] != null) { val finalK = k //Important to set the color filter in seperate thread, //by adding it to the message queue //Won't work otherwise. innerView.post { innerView.compoundDrawables[finalK].colorFilter = colorFilter } } } } } } //Step 3: Changing the color of title and subtitle. toolbarView.setTitleTextColor(toolbarIconsColor) toolbarView.setSubtitleTextColor(toolbarIconsColor) //Step 4: Changing the color of the Overflow Menu icon. setOverflowButtonColor(activity, colorFilter) } } /** * It's important to set overflowDescription attribute in styles, so we can grab the * reference to the overflow icon. Check: res/values/styles.xml * @param activity Activity where is called. * * * @param colorFilter Color to be set. */ private fun setOverflowButtonColor(activity: Activity, colorFilter: PorterDuffColorFilter) { @SuppressLint("PrivateResource") val overflowDescription = activity.getString(R.string.abc_action_menu_overflow_description) val decorView = activity.window.decorView as ViewGroup val viewTreeObserver = decorView.viewTreeObserver viewTreeObserver.addOnGlobalLayoutListener( object : ViewTreeObserver.OnGlobalLayoutListener { override fun onGlobalLayout() { val outViews = ArrayList<View>() decorView.findViewsWithText(outViews, overflowDescription, View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION) if (outViews.isEmpty()) return val overflow = outViews[0] as ImageView overflow.colorFilter = colorFilter removeOnGlobalLayoutListener(decorView, this) } }) } @SuppressWarnings("deprecation") private fun removeOnGlobalLayoutListener(v: View, listener: ViewTreeObserver.OnGlobalLayoutListener) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { v.viewTreeObserver.removeGlobalOnLayoutListener(listener) } else { v.viewTreeObserver.removeOnGlobalLayoutListener(listener) } } } }
mit
1d3fcaab486df2417eb393b9bfd97259
40.995556
171
0.596359
5.418005
false
false
false
false
Kotlin/kotlinx.serialization
formats/json/jvmMain/src/kotlinx/serialization/json/internal/JvmJsonStreams.kt
1
9388
package kotlinx.serialization.json.internal import java.io.InputStream import java.io.OutputStream import java.nio.charset.Charset internal class JsonToJavaStreamWriter(private val stream: OutputStream) : JsonWriter { private val buffer = ByteArrayPool.take() private var charArray = CharArrayPool.take() private var indexInBuffer: Int = 0 override fun writeLong(value: Long) { write(value.toString()) } override fun writeChar(char: Char) { writeUtf8CodePoint(char.code) } override fun write(text: String) { val length = text.length ensureTotalCapacity(0, length) text.toCharArray(charArray, 0, 0, length) writeUtf8(charArray, length) } override fun writeQuoted(text: String) { ensureTotalCapacity(0, text.length + 2) val arr = charArray arr[0] = '"' val length = text.length text.toCharArray(arr, 1, 0, length) for (i in 1 until 1 + length) { val ch = arr[i].code // Do we have unescaped symbols? if (ch < ESCAPE_MARKERS.size && ESCAPE_MARKERS[ch] != 0.toByte()) { // Go to slow path return appendStringSlowPath(i, text) } } // Update the state // Capacity is not ensured because we didn't hit the slow path and thus guessed it properly in the beginning arr[length + 1] = '"' writeUtf8(arr, length + 2) flush() } private fun appendStringSlowPath(currentSize: Int, string: String) { var sz = currentSize for (i in currentSize - 1 until string.length) { /* * We ar already on slow path and haven't guessed the capacity properly. * Reserve +2 for backslash-escaped symbols on each iteration */ sz = ensureTotalCapacity(sz, 2) val ch = string[i].code // Do we have unescaped symbols? if (ch < ESCAPE_MARKERS.size) { /* * Escape markers are populated for backslash-escaped symbols. * E.g. ESCAPE_MARKERS['\b'] == 'b'.toByte() * Everything else is populated with either zeros (no escapes) * or ones (unicode escape) */ when (val marker = ESCAPE_MARKERS[ch]) { 0.toByte() -> { charArray[sz++] = ch.toChar() } 1.toByte() -> { val escapedString = ESCAPE_STRINGS[ch]!! sz = ensureTotalCapacity(sz, escapedString.length) escapedString.toCharArray(charArray, sz, 0, escapedString.length) sz += escapedString.length } else -> { charArray[sz] = '\\' charArray[sz + 1] = marker.toInt().toChar() sz += 2 } } } else { charArray[sz++] = ch.toChar() } } ensureTotalCapacity(sz, 1) charArray[sz++] = '"' writeUtf8(charArray, sz) flush() } private fun ensureTotalCapacity(oldSize: Int, additional: Int): Int { val newSize = oldSize + additional if (charArray.size <= newSize) { charArray = charArray.copyOf(newSize.coerceAtLeast(oldSize * 2)) } return oldSize } override fun release() { flush() CharArrayPool.release(charArray) ByteArrayPool.release(buffer) } private fun flush() { stream.write(buffer, 0, indexInBuffer) indexInBuffer = 0 } @Suppress("NOTHING_TO_INLINE") // ! you should never ask for more than the buffer size private inline fun ensure(bytesCount: Int) { if (rest() < bytesCount) { flush() } } @Suppress("NOTHING_TO_INLINE") // ! you should never ask for more than the buffer size private inline fun write(byte: Int) { buffer[indexInBuffer++] = byte.toByte() } @Suppress("NOTHING_TO_INLINE") private inline fun rest(): Int { return buffer.size - indexInBuffer } /* Sources taken from okio library with minor changes, see https://github.com/square/okio */ private fun writeUtf8(string: CharArray, count: Int) { require(count >= 0) { "count < 0" } require(count <= string.size) { "count > string.length: $count > ${string.size}" } // Transcode a UTF-16 Java String to UTF-8 bytes. var i = 0 while (i < count) { var c = string[i].code when { c < 0x80 -> { // Emit a 7-bit character with 1 byte. ensure(1) write(c) // 0xxxxxxx i++ val runLimit = minOf(count, i + rest()) // Fast-path contiguous runs of ASCII characters. This is ugly, but yields a ~4x performance // improvement over independent calls to writeByte(). while (i < runLimit) { c = string[i].code if (c >= 0x80) break write(c) // 0xxxxxxx i++ } } c < 0x800 -> { // Emit a 11-bit character with 2 bytes. ensure(2) write(c shr 6 or 0xc0) // 110xxxxx write(c and 0x3f or 0x80) // 10xxxxxx i++ } c < 0xd800 || c > 0xdfff -> { // Emit a 16-bit character with 3 bytes. ensure(3) write(c shr 12 or 0xe0) // 1110xxxx write(c shr 6 and 0x3f or 0x80) // 10xxxxxx write(c and 0x3f or 0x80) // 10xxxxxx i++ } else -> { // c is a surrogate. Make sure it is a high surrogate & that its successor is a low // surrogate. If not, the UTF-16 is invalid, in which case we emit a replacement // character. val low = (if (i + 1 < count) string[i + 1].code else 0) if (c > 0xdbff || low !in 0xdc00..0xdfff) { ensure(1) write('?'.code) i++ } else { // UTF-16 high surrogate: 110110xxxxxxxxxx (10 bits) // UTF-16 low surrogate: 110111yyyyyyyyyy (10 bits) // Unicode code point: 00010000000000000000 + xxxxxxxxxxyyyyyyyyyy (21 bits) val codePoint = 0x010000 + (c and 0x03ff shl 10 or (low and 0x03ff)) // Emit a 21-bit character with 4 bytes. ensure(4) write(codePoint shr 18 or 0xf0) // 11110xxx write(codePoint shr 12 and 0x3f or 0x80) // 10xxxxxx write(codePoint shr 6 and 0x3f or 0x80) // 10xxyyyy write(codePoint and 0x3f or 0x80) // 10yyyyyy i += 2 } } } } } /* Sources taken from okio library with minor changes, see https://github.com/square/okio */ private fun writeUtf8CodePoint(codePoint: Int) { when { codePoint < 0x80 -> { // Emit a 7-bit code point with 1 byte. ensure(1) write(codePoint) } codePoint < 0x800 -> { // Emit a 11-bit code point with 2 bytes. ensure(2) write(codePoint shr 6 or 0xc0) // 110xxxxx write(codePoint and 0x3f or 0x80) // 10xxxxxx } codePoint in 0xd800..0xdfff -> { // Emit a replacement character for a partial surrogate. ensure(1) write('?'.code) } codePoint < 0x10000 -> { // Emit a 16-bit code point with 3 bytes. ensure(3) write(codePoint shr 12 or 0xe0) // 1110xxxx write(codePoint shr 6 and 0x3f or 0x80) // 10xxxxxx write(codePoint and 0x3f or 0x80) // 10xxxxxx } codePoint <= 0x10ffff -> { // Emit a 21-bit code point with 4 bytes. ensure(4) write(codePoint shr 18 or 0xf0) // 11110xxx write(codePoint shr 12 and 0x3f or 0x80) // 10xxxxxx write(codePoint shr 6 and 0x3f or 0x80) // 10xxyyyy write(codePoint and 0x3f or 0x80) // 10yyyyyy } else -> { throw JsonEncodingException("Unexpected code point: $codePoint") } } } } internal class JavaStreamSerialReader( stream: InputStream, charset: Charset = Charsets.UTF_8 ) : SerialReader { private val reader = stream.reader(charset) override fun read(buffer: CharArray, bufferOffset: Int, count: Int): Int { return reader.read(buffer, bufferOffset, count) } }
apache-2.0
c6600be4816c4b1168724382bb2c8a58
35.247104
116
0.494781
4.588465
false
false
false
false
davidwhitman/changelogs
app/src/main/java/com/thunderclouddev/changelogs/ui/comparator/SizeComparator.kt
1
956
/* * Copyright (c) 2017. * Distributed under the GNU GPLv3 by David Whitman. * https://www.gnu.org/licenses/gpl-3.0.en.html * * This source code is made available to help others learn. Please don't clone my app. */ package com.thunderclouddev.changelogs.ui.comparator import java.util.* /** * @author Thundercloud Dev on 6/9/2016. */ //class SizeComparator : Comparator<AppInfo> { // companion object { // // Performance, yo // private val recentlyUpdatedComparator = RecentlyUpdatedComparator() // } // // override fun compare(lhs: AppInfo?, rhs: AppInfo?): Int { // val leftMC = MostCorrectAppInfo(lhs!!) // val rightMC = MostCorrectAppInfo(rhs!!) // val updateResult = rightMC.installSize.compareTo(leftMC.installSize) // // if (updateResult != 0) { // return updateResult // } else { // return recentlyUpdatedComparator.compare(lhs, rhs) // } // } //}
gpl-3.0
94e73a89d1757b59e19b8599de4fae9e
28
86
0.638075
3.676923
false
false
false
false
minjaesong/terran-basic-java-vm
src/net/torvald/terranvm/runtime/compiler/cflat/NewCompiler.kt
1
22890
package net.torvald.terranvm.runtime.compiler.cflat import net.torvald.terranvm.runtime.* import net.torvald.terranvm.runtime.compiler.cflat.Cflat.ExpressionType.* import net.torvald.terrarum.virtualcomputer.terranvmadapter.printASM import java.lang.StringBuilder import kotlin.UnsupportedOperationException import kotlin.collections.HashMap /** * Compilation step: * * User Input -> Tree Representation -> IR1 (preorder?) -> IR2 (postorder) -> ASM => Fed into Assembler * * Reference: * - *Compiler Design: Virtual Machines*, Reinhard Wilhelm and Helmut Seidi, 2011, ISBN 3642149081 */ object NewCompiler { val testProgram = """ int c; int d; int shit; int plac; int e_ho; int lder; int r; //c = (3 + 4) * (7 - 2); c = -3; if (c > 42) { c = 0; } else { c = 1; } void newfunction(int k) { dosomething(k, -k); } //d = "Hello, world!"; float dd; """.trimIndent() // TODO add issues here // lexer and parser goes here // /* /** * An example of (3 + 4) * (7 - 2). * * This is also precisely what **IR1** is supposed to be. * Invoke this "Function" and you will get a string, which is **IR2**. * IR2 is */ val TEST_CODE: () -> CodeR = { { MUL(0, { ADD(0, { LIT(0, 3) }, { LIT(0, 4) }) }, { SUB(0, { LIT(0, 7) }, { LIT(0, 2) }) }) } } /** * If (3) 7200 Else 5415; 3 + 4; 7 * 2 */ val TEST_CODE2 = { { IFELSE(1, { LIT(1, 3) }, // cond { LIT(2, 7200) }, // true { LIT(4, 5415) } // false ) } bind { // AM I >>=ing right ? ADD(6, { LIT(6, 3) }, { LIT(6, 4) }) } bind { MUL(7, { LIT(7, 7) }, { LIT(7, 2) }) } } /** * var a = (b + (b * c)); // a |> 5; b |> 6; c |> 7 * * Expected output: loadc 6; load; loadc 6; load; ... -- as per our reference book */ val TEST_VARS = { // function for variable address val aTable = hashMapOf("a" to 5, "b" to 6, "c" to 7) val aenv: Rho = { name -> aTable[name]!! } // the actual code { ASSIGN(1, { VAR_L(1, "a", aenv) }, { ADD(1, { VAR_R(1, "b", aenv) }, { MUL(1, { VAR_R(1, "b", aenv) }, { VAR_R(1, "c", aenv) }) }) }, aenv ) } }*/ /** Shitty >>= (toilet plunger) */ private infix fun (CodeR).bind(other: CodeR) = sequenceOf(this, other) private infix fun (Sequence<CodeR>).bind(other: CodeR) = this + other // TREE TO IR1 fun toIR1(tree: Cflat.SyntaxTreeNode): Pair<CodeR, Rho> { //val parentCode: Sequence<CodeR> = sequenceOf( { "" } ) val variableAddr = HashMap<String, Int>() var varCnt = 0 fun String.toVarName() = "$$this" val aenv: Rho = { name -> if (!variableAddr.containsKey(name.toVarName())) throw UnresolvedReference("No such variable defined: $name") //println("Fetch var ${name.toVarName()} -> ${variableAddr[name.toVarName()]}") variableAddr[name.toVarName()]!! } fun addvar(name: String, ln: Int) { if (!variableAddr.containsKey(name.toVarName())) { variableAddr[name.toVarName()] = varCnt + 256 // index starts at 100h varCnt++ } //println("Add var ${name.toVarName()} -> ${variableAddr[name.toVarName()]}") } // TODO recursion is a key // SyntaxTreeNode has its own traverse function, but our traverse is nothing trivial // so let's just leave it this way. // Traverse order: Self -> Arguments (e1, e2, ...) -> Statements (s) fun traverse1(node: Cflat.SyntaxTreeNode) : CodeR { val l = node.lineNumber // termination conditions // if (node.expressionType == LITERAL_LEAF) { return when (node.returnType!!) { Cflat.ReturnType.INT -> { CodeR { LIT(l, node.literalValue as Int) }} Cflat.ReturnType.FLOAT -> { CodeR { LIT(l, node.literalValue as Float) }} Cflat.ReturnType.DATABASE -> { CodeR { LIT(l, node.literalValue as String) }} else -> { CodeR { _REM(l, "Unsupported literal with type: ${node.returnType}") }} } } else if (node.expressionType == VARIABLE_READ) { addvar(node.name!!, l) return CodeR { VAR_R(l, node.name!!, aenv) } } else if (node.expressionType == VARIABLE_WRITE) { if (!variableAddr.containsKey(node.name!!)) { throw UnresolvedReference("No such variable defined: ${node.name!!}") } return CodeR { VAR_L(l, node.name!!, aenv) } } // recursion conditions // else { return if (node.expressionType == FUNCTION_CALL) { when (node.name) { "+" -> { CodeR { ADD(l, traverse1(node.arguments[0]), traverse1(node.arguments[1])) }} "-" -> { CodeR { SUB(l, traverse1(node.arguments[0]), traverse1(node.arguments[1])) }} "*" -> { CodeR { MUL(l, traverse1(node.arguments[0]), traverse1(node.arguments[1])) }} "/" -> { CodeR { DIV(l, traverse1(node.arguments[0]), traverse1(node.arguments[1])) }} "=" -> { CodeR { ASSIGN(l, CodeL { VAR_L(l, node.arguments[0].name!!, aenv) }, traverse1(node.arguments[1]), aenv) }} "==" -> { CodeR { EQU(l, traverse1(node.arguments[0]), traverse1(node.arguments[1])) }} "!=" -> { CodeR { NEQ(l, traverse1(node.arguments[0]), traverse1(node.arguments[1])) }} ">=" -> { CodeR { GEQ(l, traverse1(node.arguments[0]), traverse1(node.arguments[1])) }} "<=" -> { CodeR { LEQ(l, traverse1(node.arguments[0]), traverse1(node.arguments[1])) }} ">" -> { CodeR { GT(l, traverse1(node.arguments[0]), traverse1(node.arguments[1])) }} "<" -> { CodeR { LS(l, traverse1(node.arguments[0]), traverse1(node.arguments[1])) }} "if" -> { CodeR { IF(l, traverse1(node.arguments[0]), traverse1(node.statements[0])) }} "ifelse" -> { CodeR { IFELSE(l, traverse1(node.arguments[0]), traverse1(node.statements[0]), traverse1(node.statements[1])) }} "#_unaryminus" -> { CodeR { NEG(l, traverse1(node.arguments[0])) } } // calling arbitrary function else -> { // see p.42 ? val finalCmd = StringBuilder() finalCmd.append(ALLOCATSTACK(node.arguments.size)) // push CodeR args passing into the stack, reversed order node.arguments.reversed().map { traverse1(it) }.forEach { finalCmd.append(PUSH(it)) } finalCmd.append(MARKFUNCCALL()) finalCmd.append(CALLFUNC(node.arguments.size)) // TODO slide CodeR { finalCmd.toString() } // we're doing this because I couldn't build func composition } } } else if (node.expressionType == INTERNAL_FUNCTION_CALL) { when (node.name) { "#_declarevar" -> { addvar(node.arguments[0].literalValue as String, l) return CodeR { NEWVAR(l, node.arguments[1].literalValue as String, node.arguments[0].literalValue as String) } } else -> { return CodeR { _REM(l, "Unknown internal function: ${node.name}") }} } } else if (node.name == Cflat.rootNodeName) { return CodeR { _PARSE_HEAD(node.statements.map { traverse1(it) }) } } /*else if (node.expressionType == FUNCTION_DEF) { }*/ else { throw UnsupportedOperationException("Unsupported node:\n[NODE START]\n$node\n[NODE END]") } } } return traverse1(tree) to aenv } // These are the definition of IR1. Invoke this "function" and string will come out, which is IR2. // l: Int means Line Number // EXPRESSIONS // Think these as: // Proper impl of the func "CodeR" requires "Operation" and "E"s; it'd be easier if we're on Haskell, but to // make proper impl in the Kotlin, the code gets too long. // Think of these as "spilled" version of the proper one. // Function "CodeR" returns IR2, and so does these spilled versions. private fun _REM(l: Int, message: String): IR2 = "\nREM Ln$l : ${message.replace('\n', '$')};\n" private fun _PARSE_HEAD(e: List<CodeR>): IR2 = e.fold("") { acc, it -> acc + it.invoke() } + "HALT;\n" /** e1 ; e2 ; add ; */ fun ADD(l: Int, e1: CodeR, e2: CodeR): IR2 = e1() + e2() + "ADD;\n" fun SUB(l: Int, e1: CodeR, e2: CodeR) = e1() + e2() + "SUB;\n" fun MUL(l: Int, e1: CodeR, e2: CodeR) = e1() + e2() + "MUL;\n" fun DIV(l: Int, e1: CodeR, e2: CodeR) = e1() + e2() + "DIV;\n" fun NEG(l: Int, e: CodeR) = e() + "NEG;\n" /** loadconst ; literal ; */ fun LIT(l: Int, e: Int) = "LOADCONST ${e.toHexString()};-_-_-_ Literal\n" // always ends with 'h' fun LIT(l: Int, e: Float) = "LOADCONST ${e}f;-_-_-_ Literal\n" // always ends with 'f' fun LIT(l: Int, e: String) = LIT(l, e.toByteArray(Charsets.UTF_8)) fun LIT(l: Int, e: ByteArray) = "LOADDATA ${e.fold("") { acc, byte -> acc + "${byte.to2Hex()} " }};" /** address(int) ; value(word) ; store ; */ fun ASSIGN(l: Int, e1: CodeL, e2: CodeR, aenv: Rho) = e2() + e1(aenv) + "STORE;\n" /** ( address -- value stored in that address ) */ // this is Forth stack notation fun VAR_R(l: Int, varname: String, aenv: Rho) = "LOADCONST ${aenv(varname).toHexString()}; LOAD;-_-_-_ Read from variable\n" // NOT using 8hexstring is deliberate /** ( address -- ); memory gets changed */ fun VAR_L(l: Int, varname: String, aenv: Rho) = "LOADCONST ${aenv(varname).toHexString()};-_-_-_ Write to variable, if following command is STORE\n" // NOT using 8hexstring is deliberate; no need for extra store; handled by ASSIGN fun NEWVAR(l: Int, type: String, varname: String) = "NEWVAR ${type.toUpperCase()} $varname;\n" fun JUMP(l: Int, newPC: CodeR) = "JUMP $newPC;\n" // FOR NON-COMPARISON OPS fun JUMPZ(l: Int, newPC: CodeR) = "JUMPZ $newPC;\n" fun JUMPNZ(l: Int, newPC: CodeR) = "JUMPNZ $newPC;\n" // FOR COMPARISON OPS ONLY !! fun JUMPFALSE(l: Int, newPC: CodeR) = "JUMPFALSE $newPC;\n" // zero means false fun IF(l: Int, cond: CodeR, invokeTrue: CodeR) = cond() + "JUMPFALSE ${labelFalse(l, cond)};\n" + invokeTrue() + "LABEL ${labelFalse(l, cond)};\n" fun IFELSE(l: Int, cond: CodeR, invokeTrue: CodeR, invokeFalse: CodeR) = cond() + "JUMPFALSE ${labelFalse(l, cond)};\n" + invokeTrue() + "JUMP ${labelThen(l, cond)};\n" + "LABEL ${labelFalse(l, cond)};\n" + invokeFalse() + "LABEL ${labelThen(l, cond)};\n" fun WHILE(l: Int, cond: CodeR, invokeWhile: CodeR) = "LABEL ${labelWhile(l, cond)};\n" + cond() + "JUMPFALSE ${labelThen(l, cond)};\n" + invokeWhile() + "JUMP ${labelWhile(l, cond)};\n" + "LABEL ${labelThen(l, cond)};\n" fun EQU(l: Int, e1: CodeR, e2: CodeR) = e1() + e2() + "ISEQUAL;\n" fun NEQ(l: Int, e1: CodeR, e2: CodeR) = e1() + e2() + "ISNOTEQUAL;\n" fun LEQ(l: Int, e1: CodeR, e2: CodeR) = e1() + e2() + "ISLESSEQUAL;\n" fun GEQ(l: Int, e1: CodeR, e2: CodeR) = e1() + e2() + "ISGREATEQUAL;\n" fun GT(l: Int, e1: CodeR, e2: CodeR) = e1() + e2() + "ISGREATER;\n" fun LS(l: Int, e1: CodeR, e2: CodeR) = e1() + e2() + "ISLESSER;\n" // TODO NEWFUNC -- how do I deal with the function arguments? //fun FOR // TODO for ( e1 ; e2 ; e3 ) s' === e1 ; while ( e2 ) { s' ; e3 ; } fun NOP() = "" fun PUSH() = "PUSH;-_-_-_ Inline ASM\n" fun PUSHEP() = "PUSHEP;\n" fun PUSHFP() = "PUSHFP;\n" fun PUSH(e: CodeR) = e() + "PUSH;\n" fun MARKFUNCCALL() = PUSHEP() + PUSHFP() fun CALLFUNC(m: Int) = "CALLFUNC $m;\n" fun ALLOCATSTACK(m: Int) = "ALLOCATSTACK $m;\n" // STATEMENTS // also "spilled" version of function "Code" // SEXP stands for Statements-to-EXPression; my wild guess from my compiler prof's sense of naming, who is sexually // attracted to the language Haskell /** @params codeR an any function that takes nothing and returns IR2 (like LIT, ADD, VAR_R, JUMP) */ fun SEXP(l: Int, codeR: CodeR, rho: Rho): IR2 = codeR() + "POP;\n" /** @params codeR an any function that takes Rho and returns IR2 (like ASSIGN, VAR_L) */ fun SEXP(l: Int, codeL: CodeL, rho: Rho): IR2 = codeL(rho) + "POP;\n" fun SSEQ(l: Int, s: List<CodeR>, rho: Rho): IR2 = if (s.isEmpty()) "" else s.first().invoke() + SSEQ(l, s.drop(1), rho) private fun labelUnit(lineNum: Int, code: CodeR): IR2 { return "\$LN${lineNum}_${code.hashCode().toHexString().dropLast(1)}" // hopefully there'll be no hash collision... } private fun labelFalse(lineNum: Int, code: CodeR) = labelUnit(lineNum, code) + "_FALSE" private fun labelThen(lineNum: Int, code: CodeR) = labelUnit(lineNum, code) + "_THEN" private fun labelWhile(lineNum: Int, code: CodeR) = "\$WHILE_" + labelUnit(lineNum, code).drop(1) // IR2 to ASM private const val IR1_COMMENT_MARKER = "-_-_-_" private const val EP = "r14" private const val FP = "r15" private const val PC = "r0" private const val SP = "r1" // special register /** - IR2 conditional: ``` IS-Comp JUMPFALSE Lfalse λ. code s_true rho JUMP Lthen LABEL Lfalse λ. code s_false rho LABEL Lthen ... ``` - ASM conditional: ``` λ. <comparison> rho CMP; JZ/JNZ/... Lfalse (do.) ``` IR2's JUMPFALSE needs to be converted equivalent ASM according to the IS-Comp, for example, ISEQUAL; JUMPZ false === CMP; JNZ false. If you do the calculation, ALL THE RETURNING LABEL TAKE FALSE-LABELS. (easy coding wohoo!) */ private fun IR2toFalseJumps(compFun: IR2): Array<String> { return when(compFun) { "ISEQUAL" -> arrayOf("JNZ") "ISNOTEQUAL" -> arrayOf("JZ") "ISGREATER" -> arrayOf("JLS", "JZ") "ISLESSER" -> arrayOf("JGT, JZ") "ISGREATEQUAL" -> arrayOf("JLS") "ISLESSEQUAL" -> arrayOf("JGT") else -> throw UnsupportedOperationException("Unacceptable comparison operator: $compFun") } } fun toASM(ir2: IR2, addDebugComments: Boolean = true): String { val irList1 = ir2.replace(Regex("""$IR1_COMMENT_MARKER[^\n]*\n"""), "") // get rid of debug comment .replace(Regex("""; *"""), "\n") // get rid of traling spaces after semicolon .replace(Regex("""\n+"""), "\n") // get rid of empty lines .split('\n') // CAPTCHA Sarah Connor // put all the newvar into the top of the list fun filterNewvar(s: IR2) = s.startsWith("NEWVAR") val irList = listOf("SECT DATA") + irList1.filter { filterNewvar(it) } + listOf("SECT CODE") + irList1.filterNot { filterNewvar(it) } val asm = StringBuilder() var prevCompFun = "" println("[START irList]") println(irList.joinToString("\n")) // test return irList as one string println("[END irList]\n") for (c in 0..irList.lastIndex) { val it = irList[c] val tokens = it.split(Regex(" +")) val head = tokens[0] val arg1 = tokens.getOrNull(1) val arg2 = tokens.getOrNull(2) val arg3 = tokens.getOrNull(3) if (it.isEmpty()) continue val stmt: List<String>? = when (head) { "HALT" -> { listOf("HALT;") } "LOADCONST" -> { // ( -- immediate ) val l = listOf( "LOADWORDIHI r1, ${arg1!!.dropLast(5)}h;", "LOADWORDILO r1, ${arg1.takeLast(5)};", "PUSH r1;" ) if (arg1.length >= 5) l else l.drop(1) } "LOAD" -> { // ( address -- value in the addr ) listOf("POP r1;", "LOADWORD r1, r1, r0;" ) } "STORE" -> { // ( value, address -- ) // TODO 'address' is virtual one listOf("POP r2;", "POP r1;", "STOREWORD r1, r2, r0;" ) } "LABEL" -> { listOf(":$arg1;") } "JUMP" -> { listOf("JMP @$arg1;") } "ISEQUAL", "ISNOTEQUAL", "ISGREATER", "ISLESSER", "ISGREATEQUAL", "ISLESSEQUAL" -> { prevCompFun = head // it's guaranteed compfunction is followed by JUMPFALSE (see IF/IFELSE/WHILE) listOf("POP r2;", "POP r1;", "CMP r1, r2;" ) } "JUMPFALSE" -> { IR2toFalseJumps(prevCompFun).map { "$it @$arg1;" } } "NEG" -> { listOf("POP r1;", "SUB r1, r0, r1;", "PUSH r1;" ) } "SECT" -> { listOf(".$arg1;") } "NEWVAR" -> { listOf("$arg1 $arg2;") } "PUSH" -> { listOf("PUSH r1;") } "PUSHEP" -> { listOf("PUSH $EP;") } "PUSHFP" -> { listOf("PUSH $FP;") } "CALLFUNC" -> { // instruction CALL (fig 2.27) listOf("SRR $FP, $SP;", // set FP "SRR r1, $PC;", // swap(p, q); put PC into r1 (= p) "POP r2;", // swap(p, q); pop into r2 (= q) "PUSH r1;", // swap(p, q); push p // instruction ENTER(m) part here (fig 2.28) "LOADWORDILO r1, ${arg1!!.toInt()}", // EP = SP + m "ADDINT $EP, r1, $FP", // EP = SP + m; FP still holds SP // the last of CALL (jump) "SRW r2, $PC;" // set PC as q (will do unconditional jump as PC is being overwritten) ) } "ALLOCATSTACK" -> { val list = mutableListOf<String>() repeat(arg1!!.toInt()) { list.add("PUSH r0;") } // we can just increment SP, but the stack will remain 0xFFFFFFFF which makes debugging trickier /*return*/ list.toList() } "JSR" -> { listOf("JSR;") } else -> { listOf("# Unknown IR2: $it") } } // keep this as is; it puts \n and original IR2 as formatted comments val tabLen = 50 if (addDebugComments) { stmt?.forEachIndexed { index, s -> if (index == 0) if (head == "JUMPFALSE") asm.append(s.tabulate(tabLen) + "# ($prevCompFun) -> $it\n") else asm.append(s.tabulate(tabLen) + "# $it\n") else if (index == stmt.lastIndex) asm.append(s.tabulate(tabLen) + "#\n") else asm.append(s.tabulate(tabLen) + "#\n") } } else { stmt?.forEach { asm.append("$it ") } // ASMs grouped as their semantic meaning won't get \n'd } stmt?.let { asm.append("\n") } } return asm.toString() } private fun Byte.to2Hex() = this.toUint().toString(16).toUpperCase().padStart(2, '0') + 'h' private fun String.tabulate(columnSize: Int = 56) = this + " ".repeat(maxOf(1, columnSize - this.length)) } // IR1 is the bunch of functions above typealias IR2 = String /** * Address Environment; a function to map a variable name to its memory address. * * The address is usually virtual. Can be converted to real address at either (IR2 -> ASM) or (ASM -> Machine) stage. */ typealias Rho = (String) -> Int //typealias CodeL = (Rho) -> IR2 //typealias CodeR = () -> IR2 inline class CodeL(val function: (Rho) -> IR2) { operator fun invoke(rho: Rho): IR2 { return function(rho) } } inline class CodeR(val function: () -> IR2) { operator fun invoke(): IR2 { return function() } } inline class Code(val function: (Rho) -> IR2) { operator fun invoke(rho: Rho): IR2 { return function(rho) } } // due to my laziness, CodeR is also a Stmt; after all, "e;" is a statement /*inline class Stmt(val function: (Rho?) -> IR2) { operator fun invoke(rho: Rho?): IR2 { return function(rho) } }*/ fun main(args: Array<String>) { val testProg = NewCompiler.testProgram val tree = Cflat.buildTree(Cflat.tokenise(testProg)) val vm = TerranVM(4096) val assembler = Assembler(vm) println(tree) //val code = NewCompiler.TEST_VARS val (ir1, aenv) = NewCompiler.toIR1(tree) val ir2 = ir1.invoke() //code.invoke().forEach { println(it.invoke()) } // this is probably not the best sequence comprehension println("## IR2: ##") println(ir2) val asm = NewCompiler.toASM(ir2) println("## ASM: ##") println(asm) val vmImage = assembler(asm) println("## OPCODE: ##") vmImage.bytes.printASM() }
mit
36d2e4e25279852a7e5553ddf80f0b7f
38.874564
234
0.49408
3.673676
false
false
false
false
Ruben-Sten/TeXiFy-IDEA
src/nl/hannahsten/texifyidea/highlighting/LatexAnnotator.kt
1
8244
package nl.hannahsten.texifyidea.highlighting import com.intellij.lang.annotation.AnnotationHolder import com.intellij.lang.annotation.Annotator import com.intellij.lang.annotation.HighlightSeverity import com.intellij.openapi.editor.colors.TextAttributesKey import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import nl.hannahsten.texifyidea.lang.Environment import nl.hannahsten.texifyidea.psi.* import nl.hannahsten.texifyidea.util.* import nl.hannahsten.texifyidea.util.labels.getLabelDefinitionCommands import nl.hannahsten.texifyidea.util.magic.CommandMagic /** * Provide syntax highlighting. * * @author Hannah Schellekens */ open class LatexAnnotator : Annotator { override fun annotate(psiElement: PsiElement, annotationHolder: AnnotationHolder) { // Math display if (psiElement is LatexInlineMath) { annotateInlineMath(psiElement, annotationHolder) } else if (psiElement is LatexDisplayMath || (psiElement is LatexEnvironment && psiElement.isContext(Environment.Context.MATH)) ) { annotateDisplayMath(psiElement, annotationHolder) // Begin/End commands if (psiElement is LatexEnvironment) { annotationHolder.newAnnotation(HighlightSeverity.INFORMATION, "") .range(TextRange.from(psiElement.beginCommand.textOffset, 6)) .textAttributes(LatexSyntaxHighlighter.COMMAND_MATH_DISPLAY) .create() annotationHolder.newAnnotation(HighlightSeverity.INFORMATION, "") .range(TextRange.from(psiElement.endCommand?.textOffset ?: psiElement.textOffset, 4)) .textAttributes(LatexSyntaxHighlighter.COMMAND_MATH_DISPLAY) .create() } } // Optional parameters else if (psiElement is LatexOptionalParam) { annotateOptionalParameters(psiElement, annotationHolder) } // Commands else if (psiElement is LatexCommands) { annotateCommands(psiElement, annotationHolder) } } /** * Annotates an inline math element and its children. * * All elements will be coloured accoding to [LatexSyntaxHighlighter.INLINE_MATH] and * all commands that are contained in the math environment get styled with * [LatexSyntaxHighlighter.COMMAND_MATH_INLINE]. */ private fun annotateInlineMath( inlineMathElement: LatexInlineMath, annotationHolder: AnnotationHolder ) { annotationHolder.newSilentAnnotation(HighlightSeverity.INFORMATION) .range(inlineMathElement) .textAttributes(LatexSyntaxHighlighter.INLINE_MATH) .create() annotateMathCommands( inlineMathElement.childrenOfType(LatexCommands::class), annotationHolder, LatexSyntaxHighlighter.COMMAND_MATH_INLINE ) } /** * Annotates a display math element and its children. * * All elements will be coloured accoding to [LatexSyntaxHighlighter.DISPLAY_MATH] and * all commands that are contained in the math environment get styled with * [LatexSyntaxHighlighter.COMMAND_MATH_DISPLAY]. */ private fun annotateDisplayMath( displayMathElement: PsiElement, annotationHolder: AnnotationHolder ) { annotationHolder.newSilentAnnotation(HighlightSeverity.INFORMATION) .range(displayMathElement) .textAttributes(LatexSyntaxHighlighter.DISPLAY_MATH) .create() annotateMathCommands( displayMathElement.childrenOfType(LatexCommands::class), annotationHolder, LatexSyntaxHighlighter.COMMAND_MATH_DISPLAY ) } /** * Annotates all command tokens of the commands that are included in the `elements`. * * @param elements * All elements to handle. Only elements that are [LatexCommands] are considered. * @param highlighter * The attributes to apply to all command tokens. */ private fun annotateMathCommands( elements: Collection<PsiElement>, annotationHolder: AnnotationHolder, highlighter: TextAttributesKey ) { for (element in elements) { if (element !is LatexCommands) { continue } val token = element.commandToken annotationHolder.newSilentAnnotation(HighlightSeverity.INFORMATION) .range(token) .textAttributes(highlighter) .create() if (element.name == "\\text" || element.name == "\\intertext") { annotationHolder.newSilentAnnotation(HighlightSeverity.INFORMATION) .range(element.requiredParameters().firstOrNull() ?: continue) .textAttributes(LatexSyntaxHighlighter.MATH_NESTED_TEXT) .create() } } } /** * Annotates the given optional parameters of commands. */ private fun annotateOptionalParameters( optionalParamElement: LatexOptionalParam, annotationHolder: AnnotationHolder ) { for ( element in optionalParamElement.optionalParamContentList ) { if (element !is LatexOptionalParamContent) { continue } val toStyle = element.parameterText ?: continue annotationHolder.newSilentAnnotation(HighlightSeverity.INFORMATION) .range(toStyle) .textAttributes(LatexSyntaxHighlighter.OPTIONAL_PARAM) .create() } } /** * Annotates the given required parameters of commands. */ private fun annotateCommands(command: LatexCommands, annotationHolder: AnnotationHolder) { annotateStyle(command, annotationHolder) // Label references. val style = when (command.name) { in CommandMagic.labelReferenceWithoutCustomCommands -> { LatexSyntaxHighlighter.LABEL_REFERENCE } // Label definitions. in getLabelDefinitionCommands() -> { LatexSyntaxHighlighter.LABEL_DEFINITION } // Bibliography references (citations). in CommandMagic.bibliographyReference -> { LatexSyntaxHighlighter.BIBLIOGRAPHY_REFERENCE } // Label definitions. in CommandMagic.bibliographyItems -> { LatexSyntaxHighlighter.BIBLIOGRAPHY_DEFINITION } else -> return } command.requiredParameters().firstOrNull()?.let { annotationHolder.annotateRequiredParameter(it, style) } } /** * Annotates the command according to its font style, i.e. \textbf{} gets annotated with the `STYLE_BOLD` style. */ private fun annotateStyle(command: LatexCommands, annotationHolder: AnnotationHolder) { val style = when (command.name) { "\\textbf" -> LatexSyntaxHighlighter.STYLE_BOLD "\\textit" -> LatexSyntaxHighlighter.STYLE_ITALIC "\\underline" -> LatexSyntaxHighlighter.STYLE_UNDERLINE "\\sout" -> LatexSyntaxHighlighter.STYLE_STRIKETHROUGH "\\textsc" -> LatexSyntaxHighlighter.STYLE_SMALL_CAPITALS "\\overline" -> LatexSyntaxHighlighter.STYLE_OVERLINE "\\texttt" -> LatexSyntaxHighlighter.STYLE_TYPEWRITER "\\textsl" -> LatexSyntaxHighlighter.STYLE_SLANTED else -> return } command.requiredParameters().firstOrNull()?.let { annotationHolder.annotateRequiredParameter(it, style) } } /** * Annotates the contents of the given parameter with the given style. */ private fun AnnotationHolder.annotateRequiredParameter(parameter: LatexRequiredParam, style: TextAttributesKey) { val content = parameter.firstChildOfType(LatexContent::class) ?: return this.newSilentAnnotation(HighlightSeverity.INFORMATION) .range(content) .textAttributes(style) .create() } }
mit
02896127f807350bb04f8c3c8f92138d
36.816514
117
0.644833
5.611981
false
false
false
false
ziggy42/Blum
app/src/main/java/com/andreapivetta/blu/data/twitter/TweetsQueue.kt
1
2353
package com.andreapivetta.blu.data.twitter import android.content.Context import com.andreapivetta.blu.R import com.andreapivetta.blu.common.notifications.AppNotifications import com.andreapivetta.blu.common.notifications.AppNotificationsFactory import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import timber.log.Timber import java.io.InputStream import java.util.* /** * Created by andrea on 13/10/16. */ object TweetsQueue { data class StatusUpdate(val text: String, val streams: List<InputStream>, val reply: Long = -1) { companion object { fun valueOf(text: String) = StatusUpdate(text, listOf()) fun valueOf(text: String, reply: Long) = StatusUpdate(text, listOf(), reply) fun valueOf(text: String, files: List<InputStream>) = StatusUpdate(text, files) fun valueOf(text: String, files: List<InputStream>, reply: Long) = StatusUpdate(text, files, reply) } } private val queue: Queue<StatusUpdate> = LinkedList<StatusUpdate>() private lateinit var appNotifications: AppNotifications private lateinit var context: Context private var sending = false fun init(context: Context) { this.context = context this.appNotifications = AppNotificationsFactory.getAppNotifications(context) } fun add(update: StatusUpdate) { queue.add(update) tick() } @Synchronized private fun tick() { if (!sending && queue.isNotEmpty()) { sending = true val id = appNotifications.sendLongRunning( context.getString(R.string.sending_tweet_title), context.getString(R.string.sending_tweet_content), R.drawable.ic_publish) TwitterAPI.updateStatus(queue.poll()) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe({ sending = false appNotifications.stopLongRunning(id) tick() }, { Timber.e(it) sending = false appNotifications.stopLongRunning(id) tick() }) } } }
apache-2.0
2f50af3e6674b2c020b9f450592fc95a
33.617647
101
0.60986
4.831622
false
false
false
false
TWiStErRob/TWiStErRob
JFixturePlayground/src/test/java/net/twisterrob/test/jfixture/examples/journey/JourneyBuilder.kt
1
1048
package net.twisterrob.test.jfixture.examples.journey import java.time.Clock import java.time.LocalDateTime import java.time.ZoneOffset class JourneyBuilder( private var id: String = "", private val legs: MutableList<Leg> = mutableListOf() ) { fun build() = Journey(id, legs, emptyList()) fun setId(id: String): JourneyBuilder = this.apply { this.id = id } fun addLeg(leg: Leg): JourneyBuilder = this.apply { legs.add(leg) } } class LegBuilder( private var origin: Stop = Stop("", ""), private var departure: LocalDateTime = LocalDateTime.now(clock), private var mode: TransportMode = TransportMode.WALK, private var destination: Stop = Stop("", ""), private var arrival: LocalDateTime = LocalDateTime.now(clock) ) { fun build() = Leg(origin, departure, mode, destination, arrival) fun setOrigin(origin: Stop): LegBuilder = this.apply { this.origin = origin } fun setMode(mode: TransportMode): LegBuilder = this.apply { this.mode = mode } // ... companion object { private val clock = Clock.tickMillis(ZoneOffset.UTC) } }
unlicense
2225caa12c9f7c7608e8f9e541b301b1
28.942857
79
0.722328
3.576792
false
false
false
false
schaal/ocreader
app/src/main/java/email/schaal/ocreader/view/ProgressFloatingActionButton.kt
1
1500
package email.schaal.ocreader.view import android.content.Context import android.content.res.ColorStateList import android.graphics.Canvas import android.graphics.Paint import android.util.AttributeSet import androidx.annotation.Keep import com.google.android.material.floatingactionbutton.FloatingActionButton import email.schaal.ocreader.R /** * FloatingActionButton with ability to show progress */ class ProgressFloatingActionButton(context: Context, attrs: AttributeSet?) : FloatingActionButton(context, attrs) { private val circlePaint = Paint() var progress = 0f @Keep set(value) { field = value invalidate() } private val diameter: Float = resources.getDimensionPixelSize(R.dimen.fab_size_normal).toFloat() @Keep fun setFabBackgroundColor(color: Int) { backgroundTintList = ColorStateList.valueOf(color) } override fun onDraw(canvas: Canvas) { val radius = diameter / 2 val count = canvas.save() // draw progress circle fraction canvas.clipRect(0f, diameter * (1 - progress), diameter, diameter) canvas.drawCircle(radius, radius, radius, circlePaint) canvas.restoreToCount(count) super.onDraw(canvas) } init { context.obtainStyledAttributes(attrs, R.styleable.ProgressFloatingActionButton).also { circlePaint.color = it.getColor(R.styleable.ProgressFloatingActionButton_progressColor, 0) }.recycle() } }
gpl-3.0
7363603f3a97e5e6980378dcd98b6b1e
30.93617
115
0.708667
4.731861
false
false
false
false
d3xter/bo-android
app/src/main/java/org/blitzortung/android/data/provider/blitzortung/TimestampIterator.kt
1
1570
/* Copyright 2015 Andreas Würl 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. */ package org.blitzortung.android.data.provider.blitzortung class TimestampIterator( private val intervalLength: Long, startTime: Long, private val endTime: Long = System.currentTimeMillis() ) : Iterator<Long> { private var currentTime: Long = roundTime(startTime) fun roundTime(time: Long): Long { return time / intervalLength * intervalLength } override fun hasNext(): Boolean { return currentTime <= endTime } override fun next(): Long { val currentTimeCopy = currentTime currentTime += intervalLength return currentTimeCopy } } /** * Values of the Timestamp-Sequence are lazy generated, so we provide a Sequence for it * @param intervalLength Interval length * @param startTime Start time of the sequence */ internal fun createTimestampSequence(intervalLength: Long, startTime: Long): Sequence<Long> { return Sequence { TimestampIterator(intervalLength, startTime) } }
apache-2.0
925fd43d7352c565d383b6857afa1c04
29.764706
93
0.718292
4.768997
false
false
false
false
tasks/tasks
app/src/main/java/org/tasks/location/AndroidLocationManager.kt
1
1469
package org.tasks.location import android.annotation.SuppressLint import android.app.PendingIntent import android.content.Context import android.location.Location import dagger.hilt.android.qualifiers.ApplicationContext import timber.log.Timber import javax.inject.Inject class AndroidLocationManager @Inject constructor( @ApplicationContext private val context: Context, ) : LocationManager { private val locationManager get() = context.getSystemService(android.location.LocationManager::class.java) override val lastKnownLocations: List<Location> get() = locationManager.allProviders.mapNotNull { locationManager.getLastKnownLocationOrNull(it) } @SuppressLint("MissingPermission") override fun addProximityAlert( latitude: Double, longitude: Double, radius: Float, intent: PendingIntent ) = locationManager.addProximityAlert(latitude, longitude, radius, -1, intent) override fun removeProximityAlert(intent: PendingIntent) = locationManager.removeProximityAlert(intent) companion object { @SuppressLint("MissingPermission") private fun android.location.LocationManager.getLastKnownLocationOrNull(provider: String) = try { getLastKnownLocation(provider) } catch (e: Exception) { Timber.e(e) null } } }
gpl-3.0
e9b71cf254924f6d5017ae2114eaf268
32.409091
99
0.683458
5.481343
false
false
false
false
natanieljr/droidmate
project/pcComponents/core/src/main/kotlin/org/droidmate/tools/LogcatMonitor.kt
1
2730
package org.droidmate.tools import kotlinx.coroutines.* import org.droidmate.configuration.ConfigurationWrapper import org.droidmate.device.android_sdk.IAdbWrapper import org.droidmate.logging.Markers import org.droidmate.misc.SysCmdInterruptableExecutor import java.nio.file.Files import java.nio.file.Path import org.slf4j.Logger import org.slf4j.LoggerFactory import java.util.concurrent.atomic.AtomicBoolean import kotlin.coroutines.CoroutineContext class LogcatMonitor(private val cfg: ConfigurationWrapper, private val adbWrapper: IAdbWrapper): CoroutineScope { private val log: Logger by lazy { LoggerFactory.getLogger(LogcatMonitor::class.java) } override val coroutineContext: CoroutineContext = CoroutineName("LogcatMonitor") + Job() + Dispatchers.Default // Coverage monitor variables private val sysCmdExecutor = SysCmdInterruptableExecutor() private var running: AtomicBoolean = AtomicBoolean(true) /** * Starts the monitoring job. */ fun start() { launch(start = CoroutineStart.DEFAULT) { run() } } /** * Starts monitoring logcat. */ private suspend fun run() { log.info(Markers.appHealth, "Start monitoring logcat. Output to ${getLogfilePath().toAbsolutePath()}") try { withContext(Dispatchers.IO) { Files.createDirectories(getLogfilePath().parent) while (running.get()) { monitorLogcat() delay(5) } } } catch (ex: Exception) { ex.printStackTrace() } } /** * Starts executing a command in order to monitor the logcat if the previous command is already terminated. */ private fun monitorLogcat() { val path = getLogfilePath() val output = adbWrapper.executeCommand(sysCmdExecutor, cfg.deviceSerialNumber, "", "Logcat logfile monitor", "logcat", "-v", "time") // Append the logcat content to the logfile log.info("Writing logcat output into $path") val file = path.toFile() file.appendBytes(output.toByteArray()) } /** * Returns the logfile name in which the logcat content is written into. */ private fun getLogfilePath(): Path { return cfg.droidmateOutputDirPath.resolve("logcat.log") } /** * Notifies the logcat monitor and [sysCmdExecutor] to finish. */ fun terminate() { running.set(false) sysCmdExecutor.stopCurrentExecutionIfExisting() log.info("Logcat monitor thread destroyed") runBlocking { if(!coroutineContext.isActive) coroutineContext[Job]?.cancelAndJoin() } } }
gpl-3.0
65edd76c6a5af62afee8dd5ef58ce67c
30.755814
116
0.658608
4.772727
false
false
false
false
jonalmeida/focus-android
app/src/main/java/org/mozilla/focus/activity/InstallFirefoxActivity.kt
2
2607
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*- * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.activity import android.app.Activity import android.content.Context import android.content.Intent import android.content.pm.ActivityInfo import android.net.Uri import android.os.Bundle import android.webkit.WebView import org.mozilla.focus.telemetry.TelemetryWrapper import org.mozilla.focus.utils.AppConstants import org.mozilla.focus.utils.Browsers /** * Helper activity that will open the Google Play store by following a redirect URL. */ class InstallFirefoxActivity : Activity() { private var webView: WebView? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) webView = WebView(this) setContentView(webView) webView!!.loadUrl(REDIRECT_URL) } override fun onPause() { super.onPause() if (webView != null) { webView!!.onPause() } finish() } override fun onDestroy() { super.onDestroy() if (webView != null) { webView!!.destroy() } } companion object { private const val REDIRECT_URL = "https://app.adjust.com/gs1ao4" fun resolveAppStore(context: Context): ActivityInfo? { val resolveInfo = context.packageManager.resolveActivity(createStoreIntent(), 0) if (resolveInfo?.activityInfo == null) { return null } return if (!resolveInfo.activityInfo.exported) { // We are not allowed to launch this activity. null } else resolveInfo.activityInfo } private fun createStoreIntent(): Intent { return Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + Browsers.KnownBrowser.FIREFOX.packageName)) } fun open(context: Context) { if (AppConstants.isKlarBuild) { // Redirect to Google Play directly context.startActivity(createStoreIntent()) } else { // Start this activity to load the redirect URL in a WebView. val intent = Intent(context, InstallFirefoxActivity::class.java) context.startActivity(intent) } TelemetryWrapper.installFirefoxEvent() } } }
mpl-2.0
ec1d0fa98d51b9165720666c36e93f2b
28.292135
98
0.624089
4.672043
false
false
false
false
nemerosa/ontrack
ontrack-extension-general/src/main/java/net/nemerosa/ontrack/extension/general/MetaInfoPropertyType.kt
1
6134
package net.nemerosa.ontrack.extension.general import com.fasterxml.jackson.databind.JsonNode import net.nemerosa.ontrack.extension.support.AbstractPropertyType import net.nemerosa.ontrack.model.form.Form import net.nemerosa.ontrack.model.form.MultiForm import net.nemerosa.ontrack.model.form.Text import net.nemerosa.ontrack.model.security.ProjectConfig import net.nemerosa.ontrack.model.security.SecurityService import net.nemerosa.ontrack.model.structure.ProjectEntity import net.nemerosa.ontrack.model.structure.ProjectEntityType import net.nemerosa.ontrack.model.structure.PropertySearchArguments import net.nemerosa.ontrack.model.structure.SearchIndexService import org.apache.commons.lang3.StringUtils import org.springframework.stereotype.Component import java.util.* import java.util.function.Function @Component class MetaInfoPropertyType( extensionFeature: GeneralExtensionFeature, private val searchIndexService: SearchIndexService, private val metaInfoSearchExtension: MetaInfoSearchExtension ) : AbstractPropertyType<MetaInfoProperty>(extensionFeature) { override fun getName(): String = "Meta information" override fun getDescription(): String = "List of meta information properties" override fun getSupportedEntityTypes(): Set<ProjectEntityType> = EnumSet.allOf(ProjectEntityType::class.java) override fun canEdit(entity: ProjectEntity, securityService: SecurityService): Boolean { return securityService.isProjectFunctionGranted(entity, ProjectConfig::class.java) } override fun canView(entity: ProjectEntity, securityService: SecurityService): Boolean = true override fun onPropertyChanged(entity: ProjectEntity, value: MetaInfoProperty) { searchIndexService.createSearchIndex(metaInfoSearchExtension, MetaInfoSearchItem(entity, value)) } override fun onPropertyDeleted(entity: ProjectEntity, oldValue: MetaInfoProperty) { searchIndexService.deleteSearchIndex(metaInfoSearchExtension, MetaInfoSearchItem(entity, oldValue).id) } override fun getEditionForm(entity: ProjectEntity, value: MetaInfoProperty?): Form = Form.create() .with( MultiForm.of( "items", Form.create() .name() .with( Text.of("value").label("Value") ) .with( Text.of("link").label("Link").optional() ) .with( Text.of("category").label("Category").optional() ) ) .label("Items") .value(value?.items ?: emptyList<Any>()) ) override fun fromClient(node: JsonNode): MetaInfoProperty { return fromStorage(node) } override fun fromStorage(node: JsonNode): MetaInfoProperty { return parse(node, MetaInfoProperty::class.java) } override fun containsValue(property: MetaInfoProperty, propertyValue: String): Boolean { val pos = StringUtils.indexOf(propertyValue, ":") return if (pos > 0) { val value = StringUtils.substringAfter(propertyValue, ":") val name = StringUtils.substringBefore(propertyValue, ":") property.matchNameValue(name, value) } else { false } } override fun replaceValue(value: MetaInfoProperty, replacementFunction: Function<String, String>): MetaInfoProperty { return MetaInfoProperty( value.items .map { item -> MetaInfoPropertyItem( item.name, item.value?.apply { replacementFunction.apply(this) }, item.link?.apply { replacementFunction.apply(this) }, item.category?.apply { replacementFunction.apply(this) } ) } ) } override fun getSearchArguments(token: String): PropertySearchArguments? { val name: String? val value: String? if (token.indexOf(":") >= 1) { name = token.substringBefore(":").trim() value = token.substringAfter(":").trimStart() } else { name = null value = token } return if (name.isNullOrBlank()) { if (value.isNullOrBlank()) { // Empty null } else { // Value only PropertySearchArguments( jsonContext = "jsonb_array_elements(pp.json->'items') as item", jsonCriteria = "item->>'value' ilike :value", criteriaParams = mapOf( "value" to value.toValuePattern() ) ) } } else if (value.isNullOrBlank()) { // Name only PropertySearchArguments( jsonContext = "jsonb_array_elements(pp.json->'items') as item", jsonCriteria = "item->>'name' = :name", criteriaParams = mapOf( "name" to name ) ) } else { // Name & value PropertySearchArguments( jsonContext = "jsonb_array_elements(pp.json->'items') as item", jsonCriteria = "item->>'name' = :name and item->>'value' ilike :value", criteriaParams = mapOf( "name" to name, "value" to value.toValuePattern() ) ) } } private fun String.toValuePattern(): String { return this.replace("*", "%") } }
mit
6cf7c226b3e6b18e89844341c0228cfb
40.445946
121
0.556733
5.462155
false
false
false
false
06needhamt/Neuroph-Intellij-Plugin
neuroph-plugin/src/com/thomas/needham/neurophidea/examples/kotlin/TrainTest.kt
1
5260
/* The MIT License (MIT) Copyright (c) 2016 Tom Needham 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. */ package com.thomas.needham.neurophidea.examples.kotlin import org.neuroph.core.NeuralNetwork import org.neuroph.core.learning.SupervisedTrainingElement import org.neuroph.core.learning.TrainingSet import org.neuroph.nnet.MultiLayerPerceptron import org.neuroph.nnet.learning.BackPropagation import org.neuroph.util.TransferFunctionType import java.io.* import java.util.* object TrainTest { @JvmStatic var inputSize = 8 @JvmStatic var outputSize = 1 @JvmStatic var network: NeuralNetwork? = null @JvmStatic var trainingSet: TrainingSet<SupervisedTrainingElement>? = null @JvmStatic var testingSet: TrainingSet<SupervisedTrainingElement>? = null @JvmStatic var layers = arrayOf(8, 8, 1) @JvmStatic fun loadNetwork() { network = NeuralNetwork.load("D:/GitHub/Neuroph-Intellij-Plugin/TrainTest.nnet") } @JvmStatic fun trainNetwork() { val list = ArrayList<Int>() for (layer in layers) { list.add(layer) } val network = MultiLayerPerceptron(list, TransferFunctionType.SIGMOID); trainingSet = TrainingSet<SupervisedTrainingElement>(inputSize, outputSize) trainingSet = TrainingSet.createFromFile("D:/GitHub/NeuralNetworkTest/Classroom Occupation Data.csv", inputSize, outputSize, ",") as TrainingSet<SupervisedTrainingElement>? val learningRule = BackPropagation() network.learningRule = learningRule network.learn(trainingSet) network.save("D:/GitHub/Neuroph-Intellij-Plugin/TrainTest.nnet") } @JvmStatic fun testNetwork() { var input = "" val fromKeyboard = BufferedReader(InputStreamReader(System.`in`)) val testValues = ArrayList<Double>() var testValuesDouble: DoubleArray do { try { println("Enter test values or \"\": ") input = fromKeyboard.readLine() if (input == "") { break } input = input.replace(" ", "") val stringVals = input.split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() testValues.clear() for (`val` in stringVals) { testValues.add(java.lang.Double.parseDouble(`val`)) } } catch (ioe: IOException) { ioe.printStackTrace(System.err) } catch (nfe: NumberFormatException) { nfe.printStackTrace(System.err) } testValuesDouble = DoubleArray(testValues.size) for (t in testValuesDouble.indices) { testValuesDouble[t] = testValues[t].toDouble() } network?.setInput(*testValuesDouble) network?.calculate() } while (input != "") } @JvmStatic fun testNetworkAuto(setPath: String) { var total: Double = 0.0 val list = ArrayList<Int>() val outputLine = ArrayList<String>() for (layer in layers) { list.add(layer) } testingSet = TrainingSet.createFromFile(setPath, inputSize, outputSize, ",") as TrainingSet<SupervisedTrainingElement>? val count: Int = testingSet?.elements()?.size!! var averageDeviance = 0.0 var resultString = "" try { val file = File("Results " + setPath) val fw = FileWriter(file) val bw = BufferedWriter(fw) for (i in 0..testingSet?.elements()?.size!! - 1) { val expected: Double val calculated: Double network?.setInput(*testingSet?.elementAt(i)!!.input) network?.calculate() calculated = network?.output!![0] expected = testingSet?.elementAt(i)?.idealArray!![0] println("Calculated Output: " + calculated) println("Expected Output: " + expected) println("Deviance: " + (calculated - expected)) averageDeviance += Math.abs(Math.abs(calculated) - Math.abs(expected)) total += network?.output!![0] resultString = "" for (cols in 0..testingSet?.elementAt(i)?.inputArray?.size!! - 1) { resultString += testingSet?.elementAt(i)?.inputArray!![cols].toString() + ", " } for (t in 0..network?.output!!.size - 1) { resultString += network?.output!![t].toString() + ", " } resultString = resultString.substring(0, resultString.length - 2) resultString += "" bw.write(resultString) bw.flush() println() println("Average: " + (total / count).toString()) println("Average Deviance % : " + (averageDeviance / count * 100).toString()) bw.flush() bw.close() } } catch (ex: IOException) { ex.printStackTrace() } } }
mit
d9e89d469bd5a7fd43f443fe8f348204
32.503185
174
0.713308
3.910781
false
true
false
false
REBOOTERS/AndroidAnimationExercise
imitate/src/main/java/com/engineer/imitate/util/Throttle.kt
1
701
package com.engineer.imitate.util import android.os.SystemClock import java.util.concurrent.TimeUnit class Throttle( skipDuration: Long, timeUnit: TimeUnit ) { private val delayMilliseconds: Long private var oldTime = 0L init { if (skipDuration < 0) { delayMilliseconds = 0 } else { delayMilliseconds = timeUnit.toMillis(skipDuration) } } fun needSkip(): Boolean { val nowTime = SystemClock.elapsedRealtime() val intervalTime = nowTime - oldTime if (oldTime == 0L || intervalTime >= delayMilliseconds) { oldTime = nowTime return false } return true } }
apache-2.0
a3e2b1777094bd47a3d598fb004bb1d4
21.645161
65
0.607703
4.642384
false
false
false
false
Orchextra/orchextra-android-sdk
core/src/main/java/com/gigigo/orchextra/core/utils/LogUtils.kt
1
2973
/* * Created by Orchextra * * Copyright (C) 2017 Gigigo Mobile Services SL * * 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. */ package com.gigigo.orchextra.core.utils import android.util.Log import com.gigigo.orchextra.core.Orchextra object LogUtils { private val MAX_LOG_TAG_LENGTH = 23 var LOG_LEVEL = Log.DEBUG var fileLogging: FileLogging? = null fun makeLogTag(str: String): String { return if (str.length > MAX_LOG_TAG_LENGTH) { str.substring(0, MAX_LOG_TAG_LENGTH - 1) } else { str } } /** * Don't use this when obfuscating class names! */ fun makeLogTag(cls: Class<*>): String = makeLogTag(cls.simpleName) fun LOGD(tag: String, message: String) { if (Orchextra.isDebuggable()) { if (LOG_LEVEL <= Log.DEBUG) { Log.d(tag, message) fileLogging?.log(Log.DEBUG, tag, message) } } } fun LOGD(tag: String, message: String, cause: Throwable) { if (Orchextra.isDebuggable()) { if (LOG_LEVEL <= Log.DEBUG) { Log.d(tag, message, cause) fileLogging?.log(Log.DEBUG, tag, message, cause) } } } fun LOGV(tag: String, message: String) { if (Orchextra.isDebuggable()) { if (LOG_LEVEL <= Log.VERBOSE) { Log.v(tag, message) fileLogging?.log(Log.VERBOSE, tag, message) } } } fun LOGV(tag: String, message: String, cause: Throwable) { if (Orchextra.isDebuggable()) { if (LOG_LEVEL <= Log.VERBOSE) { Log.v(tag, message, cause) fileLogging?.log(Log.VERBOSE, tag, message) } } } fun LOGI(tag: String, message: String) { if (Orchextra.isDebuggable()) { Log.i(tag, message) fileLogging?.log(Log.INFO, tag, message) } } fun LOGI(tag: String, message: String, cause: Throwable) { if (Orchextra.isDebuggable()) { Log.i(tag, message, cause) fileLogging?.log(Log.INFO, tag, message) } } fun LOGW(tag: String, message: String) { Log.w(tag, message) fileLogging?.log(Log.WARN, tag, message) } fun LOGW(tag: String, message: String, cause: Throwable) { Log.w(tag, message, cause) fileLogging?.log(Log.WARN, tag, message, cause) } fun LOGE(tag: String, message: String) { Log.e(tag, message) fileLogging?.log(Log.ERROR, tag, message) } fun LOGE(tag: String, message: String, cause: Throwable) { Log.e(tag, message, cause) fileLogging?.log(Log.ERROR, tag, message, cause) } }
apache-2.0
25b0f770ca8b0623aab2ed4a160880f1
25.318584
75
0.641103
3.436994
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/fragment/message/MessageNewConversationFragment.kt
1
16429
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.fragment.message import android.accounts.AccountManager import android.content.Context import android.graphics.Canvas import android.graphics.Paint import android.graphics.RectF import android.os.Bundle import android.support.annotation.WorkerThread import android.support.v4.app.LoaderManager.LoaderCallbacks import android.support.v4.content.Loader import android.support.v7.widget.LinearLayoutManager import android.text.Editable import android.text.Spannable import android.text.SpannableStringBuilder import android.text.TextUtils import android.text.style.ReplacementSpan import android.view.* import kotlinx.android.synthetic.main.fragment_messages_conversation_new.* import org.mariotaku.kpreferences.get import org.mariotaku.ktextension.* import org.mariotaku.library.objectcursor.ObjectCursor import org.mariotaku.sqliteqb.library.Expression import de.vanita5.twittnuker.R import de.vanita5.twittnuker.adapter.SelectableUsersAdapter import de.vanita5.twittnuker.constant.IntentConstants.* import de.vanita5.twittnuker.constant.nameFirstKey import de.vanita5.twittnuker.extension.model.isOfficial import de.vanita5.twittnuker.extension.queryOne import de.vanita5.twittnuker.extension.text.appendCompat import de.vanita5.twittnuker.fragment.BaseFragment import de.vanita5.twittnuker.loader.CacheUserSearchLoader import de.vanita5.twittnuker.model.ParcelableMessageConversation import de.vanita5.twittnuker.model.ParcelableMessageConversation.ConversationType import de.vanita5.twittnuker.model.ParcelableUser import de.vanita5.twittnuker.model.UserKey import de.vanita5.twittnuker.model.util.AccountUtils import de.vanita5.twittnuker.provider.TwidereDataStore.Messages.Conversations import de.vanita5.twittnuker.task.twitter.message.SendMessageTask import de.vanita5.twittnuker.text.MarkForDeleteSpan import de.vanita5.twittnuker.util.IntentUtils import de.vanita5.twittnuker.util.view.SimpleTextWatcher import java.lang.ref.WeakReference class MessageNewConversationFragment : BaseFragment(), LoaderCallbacks<List<ParcelableUser>?> { private val accountKey by lazy { arguments.getParcelable<UserKey>(EXTRA_ACCOUNT_KEY) } private val account by lazy { AccountUtils.getAccountDetails(AccountManager.get(context), accountKey, true) } private var selectedRecipients: List<ParcelableUser> get() { val text = editParticipants.editableText ?: return emptyList() return text.getSpans(0, text.length, ParticipantSpan::class.java).map(ParticipantSpan::user) } set(value) { val roundRadius = resources.getDimension(R.dimen.element_spacing_xsmall) val spanPadding = resources.getDimension(R.dimen.element_spacing_xsmall) val nameFirst = preferences[nameFirstKey] editParticipants.text = SpannableStringBuilder().apply { value.forEach { user -> val displayName = userColorNameManager.getDisplayName(user, nameFirst) val span = ParticipantSpan(user, displayName, roundRadius, spanPadding) appendCompat(user.screen_name, span, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) append(" ") } } } private var loaderInitialized: Boolean = false private var performSearchRequestRunnable: Runnable? = null private lateinit var usersAdapter: SelectableUsersAdapter override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) setHasOptionsMenu(true) usersAdapter = SelectableUsersAdapter(context, requestManager) recyclerView.adapter = usersAdapter recyclerView.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false) editParticipants.addTextChangedListener(object : SimpleTextWatcher { override fun afterTextChanged(s: Editable) { s.getSpans(0, s.length, MarkForDeleteSpan::class.java).forEach { span -> val deleteStart = s.getSpanStart(span) val deleteEnd = s.getSpanEnd(span) s.removeSpan(span) s.delete(deleteStart, deleteEnd) } } override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) { super.beforeTextChanged(s, start, count, after) } override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { if (s !is Spannable) return s.getSpans(0, s.length, PendingQuerySpan::class.java).forEach { span -> s.removeSpan(span) } // Processing deletion if (count < before) { val spans = s.getSpans(start, start, ParticipantSpan::class.java) if (spans.isNotEmpty()) { spans.forEach { span -> val deleteStart = s.getSpanStart(span) val deleteEnd = s.getSpanEnd(span) s.removeSpan(span) s.setSpan(MarkForDeleteSpan(), deleteStart, deleteEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) updateCheckState() } return } } val spaceNextStart = run { val spaceIdx = s.indexOfLast(Char::isWhitespace) if (spaceIdx < 0) return@run 0 return@run spaceIdx + 1 } // Skip if last char is space if (spaceNextStart > s.lastIndex) return if (s.getSpans(start, start + count, ParticipantSpan::class.java).isEmpty()) { s.setSpan(PendingQuerySpan(), spaceNextStart, start + count, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) searchUser(s.substring(spaceNextStart), true) } } }) val nameFirst = preferences[nameFirstKey] val roundRadius = resources.getDimension(R.dimen.element_spacing_xsmall) val spanPadding = resources.getDimension(R.dimen.element_spacing_xsmall) usersAdapter.itemCheckedListener = itemChecked@ { pos, checked -> val text: Editable = editParticipants.editableText ?: return@itemChecked false val user = usersAdapter.getUser(pos) if (checked) { text.getSpans(0, text.length, PendingQuerySpan::class.java).forEach { pending -> val start = text.getSpanStart(pending) val end = text.getSpanEnd(pending) text.removeSpan(pending) if (start < 0 || end < 0 || end < start) return@forEach text.delete(start, end) } val displayName = userColorNameManager.getDisplayName(user, nameFirst) val span = ParticipantSpan(user, displayName, roundRadius, spanPadding) text.appendCompat(user.screen_name, span, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) text.append(" ") } else { text.getSpans(0, text.length, ParticipantSpan::class.java).forEach { span -> if (user != span.user) { return@forEach } val start = text.getSpanStart(span) var end = text.getSpanEnd(span) text.removeSpan(span) // Also remove last whitespace if (end <= text.lastIndex && text[end].isWhitespace()) { end += 1 } text.delete(start, end) } } editParticipants.clearComposingText() updateCheckState() return@itemChecked true } if (savedInstanceState == null) { val users = arguments.getNullableTypedArray<ParcelableUser>(EXTRA_USERS) if (users != null && users.isNotEmpty()) { selectedRecipients = users.toList() editParticipants.setSelection(editParticipants.length()) if (arguments.getBoolean(EXTRA_OPEN_CONVERSATION)) { createOrOpenConversation() } } } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { return inflater.inflate(R.layout.fragment_messages_conversation_new, container, false) } override fun onCreateLoader(id: Int, args: Bundle): Loader<List<ParcelableUser>?> { val query = args.getString(EXTRA_QUERY) val fromCache = args.getBoolean(EXTRA_FROM_CACHE) val fromUser = args.getBoolean(EXTRA_FROM_USER) return CacheUserSearchLoader(context, accountKey, query, !fromCache, true, fromUser) } override fun onLoaderReset(loader: Loader<List<ParcelableUser>?>) { usersAdapter.data = null } override fun onLoadFinished(loader: Loader<List<ParcelableUser>?>, data: List<ParcelableUser>?) { usersAdapter.data = data updateCheckState() } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.menu_messages_conversation_new, menu) } override fun onPrepareOptionsMenu(menu: Menu) { menu.setItemAvailability(R.id.create_conversation, selectedRecipients.isNotEmpty()) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.create_conversation -> { createOrOpenConversation() return true } } return super.onOptionsItemSelected(item) } private fun createOrOpenConversation() { val account = this.account ?: return val selected = this.selectedRecipients if (selected.isEmpty()) return val maxParticipants = if (account.isOfficial(context)) { defaultFeatures.twitterDirectMessageMaxParticipants } else { 1 } if (selected.size > maxParticipants) { editParticipants.error = getString(R.string.error_message_message_too_many_participants) return } val conversation = ParcelableMessageConversation() conversation.account_color = account.color conversation.account_key = account.key conversation.id = "${SendMessageTask.TEMP_CONVERSATION_ID_PREFIX}${System.currentTimeMillis()}" conversation.local_timestamp = System.currentTimeMillis() conversation.conversation_type = if (selected.size > 1) { ConversationType.GROUP } else { ConversationType.ONE_TO_ONE } conversation.participants = (selected + account.user).toTypedArray() conversation.is_temp = true if (conversation.conversation_type == ConversationType.ONE_TO_ONE) { val participantKeys = conversation.participants.map(ParcelableUser::key) val existingConversation = findMessageConversation(context, accountKey, participantKeys) if (existingConversation != null) { activity.startActivity(IntentUtils.messageConversation(accountKey, existingConversation.id)) activity.finish() return } } val values = ObjectCursor.valuesCreatorFrom(ParcelableMessageConversation::class.java).create(conversation) context.contentResolver.insert(Conversations.CONTENT_URI, values) activity.startActivity(IntentUtils.messageConversation(accountKey, conversation.id)) activity.finish() } private fun updateCheckState() { val selected = selectedRecipients usersAdapter.clearCheckState() usersAdapter.clearLockedState() usersAdapter.setLockedState(accountKey, true) selected.forEach { user -> usersAdapter.setCheckState(user.key, true) } usersAdapter.notifyDataSetChanged() activity?.invalidateOptionsMenu() } private fun searchUser(query: String, fromType: Boolean) { if (TextUtils.isEmpty(query)) { return } val args = Bundle { this[EXTRA_ACCOUNT_KEY] = accountKey this[EXTRA_QUERY] = query this[EXTRA_FROM_CACHE] = fromType } if (loaderInitialized) { loaderManager.initLoader(0, args, this) loaderInitialized = true } else { loaderManager.restartLoader(0, args, this) } if (performSearchRequestRunnable != null) { editParticipants.removeCallbacks(performSearchRequestRunnable) } if (fromType) { performSearchRequestRunnable = PerformSearchRequestRunnable(query, this) editParticipants.postDelayed(performSearchRequestRunnable, 1000L) } } @WorkerThread fun findMessageConversation(context: Context, accountKey: UserKey, participantKeys: Collection<UserKey>): ParcelableMessageConversation? { val resolver = context.contentResolver val where = Expression.and(Expression.equalsArgs(Conversations.ACCOUNT_KEY), Expression.equalsArgs(Conversations.PARTICIPANT_KEYS)).sql val whereArgs = arrayOf(accountKey.toString(), participantKeys.sorted().joinToString(",")) return resolver.queryOne(Conversations.CONTENT_URI, Conversations.COLUMNS, where, whereArgs, null, ParcelableMessageConversation::class.java) } internal class PerformSearchRequestRunnable(val query: String, fragment: MessageNewConversationFragment) : Runnable { val fragmentRef = WeakReference(fragment) override fun run() { val fragment = fragmentRef.get() ?: return fragment.searchUser(query, false) } } class PendingQuerySpan class ParticipantSpan( val user: ParcelableUser, val displayName: String, val roundRadius: Float, val padding: Float ) : ReplacementSpan() { private var backgroundPaint = Paint(Paint.ANTI_ALIAS_FLAG) private var backgroundBounds = RectF() private var nameWidth: Float = 0f init { backgroundPaint.color = 0x20808080 } override fun draw(canvas: Canvas, text: CharSequence, start: Int, end: Int, x: Float, top: Int, y: Int, bottom: Int, paint: Paint) { backgroundBounds.set(x, top.toFloat() + padding / 2, x + nameWidth + padding * 2, bottom - padding / 2) canvas.drawRoundRect(backgroundBounds, roundRadius, roundRadius, backgroundPaint) val textSizeBackup = paint.textSize paint.textSize = textSizeBackup - padding canvas.drawText(displayName, x + padding, y - padding / 2, paint) paint.textSize = textSizeBackup } override fun getSize(paint: Paint, text: CharSequence, start: Int, end: Int, fm: Paint.FontMetricsInt?): Int { val textSizeBackup = paint.textSize paint.textSize = textSizeBackup - padding nameWidth = paint.measureText(displayName) paint.textSize = textSizeBackup return Math.round(nameWidth + padding * 2) } } }
gpl-3.0
1bd7e6502afdfc75c4edc9216deb5e52
42.696809
140
0.646174
5.024159
false
false
false
false
stripe/stripe-android
payments-core/src/main/java/com/stripe/android/cards/DefaultCardAccountRangeStore.kt
1
1529
package com.stripe.android.cards import android.content.Context import androidx.annotation.VisibleForTesting import com.stripe.android.model.AccountRange import com.stripe.android.model.parsers.AccountRangeJsonParser import org.json.JSONObject internal class DefaultCardAccountRangeStore( private val context: Context ) : CardAccountRangeStore { private val accountRangeJsonParser = AccountRangeJsonParser() private val prefs by lazy { context.getSharedPreferences(PREF_FILE, Context.MODE_PRIVATE) } override suspend fun get(bin: Bin): List<AccountRange> { return prefs.getStringSet(createPrefKey(bin), null) .orEmpty() .mapNotNull { accountRangeJsonParser.parse(JSONObject(it)) } } override fun save( bin: Bin, accountRanges: List<AccountRange> ) { val serializedAccountRanges = accountRanges.map { accountRangeJsonParser.serialize(it).toString() }.toSet() prefs.edit() .putStringSet(createPrefKey(bin), serializedAccountRanges) .apply() } override suspend fun contains( bin: Bin ): Boolean = prefs.contains(createPrefKey(bin)) @VisibleForTesting internal fun createPrefKey(bin: Bin): String = "$PREF_KEY_ACCOUNT_RANGES:$bin" private companion object { private const val PREF_FILE = "InMemoryCardAccountRangeSource.Store" private const val PREF_KEY_ACCOUNT_RANGES = "key_account_ranges" } }
mit
c211c4bdb14e62be2f68b331d8e51bb7
29.58
82
0.685415
4.675841
false
false
false
false
hannesa2/owncloud-android
owncloudData/src/test/java/com/owncloud/android/data/capabilities/datasources/OCRemoteCapabilitiesDataSourceTest.kt
2
2753
/** * ownCloud Android client application * * @author David González Verdugo * @author Jesús Recio * Copyright (C) 2020 ownCloud GmbH. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.owncloud.android.data.capabilities.datasources import com.owncloud.android.data.capabilities.datasources.implementation.OCRemoteCapabilitiesDataSource import com.owncloud.android.lib.resources.status.services.implementation.OCCapabilityService import com.owncloud.android.data.capabilities.datasources.mapper.RemoteCapabilityMapper import com.owncloud.android.testutil.OC_ACCOUNT_NAME import com.owncloud.android.testutil.OC_CAPABILITY import com.owncloud.android.utils.createRemoteOperationResultMock import io.mockk.every import io.mockk.mockk import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull import org.junit.Before import org.junit.Test class OCRemoteCapabilitiesDataSourceTest { private lateinit var ocRemoteCapabilitiesDataSource: OCRemoteCapabilitiesDataSource private val ocCapabilityService: OCCapabilityService = mockk() private val remoteCapabilityMapper = RemoteCapabilityMapper() @Before fun init() { ocRemoteCapabilitiesDataSource = OCRemoteCapabilitiesDataSource( ocCapabilityService, remoteCapabilityMapper ) } @Test fun readRemoteCapabilities() { val accountName = OC_ACCOUNT_NAME val remoteCapability = remoteCapabilityMapper.toRemote(OC_CAPABILITY)!! val getRemoteCapabilitiesOperationResult = createRemoteOperationResultMock(remoteCapability, true) every { ocCapabilityService.getCapabilities() } returns getRemoteCapabilitiesOperationResult // Get capability from remote datasource val capabilities = ocRemoteCapabilitiesDataSource.getCapabilities(accountName) assertNotNull(capabilities) assertEquals(OC_CAPABILITY.accountName, capabilities.accountName) assertEquals(OC_CAPABILITY.versionMayor, capabilities.versionMayor) assertEquals(OC_CAPABILITY.versionMinor, capabilities.versionMinor) assertEquals(OC_CAPABILITY.versionMicro, capabilities.versionMicro) } }
gpl-2.0
57d0a71d3c48741193f9fc1f39a8b6c0
37.746479
106
0.774264
4.903743
false
true
false
false
Dmedina88/SSB
example/app/src/main/kotlin/com/grayherring/devtalks/di/DataModule.kt
1
3301
package com.grayherring.devtalks.di import android.app.Application import com.google.gson.Gson import com.google.gson.GsonBuilder import com.grayherring.devtalks.base.util.capture.GsonPrefRecorder import com.grayherring.devtalks.data.repository.Repository import com.grayherring.devtalks.data.repository.api.DevTalkApi import com.grayherring.devtalks.data.repository.api.DevTalkApiClient import com.grayherring.devtalks.data.repository.api.ExceptionInterceptor import com.grayherring.devtalks.ui.home.HomeState import com.readystatesoftware.chuck.ChuckInterceptor import dagger.Module import dagger.Provides import okhttp3.HttpUrl import okhttp3.OkHttpClient import okhttp3.OkHttpClient.Builder import okhttp3.logging.HttpLoggingInterceptor import okhttp3.logging.HttpLoggingInterceptor.Level.BODY import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import javax.inject.Singleton @Module(includes = arrayOf(ViewModelModule::class)) class DataModule { // @PerApp @Provides fun provideAppDatabase(context: Context) = AppDatabase.createPersistentDatabase(context) @Provides @Singleton fun providesGson() = GsonBuilder() .setDateFormat("yyyy-dd-MM") .create() @Provides @Singleton fun provideExceptionInterceptor(gson: Gson) = ExceptionInterceptor(gson) @Provides @Singleton fun provideOkHttpClient(exceptionInterceptor: ExceptionInterceptor, application: Application): OkHttpClient { val clientBuilder = Builder() val httpLoggingInterceptor = HttpLoggingInterceptor() httpLoggingInterceptor.level = BODY clientBuilder.addInterceptor(ChuckInterceptor(application)) clientBuilder.addInterceptor(httpLoggingInterceptor) clientBuilder.addInterceptor(exceptionInterceptor) return clientBuilder.build() } @Provides @Singleton fun provideHttpUrl(): HttpUrl = HttpUrl.parse("https://dev-talk-test.herokuapp.com") as HttpUrl @Provides @Singleton fun provideDevTalkApiClient(devTalkApi: DevTalkApi) = DevTalkApiClient( devTalkApi) @Provides @Singleton fun provideRepository(devTalkApi: DevTalkApiClient) = Repository(devTalkApi) @Provides @Singleton fun provideRetrofit(baseUrl: HttpUrl, client: OkHttpClient, gson: Gson): Retrofit { return Retrofit.Builder() .client(client) .baseUrl(baseUrl) .addConverterFactory(GsonConverterFactory.create(gson)) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build() } @Provides @Singleton fun provideDevTalkApi(retrofit: Retrofit): DevTalkApi { return retrofit.create(DevTalkApi::class.java) } @Provides @Singleton fun provideHomeCapturer(application: Application, gson: Gson): GsonPrefRecorder<HomeState> { return GsonPrefRecorder<HomeState>(application.applicationContext.getSharedPreferences("preft", 0), "stat", Array<HomeState>::class.java, gson) } // @Provides @Singleton fun provideLocalTalkDB(context: Context): TalkDB // = Room.databaseBuilder(context, TalkDB::class.java, "database-name").build() }
apache-2.0
a7efaf9c822aa4129a5e15b8ff5b4dde
37.835294
111
0.74644
4.784058
false
false
false
false
hotpodata/redchain
mobile/src/main/java/com/hotpodata/redchain/adapter/ChainAdapter.kt
1
13016
package com.hotpodata.redchain.adapter import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.animation.ValueAnimator import android.content.Context import android.provider.Settings import android.support.v7.widget.RecyclerView import android.transition.AutoTransition import android.transition.Scene import android.transition.TransitionManager import android.util.TypedValue import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.animation.AccelerateDecelerateInterpolator import android.view.animation.DecelerateInterpolator import android.view.animation.Interpolator import com.google.android.gms.ads.AdRequest import com.google.android.gms.ads.AdView import com.hotpodata.redchain.BuildConfig import com.hotpodata.redchain.ChainMaster import com.hotpodata.redchain.R import com.hotpodata.redchain.adapter.viewholder.* import com.hotpodata.redchain.data.Chain import com.hotpodata.redchain.interfaces.ChainUpdateListener import org.joda.time.Days import org.joda.time.LocalDate import org.joda.time.LocalDateTime import org.joda.time.format.DateTimeFormat import timber.log.Timber import java.security.MessageDigest import java.util.* /** * Created by jdrotos on 9/17/15. */ public class ChainAdapter(context: Context, argChain: Chain) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { val ctx = context val CHAIN_LINK = 0; val VERTICAL_LINE = 1; val CHAIN_TODAY = 2; val CHAIN_FIRST_DAY_MESSAGE = 3; val CHAIN_AD = 4 var chain: Chain var rows = ArrayList<Row>() val dtformat1 = DateTimeFormat.forPattern("EEEE") val dtformat2 = DateTimeFormat.shortDate() val dtformat3 = DateTimeFormat.shortTime() val interpo: Interpolator; val rowMaxTitleSize: Int val rowMinTitleSize: Int val rowMaxLineSize: Int val rowMinLineSize: Int var chainUpdateListener: ChainUpdateListener? = null var todayChainAnimFlag = false init { chain = argChain rowMaxTitleSize = context.resources.getDimensionPixelSize(R.dimen.row_title_max) rowMinTitleSize = context.resources.getDimensionPixelSize(R.dimen.row_title_min) rowMaxLineSize = context.resources.getDimensionPixelSize(R.dimen.row_vert_line_max_height) rowMinLineSize = context.resources.getDimensionPixelSize(R.dimen.row_vert_line_min_height) interpo = DecelerateInterpolator(10f); buildRows() } private fun goToScene(vg: ViewGroup, layoutResId: Int, animate: Boolean) { if (animate && android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) { var scene = Scene.getSceneForLayout(vg, layoutResId, ctx) TransitionManager.go(scene, AutoTransition()); } else { vg.removeAllViews() LayoutInflater.from(ctx).inflate(layoutResId, vg, true) } } @Suppress("DEPRECATION") override fun onBindViewHolder(holder: RecyclerView.ViewHolder?, position: Int) { if (holder is ChainTodayWithStatsVh) { if (chain.chainContainsToday()) { if (holder.statsContainer == null) { goToScene(holder.sceneRoot, R.layout.include_row_chain_today_with_stats_checked, todayChainAnimFlag) holder.rebindViews() } holder.xview.setOnClickListener(null) holder.xview.isClickable = false holder.xview.boxToXPercentage = 1f holder.xview.setColors(chain.color, ctx.resources.getColor(R.color.material_grey)) holder.todayTitleTv.invalidate() holder.timeTv?.text = chain.newestDate?.toString(dtformat3) holder.currentDayCountTv?.text = "" + chain.chainLength holder.currentDayLabelTv?.text = ctx.resources.getQuantityString(R.plurals.days_and_counting, chain.chainLength) holder.bestInChainCountTv?.text = "" + chain.longestRun holder.bestAllChainsCountTv?.text = "" + ChainMaster.getLongestRunOfAllChains() todayChainAnimFlag = false } else { if (holder.motivationBlurbTv == null) { goToScene(holder.sceneRoot, R.layout.include_row_chain_today_with_stats_unchecked,todayChainAnimFlag) holder.rebindViews() } holder.todayTitleTv.invalidate() holder.xview.isClickable = true holder.xview.setColors(chain.color, ctx.resources.getColor(R.color.material_grey)) holder.xview.boxToXPercentage = 0f holder.xview.setOnClickListener { //update data chain.addNowToChain(); chainUpdateListener?.onChainUpdated(chain) //start anim var start = if (holder.xview.boxToXPercentage == 1f) 1f else 0f; var end = if (holder.xview.boxToXPercentage == 1f) 0f else 1f; holder.xview.boxToXPercentage = start; var animator = ValueAnimator.ofFloat(start, end) animator.addUpdateListener { anim -> holder.xview.boxToXPercentage = anim.animatedFraction } animator.addListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator?) { todayChainAnimFlag = true buildRows() } }) animator.interpolator = AccelerateDecelerateInterpolator() animator.setDuration(700) animator.start() } } } if (holder is ChainLinkVh) { var titleHeight = Math.max(rowMinTitleSize, rowMaxTitleSize - position).toFloat()//rowMinTitleSize + (floatDepth * (rowMaxTitleSize - rowMinTitleSize)) var data = rows[position] as RowChainLink //var headingTypeface = rowHeadingTypeface holder.itemView.setOnClickListener(null) holder.xview.setBox(false) holder.xview.setColors(chain.color, ctx.resources.getColor(R.color.material_grey)) if (holder.tv1.textSize != titleHeight) { holder.tv1.setTextSize(TypedValue.COMPLEX_UNIT_PX, titleHeight) } val dateStr = if (data.dateTime.toLocalDate().plusDays(1).isEqual(LocalDate.now())) { ctx.getText(R.string.yesterday) } else if (Days.daysBetween(data.dateTime.toLocalDate(), LocalDate.now()).days < 7) { data.dateTime.toString(dtformat1) } else { data.dateTime.toString(dtformat2) } val timeStr = data.dateTime.toString(dtformat3) val depth = chain.chainLength - chain.chainDepth(data.dateTime) holder.tv1.text = "" + depth holder.tv2.text = "$dateStr\n$timeStr"; } if (holder is VertLineVh) { var lineHeight = Math.max(rowMinLineSize, rowMaxLineSize - position).toFloat() var data = rows.get(position) as RowChainLine if (holder.vertLine.layoutParams != null && holder.vertLine.layoutParams.height != lineHeight.toInt()) { holder.vertLine.layoutParams.height = lineHeight.toInt() holder.vertLine.layoutParams = holder.vertLine.layoutParams } holder.vertLine.setBackgroundColor(chain.color) holder.vertLine.visibility = if (data.invisible) View.INVISIBLE else View.VISIBLE; } if (holder is RowFirstDayMessageVh) { //nothing to do } if (holder is ChainAdVh) { requestAd(holder.adview) } } override fun getItemCount(): Int { return rows.size; } override fun getItemViewType(position: Int): Int { if (rows[position] is RowChainLine) { return VERTICAL_LINE; } else if (rows.get(position) is RowChainLink) { return CHAIN_LINK; } else if (rows.get(position) is RowChainToday) { return CHAIN_TODAY; } else if (rows.get(position) is RowFirstDayMessage) { return CHAIN_FIRST_DAY_MESSAGE } else if (rows.get(position) is RowChainAd) { return CHAIN_AD } return -1; } override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder? { var inflater = LayoutInflater.from(parent?.context); if (viewType == CHAIN_LINK) { var chainView: View? = inflater.inflate(R.layout.card_chain_link_center, parent, false); var vh = ChainLinkVh(chainView); return vh; } if (viewType == VERTICAL_LINE) { var lineView = inflater.inflate(R.layout.row_vertical_line_center, parent, false); return VertLineVh(lineView); } if (viewType == CHAIN_TODAY) { var view = inflater.inflate(R.layout.row_chain_today_with_stats, parent, false) var vh = ChainTodayWithStatsVh(view); return vh; } if (viewType == CHAIN_FIRST_DAY_MESSAGE) { var messageView = inflater.inflate(R.layout.row_first_day_message, parent, false) var vh = RowFirstDayMessageVh(messageView) return vh } if (viewType == CHAIN_AD) { var ad = inflater.inflate(R.layout.card_chain_ad, parent, false) var vh = ChainAdVh(ad) return vh; } return null; } public fun updateChain(chn: Chain) { chain = chn todayChainAnimFlag = false buildRows() //NOTE: buildRows() makes some assumptions, when we set a new chain, we should update all rows notifyDataSetChanged() } public fun buildRows() { var freshRows = ArrayList<Row>() if (chain.chainLength > 0) { var dateTimes = ArrayList<LocalDateTime>(chain.dateTimes); for (dt in dateTimes) { //TODAY has it's own special thing going on if (dt.toLocalDate().isBefore(LocalDate.now())) { if (freshRows.size > 0) { freshRows.add(RowChainLine(false)) } freshRows.add(RowChainLink(dt)) } } if (freshRows.size > 0) { freshRows.add(RowChainLine(true)) } } if (freshRows.size > 0) { freshRows.add(0, RowChainLine(false)) } freshRows.add(0, RowChainToday()); if (freshRows.size == 1 && chain.chainContainsToday()) { freshRows.add(RowFirstDayMessage()) } if (!BuildConfig.IS_PRO) { if (chain.chainLength < chain.longestRun) { Timber.d("Adding RowChainAd()") freshRows.add(1, RowChainLine(false)) freshRows.add(2, RowChainAd()) } } else { Timber.d("Skipping RowChainAd()") } rows = freshRows //TODO: Be smarter about this to get free animations. notifyDataSetChanged() } open class Row() { } class RowChainLink(dt: LocalDateTime) : Row() { val dateTime = dt } class RowChainLine(invis: Boolean) : Row() { val invisible = invis } class RowChainToday() : Row() { } class RowFirstDayMessage() : Row() { } class RowChainAd() : Row() { } /* ADD STUFF */ private fun requestAd(adview: AdView?) { if (!BuildConfig.IS_PRO) { var adRequest = with(AdRequest.Builder()) { if (BuildConfig.IS_DEBUG_BUILD) { addTestDevice(AdRequest.DEVICE_ID_EMULATOR) var andId = Settings.Secure.getString(ctx.contentResolver, Settings.Secure.ANDROID_ID) var hash = md5(andId).toUpperCase() Timber.d("Adding test device. hash:" + hash) addTestDevice(hash) } build() } adview?.loadAd(adRequest); } } private fun md5(s: String): String { try { var digest = MessageDigest.getInstance("MD5") digest.update(s.toByteArray()) var messageDigest = digest.digest() var hexString = StringBuffer() for (i in messageDigest.indices) { var h = Integer.toHexString(0xFF and messageDigest[i].toInt()) while (h.length < 2) h = "0" + h hexString.append(h) } return hexString.toString() } catch(ex: Exception) { Timber.e(ex, "Fail in md5"); } return "" } }
apache-2.0
9b26d3de762c4aaff232e08ca5c4548e
35.980114
163
0.598955
4.456008
false
false
false
false
Gazer/localshare
app/src/main/java/ar/com/p39/localshare/receiver/presenters/DownloadPresenter.kt
1
3569
package ar.com.p39.localshare.receiver.presenters import android.util.Log import ar.com.p39.localshare.common.presenters.Presenter import ar.com.p39.localshare.receiver.models.DownloadFile import ar.com.p39.localshare.receiver.models.DownloadList import ar.com.p39.localshare.receiver.network.SharerClient import ar.com.p39.localshare.receiver.views.DownloadView import okhttp3.OkHttpClient import okhttp3.Request import rx.Observable import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers import java.io.BufferedInputStream import java.io.InputStream class DownloadPresenter(val client: SharerClient, val httpClient: OkHttpClient) : Presenter<DownloadView>() { lateinit var downloadFiles: DownloadList fun inspectUrl(bssid: String) { client.getShareInfo() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { list: DownloadList -> if (bssid != list.ssid) { view()?.connectToWifi(list.ssid) } else { downloadFiles = list view()?.showFiles(list.files) } }, { error -> Log.e("Download", "Connect failed : $error") view()?.showError("Connect failed : $error") } ) } fun startDownload() { view()?.disableUi() Observable.just((downloadFiles as DownloadList).files) .flatMapIterable { it } .flatMap { file -> file.status = 1 view()?.downloadStart() downloadFileObserver(file) } .observeOn(AndroidSchedulers.mainThread()) .subscribe( { file: DownloadFile -> if (file.data != null) { Log.d("Download", "Completed") file.status = 2 view()?.downloadCompleted(file.data as ByteArray) } }, { error -> Log.e("Download", "Connect failed to url : $error") view()?.showError("Connect failed to url") }, { view()?.downloadFinished() } ) } private fun downloadFileObserver(file: DownloadFile): Observable<DownloadFile> { return Observable.defer { Observable.create(Observable.OnSubscribe<DownloadFile> { subscriber -> Log.d("Download", "Map : $file") val request = Request.Builder().url(file.url).build(); val response = httpClient.newCall(request).execute(); val stream: InputStream = response.body().byteStream(); val input: BufferedInputStream = BufferedInputStream(stream); file.data = input.readBytes() subscriber.onNext(file) subscriber.onCompleted() stream.close() input.close() }).subscribeOn(Schedulers.io()) } } }
apache-2.0
3cdef6cea79139377c2313948516e9e3
37.793478
109
0.487812
5.701278
false
false
false
false
andstatus/andstatus
app/src/main/kotlin/org/andstatus/app/note/NoteAdapter.kt
1
3348
/* * Copyright (c) 2015 yvolk (Yuri Volkov), http://yurivolkov.com * * 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. */ package org.andstatus.app.note import android.view.View import android.view.ViewGroup import org.andstatus.app.R import org.andstatus.app.context.MyPreferences import org.andstatus.app.timeline.TimelineActivity import org.andstatus.app.timeline.TimelineData import org.andstatus.app.util.MyUrlSpan /** * @author [email protected] */ class NoteAdapter(contextMenu: NoteContextMenu, listData: TimelineData<NoteViewItem>) : BaseNoteAdapter<NoteViewItem>(contextMenu, listData) { private var positionPrev = -1 private var itemNumberShownCounter = 0 private val TOP_TEXT: String? override fun showAvatarEtc(view: ViewGroup, item: NoteViewItem) { if (showAvatars) { showAvatar(view, item) } else { val noteView = view.findViewById<View?>(R.id.note_indented) noteView?.setPadding(dpToPixes(2), 0, dpToPixes(6), dpToPixes(2)) } } private fun preloadAttachments(position: Int) { if (positionPrev < 0 || position == positionPrev) { return } var positionToPreload = position for (i in 0..4) { positionToPreload = positionToPreload + if (position > positionPrev) 1 else -1 if (positionToPreload < 0 || positionToPreload >= count) { break } val item = getItem(positionToPreload) if (!preloadedImages.contains(item.getNoteId())) { preloadedImages.add(item.getNoteId()) item.attachedImageFiles.preloadImagesAsync() break } } } override fun showNoteNumberEtc(view: ViewGroup, item: NoteViewItem, position: Int) { preloadAttachments(position) val text: String? = when (position) { 0 -> if (mayHaveYoungerPage()) "1" else TOP_TEXT 1, 2 -> Integer.toString(position + 1) else -> if (itemNumberShownCounter < 3) Integer.toString(position + 1) else "" } MyUrlSpan.showText(view, R.id.note_number, text, linkify = false, showIfEmpty = false) itemNumberShownCounter++ positionPrev = position } override fun onClick(v: View) { var handled = false if (MyPreferences.isLongPressToOpenContextMenu()) { val item = getItem(v) if (TimelineActivity::class.java.isAssignableFrom(contextMenu.getActivity().javaClass)) { (contextMenu.getActivity() as TimelineActivity<*>).onItemClick(item) handled = true } } if (!handled) { super.onClick(v) } } init { TOP_TEXT = myContext.context.getText(R.string.top).toString() } }
apache-2.0
d803a2972ec8f742b3b7499ffa303290
35.391304
101
0.641278
4.30888
false
false
false
false
EmmyLua/IntelliJ-EmmyLua
src/main/java/com/tang/intellij/lua/stubs/LuaClosureExprStub.kt
2
2756
/* * Copyright (c) 2017. tangzx([email protected]) * * 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. */ package com.tang.intellij.lua.stubs import com.intellij.psi.stubs.IndexSink import com.intellij.psi.stubs.StubElement import com.intellij.psi.stubs.StubInputStream import com.intellij.psi.stubs.StubOutputStream import com.tang.intellij.lua.psi.LuaClosureExpr import com.tang.intellij.lua.psi.LuaElementTypes import com.tang.intellij.lua.psi.LuaParamInfo import com.tang.intellij.lua.psi.impl.LuaClosureExprImpl import com.tang.intellij.lua.psi.overloads import com.tang.intellij.lua.ty.IFunSignature import com.tang.intellij.lua.ty.ITy import com.tang.intellij.lua.ty.TyParameter class LuaClosureExprType : LuaStubElementType<LuaClosureExprStub, LuaClosureExpr>("CLOSURE_EXPR") { override fun indexStub(stub: LuaClosureExprStub, sink: IndexSink) { } override fun serialize(stub: LuaClosureExprStub, outputStream: StubOutputStream) { outputStream.writeParamInfoArray(stub.params) outputStream.writeSignatures(stub.overloads) } override fun createPsi(stub: LuaClosureExprStub): LuaClosureExpr { return LuaClosureExprImpl(stub, this) } override fun createStub(expr: LuaClosureExpr, parentStub: StubElement<*>?): LuaClosureExprStub { val varargTy = expr.varargType val params = expr.params val overloads = expr.overloads return LuaClosureExprStub(null, varargTy, params, overloads, parentStub) } override fun deserialize(inputStream: StubInputStream, parentStub: StubElement<*>?): LuaClosureExprStub { val params = inputStream.readParamInfoArray() val overloads = inputStream.readSignatures() return LuaClosureExprStub(null, null, params, overloads, parentStub) } } class LuaClosureExprStub( override val returnDocTy: ITy?, override val varargTy: ITy?, override val params: Array<LuaParamInfo>, override val overloads: Array<IFunSignature>, parent: StubElement<*>? ) : LuaStubBase<LuaClosureExpr>(parent, LuaElementTypes.CLOSURE_EXPR), LuaFuncBodyOwnerStub<LuaClosureExpr>, LuaExprStub<LuaClosureExpr> { override val tyParams: Array<TyParameter> get() = emptyArray() }
apache-2.0
fd669ddbdd6fbd0aefc8a8f9916d8397
38.956522
138
0.751814
4.144361
false
false
false
false
inorichi/tachiyomi-extensions
src/fr/mangakawaii/src/eu/kanade/tachiyomi/extension/fr/mangakawaii/MangaKawaii.kt
1
7688
package eu.kanade.tachiyomi.extension.fr.mangakawaii import android.net.Uri import android.util.Base64 import eu.kanade.tachiyomi.lib.ratelimit.RateLimitInterceptor import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.source.model.FilterList import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.source.online.ParsedHttpSource import eu.kanade.tachiyomi.util.asJsoup import okhttp3.Headers import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response import org.jsoup.nodes.Document import org.jsoup.nodes.Element import java.text.SimpleDateFormat import java.util.Locale import java.util.concurrent.TimeUnit import kotlin.math.absoluteValue import kotlin.random.Random /** * Heavily customized MyMangaReaderCMS source */ class MangaKawaii : ParsedHttpSource() { override val name = "Mangakawaii" override val baseUrl = "https://www.mangakawaii.net" val cdnUrl = "https://cdn.mangakawaii.net" override val lang = "fr" override val supportsLatest = true private val rateLimitInterceptor = RateLimitInterceptor(1) // 1 request per second override val client: OkHttpClient = network.cloudflareClient.newBuilder() .connectTimeout(10, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .addNetworkInterceptor(rateLimitInterceptor) .build() protected open val userAgentRandomizer1 = "${Random.nextInt(9).absoluteValue}" protected open val userAgentRandomizer2 = "${Random.nextInt(10, 99).absoluteValue}" protected open val userAgentRandomizer3 = "${Random.nextInt(100, 999).absoluteValue}" override fun headersBuilder(): Headers.Builder = Headers.Builder() .add( "User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) " + "Chrome/8$userAgentRandomizer1.0.4$userAgentRandomizer3.1$userAgentRandomizer2 Safari/537.36" ) // Popular override fun popularMangaRequest(page: Int) = GET(baseUrl, headers) override fun popularMangaSelector() = "a.hot-manga__item" override fun popularMangaNextPageSelector(): String? = null override fun popularMangaFromElement(element: Element): SManga = SManga.create().apply { title = element.select("div.hot-manga__item-caption").select("div.hot-manga__item-name").text().trim() setUrlWithoutDomain(element.select("a").attr("href")) thumbnail_url = "$cdnUrl/uploads" + element.select("a").attr("href") + "/cover/cover_250x350.jpg" } // Latest override fun latestUpdatesRequest(page: Int) = GET(baseUrl, headers) override fun latestUpdatesSelector() = ".section__list-group li div.section__list-group-left" override fun latestUpdatesNextPageSelector(): String? = null override fun latestUpdatesFromElement(element: Element): SManga = SManga.create().apply { title = element.select("a").attr("title") setUrlWithoutDomain(element.select("a").attr("href")) thumbnail_url = "$cdnUrl/uploads" + element.select("a").attr("href") + "/cover/cover_250x350.jpg" } // Search override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request { val uri = Uri.parse("$baseUrl/search").buildUpon() .appendQueryParameter("query", query) .appendQueryParameter("search_type", "manga") return GET(uri.toString(), headers) } override fun searchMangaSelector() = "h1 + ul a[href*=manga]" override fun searchMangaNextPageSelector(): String? = null override fun searchMangaFromElement(element: Element): SManga = SManga.create().apply { title = element.select("a").text().trim() setUrlWithoutDomain(element.select("a").attr("href")) thumbnail_url = "$cdnUrl/uploads" + element.select("a").attr("href") + "/cover/cover_250x350.jpg" } // Manga details override fun mangaDetailsParse(document: Document): SManga = SManga.create().apply { thumbnail_url = document.select("div.manga-view__header-image").select("img").attr("abs:src") description = document.select("dd.text-justify.text-break").text() author = document.select("a[href*=author]").text() artist = document.select("a[href*=artist]").text() genre = document.select("a[href*=category]").joinToString { it.text() } status = when (document.select("span.badge.bg-success.text-uppercase").text()) { "En Cours" -> SManga.ONGOING "Terminé" -> SManga.COMPLETED else -> SManga.UNKNOWN } } // Chapter list override fun chapterListSelector() = throw Exception("Not used") override fun chapterFromElement(element: Element): SChapter = throw Exception("Not used") override fun chapterListParse(response: Response): List<SChapter> { val document = response.asJsoup() var widgetDocument = document val widgetPageListUrl = Regex("""['"](/arrilot/load-widget.*?)['"]""").find(document.toString())?.groupValues?.get(1) if (widgetPageListUrl != null) { widgetDocument = client.newCall(GET("$baseUrl$widgetPageListUrl", headers)).execute().asJsoup() } return widgetDocument.select("tr[class*=volume-]:has(td)").map { SChapter.create().apply { url = it.select("td.table__chapter").select("a").attr("href") name = it.select("td.table__chapter").select("span").text().trim() chapter_number = it.select("td.table__chapter").select("span").text().substringAfter("Chapitre").replace(Regex("""[,-]"""), ".").trim().toFloatOrNull() ?: -1F date_upload = it.select("td.table__date").firstOrNull()?.text()?.let { parseDate(it) } ?: 0 scanlator = document.select("[itemprop=translator] a").joinToString { it.text().replace(Regex("""[\[\]]"""), "") } } } } private fun parseDate(date: String): Long { return SimpleDateFormat("dd.MM.yyyy", Locale.US).parse(date)?.time ?: 0L } // Pages override fun pageListParse(document: Document): List<Page> { val selectorEncoded1 = "Wkdim" + "gsai" + "mgWQyV2lkMm" + "xrS2img" + "ppZDFoY" + "kd4ZElHaW" + "RsdimgFp6cHVi" + "M1FvVzNOeVl5" + "bimgzlpZG" + "lkWjJsbVhT" + "a3imgNJQzVq" + "YjI1MFlpZFd" + "saWR1WlhJdFi" + "mgpteDFhV1FnTGi" + "mg5KdmlkZHlC" + "a2FYWimgTZiaW" + "imgRtOTBL" + "QzV0ZUMxaim" + "gGRYUnZpZEtT" + "QTZibTki" + "mgwS0imgRwdm" + "JteGlkimgNU" + "xXTm9hV3himgr" + "aWRLU0JwYldjNm" + "JtOTBpZEti" + "mgGdHpp" + "ZGNtTXFQimg" + "V2RwWml" + "kbDBw" val selectorEncoded2 = String(Base64.decode(selectorEncoded1.replace("img", ""), Base64.DEFAULT)) val selectorDecoded = String(Base64.decode(selectorEncoded2.replace("id", ""), Base64.DEFAULT)) val elements = document.select(selectorDecoded) val pages = mutableListOf<Page>() var j = 0 for (i in 0 until elements.count()) { if (elements[i].attr("src").trim().startsWith(cdnUrl)) { pages.add(Page(j, document.location(), elements[i].attr("src").trim())) ++j } } return pages } override fun imageUrlParse(document: Document): String = throw Exception("Not used") override fun imageRequest(page: Page): Request { val imgHeaders = headersBuilder().apply { add("Referer", page.url) }.build() return GET(page.imageUrl!!, imgHeaders) } }
apache-2.0
2bd1b0407cf498db3ecd5dd308fe4dbc
47.345912
167
0.659165
3.892152
false
false
false
false
TCA-Team/TumCampusApp
app/src/main/java/de/tum/in/tumcampusapp/component/tumui/feedback/FeedbackActivity.kt
1
10410
package de.tum.`in`.tumcampusapp.component.tumui.feedback import android.annotation.SuppressLint import android.app.Activity import android.content.Intent import android.content.pm.PackageManager.PERMISSION_GRANTED import android.location.Location import android.net.Uri import android.os.Build import android.os.Bundle import android.view.View import android.widget.ImageView import android.widget.ProgressBar import android.widget.Toast import android.widget.Toast.LENGTH_SHORT import androidx.annotation.RequiresApi import androidx.appcompat.app.AlertDialog import androidx.core.view.isVisible import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.LinearLayoutManager.HORIZONTAL import com.google.android.gms.location.LocationRequest import com.jakewharton.rxbinding3.widget.checkedChanges import com.jakewharton.rxbinding3.widget.textChanges import com.patloew.rxlocation.RxLocation import de.tum.`in`.tumcampusapp.R import de.tum.`in`.tumcampusapp.component.other.generic.activity.BaseActivity import de.tum.`in`.tumcampusapp.component.tumui.feedback.FeedbackPresenter.Companion.PERMISSION_CAMERA import de.tum.`in`.tumcampusapp.component.tumui.feedback.FeedbackPresenter.Companion.PERMISSION_FILES import de.tum.`in`.tumcampusapp.component.tumui.feedback.FeedbackPresenter.Companion.PERMISSION_LOCATION import de.tum.`in`.tumcampusapp.component.tumui.feedback.FeedbackPresenter.Companion.REQUEST_GALLERY import de.tum.`in`.tumcampusapp.component.tumui.feedback.FeedbackPresenter.Companion.REQUEST_TAKE_PHOTO import de.tum.`in`.tumcampusapp.utils.Const import de.tum.`in`.tumcampusapp.utils.Utils import io.reactivex.Observable import kotlinx.android.synthetic.main.activity_feedback.* import java.io.File import javax.inject.Inject class FeedbackActivity : BaseActivity(R.layout.activity_feedback), FeedbackContract.View { private lateinit var thumbnailsAdapter: FeedbackThumbnailsAdapter private var progressDialog: AlertDialog? = null @Inject lateinit var presenter: FeedbackContract.Presenter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val lrzId = Utils.getSetting(this, Const.LRZ_ID, "") injector.feedbackComponent() .lrzId(lrzId) .build() .inject(this) presenter.attachView(this) if (savedInstanceState != null) { presenter.onRestoreInstanceState(savedInstanceState) } initIncludeLocation() initPictureGallery() if (savedInstanceState == null) { presenter.initEmail() } initIncludeEmail() } public override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) presenter.onSaveInstanceState(outState) } private fun initPictureGallery() { imageRecyclerView.layoutManager = LinearLayoutManager(this, HORIZONTAL, false) val imagePaths = presenter.feedback.picturePaths val thumbnailSize = resources.getDimension(R.dimen.thumbnail_size).toInt() thumbnailsAdapter = FeedbackThumbnailsAdapter(imagePaths, { onThumbnailRemoved(it) }, thumbnailSize) imageRecyclerView.adapter = thumbnailsAdapter addImageButton.setOnClickListener { showImageOptionsDialog() } } private fun onThumbnailRemoved(path: String) { val builder = AlertDialog.Builder(this) val view = View.inflate(this, R.layout.picture_dialog, null) val imageView = view.findViewById<ImageView>(R.id.feedback_big_image) imageView.setImageURI(Uri.fromFile(File(path))) builder.setView(view) .setNegativeButton(R.string.cancel, null) .setPositiveButton(R.string.feedback_remove_image) { _, _ -> removeThumbnail(path) } val dialog = builder.create() dialog.window?.setBackgroundDrawableResource(R.drawable.rounded_corners_background) dialog.show() } private fun removeThumbnail(path: String) { presenter.removeImage(path) } private fun showImageOptionsDialog() { val options = arrayOf(getString(R.string.feedback_take_picture), getString(R.string.gallery)) val alertDialog = AlertDialog.Builder(this) .setTitle(R.string.feedback_add_picture) .setItems(options) { _, index -> presenter.onImageOptionSelected(index) } .setNegativeButton(R.string.cancel, null) .create() alertDialog.window?.setBackgroundDrawableResource(R.drawable.rounded_corners_background) alertDialog.show() } override fun getMessage(): Observable<String> = feedbackMessage.textChanges().map { it.toString() } override fun getEmail(): Observable<String> = customEmailInput.textChanges().map { it.toString() } override fun getTopicInput(): Observable<Int> = radioButtonsGroup.checkedChanges() override fun getIncludeEmail(): Observable<Boolean> = includeEmailCheckbox.checkedChanges() override fun getIncludeLocation(): Observable<Boolean> = includeLocationCheckBox.checkedChanges() @SuppressLint("MissingPermission") override fun getLocation(): Observable<Location> = RxLocation(this).location().updates(LocationRequest.create()) override fun setFeedback(message: String) { feedbackMessage.setText(message) } override fun openCamera(intent: Intent) { startActivityForResult(intent, REQUEST_TAKE_PHOTO) } override fun openGallery(intent: Intent) { startActivityForResult(intent, REQUEST_GALLERY) } @RequiresApi(api = Build.VERSION_CODES.M) override fun showPermissionRequestDialog(permission: String, requestCode: Int) { requestPermissions(arrayOf(permission), requestCode) } private fun initIncludeLocation() { includeLocationCheckBox.isChecked = presenter.feedback.includeLocation } private fun initIncludeEmail() { val feedback = presenter.feedback val email = feedback.email includeEmailCheckbox.isChecked = feedback.includeEmail if (presenter.lrzId.isEmpty()) { includeEmailCheckbox.text = getString(R.string.feedback_include_email) customEmailInput.setText(email) } else { includeEmailCheckbox.text = getString(R.string.feedback_include_email_tum_id, email) } } override fun showEmailInput(show: Boolean) { customEmailLayout.isVisible = show } fun onSendClicked(view: View) { presenter.onSendFeedback() } override fun showEmptyMessageError() { feedbackMessage.error = getString(R.string.feedback_empty) } override fun showWarning(message: String) { Toast.makeText(this, message, Toast.LENGTH_LONG).show() } override fun showDialog(title: String, message: String) { val dialog = AlertDialog.Builder(this) .setTitle(title) .setMessage(message) .setPositiveButton(R.string.ok, null) .create() dialog.window?.setBackgroundDrawableResource(R.drawable.rounded_corners_background) dialog.show() } override fun showProgressDialog() { progressDialog = AlertDialog.Builder(this) .setTitle(R.string.feedback_sending) .setView(ProgressBar(this)) .setCancelable(false) .setNeutralButton(R.string.cancel, null) .create() progressDialog?.window?.setBackgroundDrawableResource(R.drawable.rounded_corners_background) progressDialog?.show() } override fun showSendErrorDialog() { progressDialog?.dismiss() val errorDialog = AlertDialog.Builder(this) .setMessage(R.string.feedback_sending_error) .setIcon(R.drawable.ic_error_outline) .setPositiveButton(R.string.try_again) { _, _ -> presenter.feedback } .setNegativeButton(R.string.cancel, null) .create() errorDialog.window?.setBackgroundDrawableResource(R.drawable.rounded_corners_background) errorDialog.show() } override fun onFeedbackSent() { progressDialog?.dismiss() Toast.makeText(this, R.string.feedback_send_success, LENGTH_SHORT).show() finish() } override fun showSendConfirmationDialog() { val alertDialog = AlertDialog.Builder(this) .setMessage(R.string.send_feedback_question) .setPositiveButton(R.string.send) { _, _ -> presenter.onConfirmSend() } .setNegativeButton(R.string.cancel, null) .create() alertDialog.window?.setBackgroundDrawableResource(R.drawable.rounded_corners_background) alertDialog.show() } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (resultCode != Activity.RESULT_OK) { return } when (requestCode) { REQUEST_TAKE_PHOTO -> presenter.onNewImageTaken() REQUEST_GALLERY -> { val filePath = data?.data presenter.onNewImageSelected(filePath) } } } override fun onImageAdded(path: String) { thumbnailsAdapter.addImage(path) } override fun onImageRemoved(position: Int) { thumbnailsAdapter.removeImage(position) } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<String>, grantResults: IntArray ) { if (grantResults.isEmpty()) { return } val isGranted = grantResults[0] == PERMISSION_GRANTED when (requestCode) { PERMISSION_LOCATION -> { includeLocationCheckBox.isChecked = isGranted if (isGranted) { presenter.listenForLocation() } } PERMISSION_CAMERA -> { if (isGranted) { presenter.takePicture() } } PERMISSION_FILES -> { if (isGranted) { presenter.openGallery() } } } } override fun onDestroy() { presenter.detachView() super.onDestroy() } }
gpl-3.0
2df2df4d501929202d5482c495e4682a
35.145833
116
0.673391
4.859944
false
false
false
false
ligee/kotlin-jupyter
src/main/kotlin/org/jetbrains/kotlinx/jupyter/repl/ContextUpdater.kt
1
3189
package org.jetbrains.kotlinx.jupyter.repl import jupyter.kotlin.KotlinContext import jupyter.kotlin.KotlinFunctionInfo import jupyter.kotlin.KotlinVariableInfo import org.slf4j.LoggerFactory import java.lang.reflect.Field import java.util.HashSet import kotlin.reflect.jvm.kotlinFunction import kotlin.reflect.jvm.kotlinProperty import kotlin.script.experimental.jvm.BasicJvmReplEvaluator import kotlin.script.experimental.jvm.KJvmEvaluatedSnippet import kotlin.script.experimental.util.LinkedSnippet /** * ContextUpdater updates current user-defined functions and variables * to use in completion and KotlinContext. */ class ContextUpdater(val context: KotlinContext, private val evaluator: BasicJvmReplEvaluator) { private var lastProcessedSnippet: LinkedSnippet<KJvmEvaluatedSnippet>? = null fun update() { try { var lastSnippet = evaluator.lastEvaluatedSnippet val newSnippets = mutableListOf<Any>() while (lastSnippet != lastProcessedSnippet && lastSnippet != null) { val line = lastSnippet.get().result.scriptInstance if (line != null) { newSnippets.add(line) } lastSnippet = lastSnippet.previous } newSnippets.reverse() refreshVariables(newSnippets) refreshMethods(newSnippets) lastProcessedSnippet = evaluator.lastEvaluatedSnippet } catch (e: ReflectiveOperationException) { logger.error("Exception updating current variables", e) } catch (e: NullPointerException) { logger.error("Exception updating current variables", e) } } private fun refreshMethods(lines: List<Any>) { for (line in lines) { val methods = line.javaClass.methods for (method in methods) { if (objectMethods.contains(method) || method.name == "main") { continue } val function = method.kotlinFunction ?: continue context.functions[function.name] = KotlinFunctionInfo(function, line) } } } @Throws(ReflectiveOperationException::class) private fun refreshVariables(lines: List<Any>) { for (line in lines) { val fields = line.javaClass.declaredFields findVariables(fields, line) } } @Throws(IllegalAccessException::class) private fun findVariables(fields: Array<Field>, o: Any) { for (field in fields) { val fieldName = field.name if (fieldName.contains("$\$implicitReceiver") || fieldName.contains("script$")) { continue } field.isAccessible = true val value = field.get(o) val descriptor = field.kotlinProperty if (descriptor != null) { context.vars[fieldName] = KotlinVariableInfo(value, descriptor, o) } } } companion object { private val logger = LoggerFactory.getLogger(ContextUpdater::class.java) private val objectMethods = HashSet(listOf(*Any::class.java.methods)) } }
apache-2.0
610ef48be2a5f61cca396fd10a1888c1
35.655172
96
0.638131
4.921296
false
false
false
false
WonderBeat/vasilich
src/main/kotlin/com/vasilich/commands/bootstrap/ReactiveCommandInitializer.kt
1
1261
package com.vasilich.commands.bootstrap import reactor.core.Observable import javax.annotation.PostConstruct import reactor.event.selector.Selectors import reactor.event.Event import reactor.function.Consumer import org.springframework.core.Ordered import org.slf4j.LoggerFactory import com.vasilich.commands.api.Command import com.vasilich.connectors.xmpp.Topics /** * Grabs all available commands, sorts them by priority and listens to events * On event, passes it through the chain of commands, looking for the first one, that can process it */ public class ReactiveCommandInitializer (private val reactor: Observable, private val command: Command, private val topics: Topics = Topics()) { val logger = LoggerFactory.getLogger(this.javaClass)!!; PostConstruct private fun makeReactive() { reactor.on(Selectors.`$`(topics.receive), Consumer<Event<String>> { val msg = it!!.getData()!! val response = command execute msg if(response != null) { logger.debug("Chat: ${msg} -> ${response}") reactor.notify(topics.send, Event.wrap(response)) } }) } }
gpl-2.0
c49cf6d10ff374424ad3eda63ee5472b
36.088235
100
0.65345
4.740602
false
false
false
false
firebase/snippets-android
functions/app/src/main/java/devrel/firebase/google/com/functions/kotlin/MainActivity.kt
1
4040
package devrel.firebase.google.com.functions.kotlin import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.google.android.gms.tasks.Task import com.google.firebase.functions.FirebaseFunctions import com.google.firebase.functions.FirebaseFunctionsException import com.google.firebase.functions.ktx.functions import com.google.firebase.ktx.Firebase class MainActivity : AppCompatActivity() { // [START define_functions_instance] private lateinit var functions: FirebaseFunctions // [END define_functions_instance] override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // [START initialize_functions_instance] functions = Firebase.functions // [END initialize_functions_instance] } fun emulatorSettings() { // [START functions_emulator_connect] // 10.0.2.2 is the special IP address to connect to the 'localhost' of // the host computer from an Android emulator. val functions = Firebase.functions functions.useEmulator("10.0.2.2", 5001) // [END functions_emulator_connect] } // [START function_add_numbers] private fun addNumbers(a: Int, b: Int): Task<Int> { // Create the arguments to the callable function, which are two integers val data = hashMapOf( "firstNumber" to a, "secondNumber" to b ) // Call the function and extract the operation from the result return functions .getHttpsCallable("addNumbers") .call(data) .continueWith { task -> // This continuation runs on either success or failure, but if the task // has failed then task.result will throw an Exception which will be // propagated down. val result = task.result?.data as Map<String, Any> result["operationResult"] as Int } } // [END function_add_numbers] // [START function_add_message] private fun addMessage(text: String): Task<String> { // Create the arguments to the callable function. val data = hashMapOf( "text" to text, "push" to true ) return functions .getHttpsCallable("addMessage") .call(data) .continueWith { task -> // This continuation runs on either success or failure, but if the task // has failed then result will throw an Exception which will be // propagated down. val result = task.result?.data as String result } } // [END function_add_message] private fun callAddNumbers(firstNumber: Int, secondNumber: Int) { // [START call_add_numbers] addNumbers(firstNumber, secondNumber) .addOnCompleteListener { task -> if (!task.isSuccessful) { val e = task.exception if (e is FirebaseFunctionsException) { // Function error code, will be INTERNAL if the failure // was not handled properly in the function call. val code = e.code // Arbitrary error details passed back from the function, // usually a Map<String, Any>. val details = e.details } } } // [END call_add_numbers] } private fun callAddMessage(inputMessage: String){ // [START call_add_message] addMessage(inputMessage) .addOnCompleteListener { task -> if (!task.isSuccessful) { val e = task.exception if (e is FirebaseFunctionsException) { val code = e.code val details = e.details } } } // [END call_add_message] } }
apache-2.0
2616d1201c33ebf5ddee706d83c2c94a
35.396396
87
0.573762
5.031133
false
false
false
false
elect86/jAssimp
src/main/kotlin/assimp/types.kt
2
1103
package assimp /** * Created by elect on 16/11/2016. */ /** Maximum dimension for strings, ASSIMP strings are zero terminated. */ const val MAXLEN = 1024 /** Standard return type for some library functions. * Rarely used, and if, mostly in the C API. */ enum class AiReturn(val i: Int) { /** Indicates that a function was successful */ SUCCESS(0x0), /** Indicates that a function failed */ FAILURE(-0x1), /** Indicates that not enough memory was available to perform the requested operation */ OUTOFMEMORY(-0x3) } class AiMemoryInfo { /** Storage allocated for texture data */ var textures = 0 /** Storage allocated for material data */ var materials = 0 /** Storage allocated for mesh data */ var meshes = 0 /** Storage allocated for node data */ var nodes = 0 /** Storage allocated for animation data */ var animations = 0 /** Storage allocated for camera data */ var cameras = 0 /** Storage allocated for light data */ var lights = 0 /** Total storage allocated for the full import. */ var total = 0 }
mit
74f798f7c22879db8e10c3e5f28cc016
27.282051
92
0.651859
4.308594
false
false
false
false
WangDaYeeeeee/GeometricWeather
app/src/main/java/wangdaye/com/geometricweather/common/basic/models/options/unit/DistanceUnit.kt
1
2485
package wangdaye.com.geometricweather.common.basic.models.options.unit import android.content.Context import wangdaye.com.geometricweather.R import wangdaye.com.geometricweather.common.basic.models.options._basic.UnitEnum import wangdaye.com.geometricweather.common.basic.models.options._basic.Utils import wangdaye.com.geometricweather.common.utils.DisplayUtils // actual distance = distance(km) * factor. enum class DistanceUnit( override val id: String, override val unitFactor: Float ): UnitEnum<Float> { KM("km", 1f), M("m", 1000f), MI("mi", 0.6213f), NMI("nmi", 0.5399f), FT("ft", 3280.8398f); companion object { @JvmStatic fun getInstance( value: String ) = when (value) { "m" -> M "mi" -> MI "nmi" -> NMI "ft" -> FT else -> KM } } override val valueArrayId = R.array.distance_unit_values override val nameArrayId = R.array.distance_units override val voiceArrayId = R.array.distance_unit_voices override fun getName(context: Context) = Utils.getName(context, this) override fun getVoice(context: Context) = Utils.getVoice(context, this) override fun getValueWithoutUnit(valueInDefaultUnit: Float) = valueInDefaultUnit * unitFactor override fun getValueInDefaultUnit(valueInCurrentUnit: Float) = valueInCurrentUnit / unitFactor override fun getValueTextWithoutUnit( valueInDefaultUnit: Float ) = Utils.getValueTextWithoutUnit(this, valueInDefaultUnit, 2)!! override fun getValueText( context: Context, valueInDefaultUnit: Float ) = getValueText(context, valueInDefaultUnit, DisplayUtils.isRtl(context)) override fun getValueText( context: Context, valueInDefaultUnit: Float, rtl: Boolean ) = Utils.getValueText( context = context, enum = this, valueInDefaultUnit = valueInDefaultUnit, decimalNumber = 2, rtl = rtl ) override fun getValueVoice( context: Context, valueInDefaultUnit: Float ) = getValueVoice(context, valueInDefaultUnit, DisplayUtils.isRtl(context)) override fun getValueVoice( context: Context, valueInDefaultUnit: Float, rtl: Boolean ) = Utils.getVoiceText( context = context, enum = this, valueInDefaultUnit = valueInDefaultUnit, decimalNumber = 2, rtl = rtl ) }
lgpl-3.0
cf687d355f66070845c5bbe571855997
28.595238
99
0.662777
4.155518
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/view/video_player/model/VideoPlayerMediaData.kt
2
1257
package org.stepik.android.view.video_player.model import android.os.Parcel import android.os.Parcelable import org.stepik.android.model.Video data class VideoPlayerMediaData( val thumbnail: String? = null, val title: String, val description: String? = null, val cachedVideo: Video? = null, val externalVideo: Video? = null ) : Parcelable { override fun writeToParcel(parcel: Parcel, flags: Int) { parcel.writeString(thumbnail) parcel.writeString(title) parcel.writeString(description) parcel.writeParcelable(cachedVideo, flags) parcel.writeParcelable(externalVideo, flags) } override fun describeContents(): Int = 0 companion object CREATOR : Parcelable.Creator<VideoPlayerMediaData> { override fun createFromParcel(parcel: Parcel): VideoPlayerMediaData = VideoPlayerMediaData( parcel.readString(), parcel.readString()!!, parcel.readString(), parcel.readParcelable(Video::class.java.classLoader), parcel.readParcelable(Video::class.java.classLoader) ) override fun newArray(size: Int): Array<VideoPlayerMediaData?> = arrayOfNulls(size) } }
apache-2.0
52e16a11c68346e53bd7916afcafd87b
33
77
0.666667
4.853282
false
true
false
false
just6979/ScoreModel
ScoreModel/src/main/kotlin/net/justinwhite/scoremodel/phase10/Phase10Player.kt
2
3164
/* * Copyright (c) 2015 Justin White <[email protected]> * 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. */ package net.justinwhite.scoremodel.phase10 import net.justinwhite.scoremodel.Player import net.justinwhite.scoremodel.phase10.Phase10Game.* class Phase10Player(_name: String, _phases: Array<Phase>) : Player(_name) { val phases: Array<Phase> = Phase10Game.getPhasePreset() var currentPhase: Int = 0 private set @JvmOverloads constructor(_name: String = "Player X", phasePreset: PhaseSet = PhaseSet.ALL) : this(_name, Companion.getPhasePreset(phasePreset)) init { setActivePhases(_phases) } override fun toString(): String { return "%s; Phase %d".format(super.toString(), currentPhase) } fun setActivePhases(_phases: Array<Phase>) { System.arraycopy(_phases, 0, phases, 0, _phases.size) } fun setActivePhases(_phases: Array<Boolean>) { for (i in 0..Phase10Game.MAX_PHASE) { if (_phases[i]) { phases[i] = Phase.ACTIVE } else { phases[i] = Phase.INACTIVE } } } fun resetCurrentPhase() { currentPhase = 0 } fun completeCurrentPhase() { if (phases[currentPhase] === Phase.ACTIVE) { phases[currentPhase] = Phase.COMPLETED } do { currentPhase++ if (currentPhase > Phase10Game.MAX_PHASE) { currentPhase = Phase10Game.MAX_PHASE break } } while (phases[currentPhase] !== Phase.ACTIVE) } fun addScore(_score: Int?) { score += _score!! } }
bsd-3-clause
915e7905806bec14da4609fac039c6f2
35.367816
148
0.674463
4.224299
false
false
false
false
jiaminglu/kotlin-native
backend.native/tests/external/codegen/box/properties/kt10715.kt
5
262
fun box(): String { var a = Base() val count = a.count if (count != 0) return "fail 1: $count" val count2 = a.count if (count2 != 1) return "fail 2: $count2" return "OK" } class Base { var count: Int = 0 get() = field++ }
apache-2.0
a776b37b428b27475854e716772235df
14.470588
45
0.519084
3.046512
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepic/droid/util/NotificationChannelInitializer.kt
2
1679
package org.stepic.droid.util import android.app.NotificationChannel import android.app.NotificationManager import android.content.Context import android.os.Build import androidx.annotation.RequiresApi import org.stepic.droid.R import org.stepic.droid.notifications.model.StepikNotificationChannel object NotificationChannelInitializer { fun initNotificationChannels(context: Context) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { //channels were introduced only in O. Before we had used in-app channels return } val stepikNotificationChannels = StepikNotificationChannel.values() val androidChannels = ArrayList<NotificationChannel>(stepikNotificationChannels.size) stepikNotificationChannels.forEach { androidChannels.add(initChannel(context, it)) } val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.createNotificationChannels(androidChannels) } @RequiresApi(Build.VERSION_CODES.O) private fun initChannel( context: Context, stepikChannel: StepikNotificationChannel ): NotificationChannel { val channelName = context.getString(stepikChannel.visibleChannelNameRes) val channel = NotificationChannel(stepikChannel.channelId, channelName, stepikChannel.importance) channel.description = context.getString(stepikChannel.visibleChannelDescriptionRes) channel.enableLights(true) channel.enableVibration(true) channel.lightColor = context.resolveColorAttribute(R.attr.colorError) return channel } }
apache-2.0
1e604231490888834a06eb371dc8e6d8
38.97619
111
0.753425
5.198142
false
false
false
false
NerdNumber9/TachiyomiEH
app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsSourcesController.kt
1
4539
package eu.kanade.tachiyomi.ui.setting import android.graphics.drawable.Drawable import android.support.v7.preference.PreferenceGroup import android.support.v7.preference.PreferenceScreen import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.preference.getOrDefault import eu.kanade.tachiyomi.source.SourceManager import eu.kanade.tachiyomi.source.online.HttpSource import eu.kanade.tachiyomi.source.online.LoginSource import eu.kanade.tachiyomi.util.LocaleHelper import eu.kanade.tachiyomi.widget.preference.LoginCheckBoxPreference import eu.kanade.tachiyomi.widget.preference.SourceLoginDialog import eu.kanade.tachiyomi.widget.preference.SwitchPreferenceCategory import exh.source.BlacklistedSources import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get import java.util.* class SettingsSourcesController : SettingsController(), SourceLoginDialog.Listener { private val onlineSources by lazy { Injekt.get<SourceManager>().getOnlineSources().filter { it.id !in BlacklistedSources.HIDDEN_SOURCES } } override fun setupPreferenceScreen(screen: PreferenceScreen) = with(screen) { titleRes = R.string.pref_category_sources // Get the list of active language codes. val activeLangsCodes = preferences.enabledLanguages().getOrDefault() // Get a map of sources grouped by language. val sourcesByLang = onlineSources.groupByTo(TreeMap(), { it.lang }) // Order first by active languages, then inactive ones val orderedLangs = sourcesByLang.keys.filter { it in activeLangsCodes } + sourcesByLang.keys.filterNot { it in activeLangsCodes } orderedLangs.forEach { lang -> val sources = sourcesByLang[lang].orEmpty().sortedBy { it.name } // Create a preference group and set initial state and change listener SwitchPreferenceCategory(context).apply { preferenceScreen.addPreference(this) title = LocaleHelper.getDisplayName(lang, context) isPersistent = false if (lang in activeLangsCodes) { setChecked(true) addLanguageSources(this, sources) } onChange { newValue -> val checked = newValue as Boolean val current = preferences.enabledLanguages().getOrDefault() if (!checked) { preferences.enabledLanguages().set(current - lang) removeAll() } else { preferences.enabledLanguages().set(current + lang) addLanguageSources(this, sources) } true } } } } override fun setDivider(divider: Drawable?) { super.setDivider(null) } /** * Adds the source list for the given group (language). * * @param group the language category. */ private fun addLanguageSources(group: PreferenceGroup, sources: List<HttpSource>) { val hiddenCatalogues = preferences.hiddenCatalogues().getOrDefault() sources.forEach { source -> val sourcePreference = LoginCheckBoxPreference(group.context, source).apply { val id = source.id.toString() title = source.name key = getSourceKey(source.id) isPersistent = false isChecked = id !in hiddenCatalogues onChange { newValue -> val checked = newValue as Boolean val current = preferences.hiddenCatalogues().getOrDefault() preferences.hiddenCatalogues().set(if (checked) current - id else current + id) true } setOnLoginClickListener { val dialog = SourceLoginDialog(source) dialog.targetController = this@SettingsSourcesController dialog.showDialog(router) } } group.addPreference(sourcePreference) } } override fun loginDialogClosed(source: LoginSource) { val pref = findPreference(getSourceKey(source.id)) as? LoginCheckBoxPreference pref?.notifyChanged() } private fun getSourceKey(sourceId: Long): String { return "source_$sourceId" } }
apache-2.0
569e9e43f2dafe4cdc13ca75a031a8e2
35.910569
89
0.615995
5.462094
false
false
false
false
exponentjs/exponent
packages/expo-dev-menu/android/src/main/java/expo/modules/devmenu/DevMenuDefaultSettings.kt
2
1294
package expo.modules.devmenu import com.facebook.react.bridge.Arguments import com.facebook.react.bridge.WritableMap import expo.interfaces.devmenu.DevMenuSettingsInterface open class DevMenuDefaultSettings : DevMenuSettingsInterface { private fun methodUnavailable() { throw NoSuchMethodError("You cannot change the default settings. Export `DevMenuSettings` module if you want to change the settings.") } override var motionGestureEnabled: Boolean get() = true set(_) = methodUnavailable() override var touchGestureEnabled: Boolean get() = true set(_) = methodUnavailable() override var keyCommandsEnabled: Boolean get() = true set(_) = methodUnavailable() override var showsAtLaunch: Boolean get() = false set(_) = methodUnavailable() override var isOnboardingFinished: Boolean get() = true set(_) = methodUnavailable() override fun serialize(): WritableMap = Arguments .createMap() .apply { putBoolean("motionGestureEnabled", motionGestureEnabled) putBoolean("touchGestureEnabled", touchGestureEnabled) putBoolean("keyCommandsEnabled", keyCommandsEnabled) putBoolean("showsAtLaunch", showsAtLaunch) putBoolean("isOnboardingFinished", isOnboardingFinished) } }
bsd-3-clause
a916103b52dec160291b65baf2f1f492
29.809524
138
0.729521
5.054688
false
false
false
false
abigpotostew/easypolitics
ui/src/main/kotlin/bz/stew/bracken/ui/pages/browse/view/mixins/TwitterLink.kt
1
681
package bz.stew.bracken.ui.pages.browse.view.mixins import bz.stew.bracken.ui.extension.html.LinkTarget import bz.stew.bracken.ui.common.view.SubTemplate import bz.stewart.bracken.shared.data.person.Legislator import kotlinx.html.FlowContent import kotlinx.html.a class TwitterLink(private val legislator: Legislator, private val target: LinkTarget = LinkTarget.BLANK) : SubTemplate { override fun renderIn(root: FlowContent) { val twitter = legislator.getTwitter() val linkTarget = target root.a { +"@" +twitter href = "http://www.twitter.com/$twitter" target = linkTarget.htmlValue() } } }
apache-2.0
f4dab921aa21a8a0d481e2d023ce8caa
33.1
120
0.688693
3.913793
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/base/scripting/src/org/jetbrains/kotlin/idea/core/script/configuration/CompositeScriptConfigurationManager.kt
2
8118
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.core.script.configuration import com.intellij.codeInsight.daemon.OutsidersPsiFileSupport import com.intellij.ide.scratch.ScratchUtil import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.ProjectJdkTable import com.intellij.openapi.projectRoots.ProjectJdkTable.JDK_TABLE_TOPIC import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.search.GlobalSearchScope import org.jetbrains.kotlin.idea.core.KotlinPluginDisposable import org.jetbrains.kotlin.idea.core.script.ScriptConfigurationManager import org.jetbrains.kotlin.idea.core.script.ScriptDependenciesModificationTracker import org.jetbrains.kotlin.idea.core.script.configuration.listener.ScriptChangesNotifier import org.jetbrains.kotlin.idea.core.script.configuration.utils.getKtFile import org.jetbrains.kotlin.idea.core.script.ucache.ScriptClassRootsBuilder import org.jetbrains.kotlin.idea.core.script.ucache.ScriptClassRootsCache import org.jetbrains.kotlin.idea.core.script.ucache.ScriptClassRootsUpdater import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.scripting.definitions.ScriptDefinition import org.jetbrains.kotlin.scripting.resolve.ScriptCompilationConfigurationWrapper /** * The [CompositeScriptConfigurationManager] will provide redirection of [ScriptConfigurationManager] calls to the * custom [ScriptingSupport] or [DefaultScriptingSupport] if that script lack of custom [ScriptingSupport]. * * The [ScriptConfigurationManager] is implemented by caching all scripts using the [ScriptClassRootsCache]. * The [ScriptClassRootsCache] is always available and never blacked by the writer, as all writes occurs * using the copy-on-write strategy. * * This cache is loaded on start and will be updating asynchronously using the [updater]. * Sync updates still may be occurred from the [DefaultScriptingSupport]. * * We are also watching all script documents: * [notifier] will call first applicable [ScriptChangesNotifier.listeners] when editor is activated or document changed. * Listener should do something to invalidate configuration and schedule reloading. */ class CompositeScriptConfigurationManager(val project: Project) : ScriptConfigurationManager { private val notifier = ScriptChangesNotifier(project) private val classpathRoots: ScriptClassRootsCache get() = updater.classpathRoots private val plugins get() = ScriptingSupport.EPN.getPoint(project).extensionList val default = DefaultScriptingSupport(this) val updater = object : ScriptClassRootsUpdater(project, this) { override fun gatherRoots(builder: ScriptClassRootsBuilder) { default.collectConfigurations(builder) plugins.forEach { it.collectConfigurations(builder) } } override fun afterUpdate() { plugins.forEach { it.afterUpdate() } } } override fun loadPlugins() { plugins } fun updateScriptDependenciesIfNeeded(file: VirtualFile) { notifier.updateScriptDependenciesIfNeeded(file) } fun tryGetScriptDefinitionFast(locationId: String): ScriptDefinition? { return classpathRoots.getLightScriptInfo(locationId)?.definition } private fun getOrLoadConfiguration( virtualFile: VirtualFile, preloadedKtFile: KtFile? = null ): ScriptCompilationConfigurationWrapper? { val scriptConfiguration = classpathRoots.getScriptConfiguration(virtualFile) if (scriptConfiguration != null) return scriptConfiguration // check that this script should be loaded later in special way (e.g. gradle project import) // (and not for syntactic diff files) if (!OutsidersPsiFileSupport.isOutsiderFile(virtualFile)) { val plugin = plugins.firstOrNull { it.isApplicable(virtualFile) } if (plugin != null) { return plugin.getConfigurationImmediately(virtualFile)?.also { updater.addConfiguration(virtualFile, it) } } } return default.getOrLoadConfiguration(virtualFile, preloadedKtFile) } override fun getConfiguration(file: KtFile) = getOrLoadConfiguration(file.originalFile.virtualFile, file) override fun hasConfiguration(file: KtFile): Boolean = classpathRoots.contains(file.originalFile.virtualFile) override fun isConfigurationLoadingInProgress(file: KtFile): Boolean = plugins.firstOrNull { it.isApplicable(file.originalFile.virtualFile) }?.isConfigurationLoadingInProgress(file) ?: default.isConfigurationLoadingInProgress(file) fun getLightScriptInfo(file: String): ScriptClassRootsCache.LightScriptInfo? = classpathRoots.getLightScriptInfo(file) override fun updateScriptDefinitionReferences() { ScriptDependenciesModificationTracker.getInstance(project).incModificationCount() default.updateScriptDefinitionsReferences() if (classpathRoots.customDefinitionsUsed) { updater.invalidateAndCommit() } } init { val connection = project.messageBus.connect(KotlinPluginDisposable.getInstance(project)) connection.subscribe(JDK_TABLE_TOPIC, object : ProjectJdkTable.Listener { override fun jdkAdded(jdk: Sdk) = updater.checkInvalidSdks() override fun jdkNameChanged(jdk: Sdk, previousName: String) = updater.checkInvalidSdks() override fun jdkRemoved(jdk: Sdk) = updater.checkInvalidSdks(remove = jdk) }) } /** * Returns script classpath roots * Loads script configuration if classpath roots don't contain [file] yet */ private fun getActualClasspathRoots(file: VirtualFile): ScriptClassRootsCache { try { // we should run default loader if this [file] is not cached in [classpathRoots] // and it is not supported by any of [plugins] // getOrLoadConfiguration will do this // (despite that it's result becomes unused, it still may populate [classpathRoots]) getOrLoadConfiguration(file, null) } catch (cancelled: ProcessCanceledException) { // read actions may be cancelled if we are called by impatient reader } return this.classpathRoots } override fun getScriptSdk(file: VirtualFile): Sdk? = if (ScratchUtil.isScratch(file)) { ProjectRootManager.getInstance(project).projectSdk } else { getActualClasspathRoots(file).getScriptSdk(file) } override fun getFirstScriptsSdk(): Sdk? = classpathRoots.firstScriptSdk override fun getScriptDependenciesClassFilesScope(file: VirtualFile): GlobalSearchScope = classpathRoots.getScriptDependenciesClassFilesScope(file) override fun getAllScriptsDependenciesClassFilesScope(): GlobalSearchScope = classpathRoots.allDependenciesClassFilesScope override fun getAllScriptDependenciesSourcesScope(): GlobalSearchScope = classpathRoots.allDependenciesSourcesScope override fun getAllScriptsDependenciesClassFiles(): Collection<VirtualFile> = classpathRoots.allDependenciesClassFiles override fun getAllScriptDependenciesSources(): Collection<VirtualFile> = classpathRoots.allDependenciesSources /////////////////// // Adapters for deprecated API // @Deprecated("Use getScriptClasspath(KtFile) instead") override fun getScriptClasspath(file: VirtualFile): List<VirtualFile> { val ktFile = project.getKtFile(file) ?: return emptyList() return getScriptClasspath(ktFile) } override fun getScriptClasspath(file: KtFile): List<VirtualFile> = ScriptConfigurationManager.toVfsRoots(getConfiguration(file)?.dependenciesClassPath.orEmpty()) }
apache-2.0
505239fc8ce54121e48c286effe13210
42.881081
120
0.745134
5.376159
false
true
false
false
filpgame/kotlinx-examples
app/src/main/java/com/filpgame/kotlinx/ui/list/User.kt
1
666
package com.filpgame.kotlinx.ui.list import android.R.drawable.* import java.security.SecureRandom fun <T> Array<T>.random(): T = this[SecureRandom().nextInt(this.count())] val pictures = arrayOf(ic_media_play, ic_delete, ic_lock_lock, ic_dialog_map, ic_lock_power_off, ic_menu_zoom, ic_input_add) val names = arrayOf("Felipe", "Cicrano", "Pedro", "Thiago", "John", "Fulano", "Beltrano") val occupations = arrayOf("Developer", "Engineer", "QA", "Manager", "Driver", "Seller", "Customer Relationship") data class User( val name: String = names.random(), val occupation: String = occupations.random(), val picture: Int = pictures.random() )
mit
9329c416702c934ffa7f8f5137659d81
40.6875
124
0.690691
3.217391
false
false
false
false
Turbo87/intellij-rust
src/main/kotlin/org/rust/lang/core/psi/impl/mixin/RustBlockImplMixin.kt
1
1259
package org.rust.lang.core.psi.impl.mixin import com.intellij.lang.ASTNode import com.intellij.psi.util.PsiTreeUtil import org.rust.lang.core.psi.* import org.rust.lang.core.psi.impl.RustCompositeElementImpl import org.rust.lang.core.psi.util.isAfter abstract class RustBlockImplMixin(node: ASTNode) : RustCompositeElementImpl(node) , RustBlock { override val declarations: Collection<RustDeclaringElement> get() = stmtList.filterIsInstance<RustDeclStmt>() .map { it.letDecl } .filterNotNull() } /** * Let declarations visible at the `element` according to Rust scoping rules. * More recent declarations come first. * * Example: * * ``` * { * let x = 92; // visible * let x = x; // not visible * ^ element * let x = 62; // not visible * } * ``` */ fun RustBlock.letDeclarationsVisibleAt(element: RustCompositeElement): Sequence<RustLetDecl> = stmtList.asReversed().asSequence() .filterIsInstance<RustDeclStmt>() .mapNotNull { it.letDecl } .dropWhile { it.isAfter(element) } // Drops at most one element .dropWhile { PsiTreeUtil.isAncestor(it, element, true) }
mit
9270426e8ceb84f437ab00f580bdd968
31.282051
94
0.635425
4.009554
false
false
false
false
RonnChyran/Face-of-Sidonia
Sidonia/SidoniaWatchface/src/main/java/moe/chyyran/sidonia/drawables/StatusDrawable.kt
1
6848
package moe.chyyran.sidonia.drawables import android.graphics.* import com.ustwo.clockwise.common.WatchFaceTime import com.ustwo.clockwise.wearable.WatchFace private class TextOffsets(val leftTextOffset: PointF, val rightTextOffset: PointF, val halfHeightTextOffset: PointF) class StatusDrawable(watch: WatchFace) : SidoniaDrawable(watch) { private var mLeftTextPaint: Paint = createWeekDayPaint() private var mRightTextPaint: Paint = createDatePaint() private var mHalfHeightTextPaint: Paint = createHalfHeightDisplayPaint() private fun getTextOffsets(kanji: String, time: String): TextOffsets { val leftTextMetrics = mLeftTextPaint.fontMetrics // This text is to be drawn in cell 0, 1. val leftCellOffset = this.getCellOffset(0, 1) // Calculate the difference on each side between the cell walls and the // width of the text, in order to properly center the text horizontally. val leftTextWidthDiff = (hudCellWidth - mLeftTextPaint.measureText(kanji)) / 2f // Calculate the difference on each side between the cell walls and the height of // the text, in order to properly center the text vertically. val leftTextHeightDiff = (hudCellWidth - (leftTextMetrics.ascent + leftTextMetrics.descent)) / 2f // The offset is simply the cell offset + the difference between the cell walls // and the dimensions of the text. val leftOffset = PointF(leftCellOffset.x + leftTextWidthDiff, leftCellOffset.y + leftTextHeightDiff) val rightCellOffset = this.getCellOffset(0, 2) // actually 2.5 ish, but we will ignore the x. val rightTextMetrics = mRightTextPaint.fontMetrics val rightTextWidth = mRightTextPaint.measureText(time) / 2f val rightTextHeightDiff = (hudCellWidth - (rightTextMetrics.ascent + rightTextMetrics.descent)) / 2f val rightLeftOffset = edgeOffset + desiredMinimumWidth / 1.60f - rightTextWidth // Here the x offset has been manually specified, but the top offset is the same principle val rightOffset = PointF(rightLeftOffset, rightCellOffset.y + rightTextHeightDiff) // Half height text is it's own special case. val halfHeightTextWidth = mHalfHeightTextPaint.measureText("T") / 2f val halfHeightTextHeight = (rightTextMetrics.ascent + rightTextMetrics.descent) / 2f val halfHeightTopOffset = edgeOffset + hudCellWidth / 9f val halfHeightLeftOffset = edgeOffset + desiredMinimumWidth / 2.25f - halfHeightTextWidth val halfHeightOffset = PointF(halfHeightLeftOffset, halfHeightTopOffset - halfHeightTextHeight) return TextOffsets(leftOffset, rightOffset, halfHeightOffset) } private fun createHalfHeightDisplayPaint(): Paint { val centerTextSize = desiredMinimumWidth / 12.0f val halfHeightPaint = Paint() halfHeightPaint.typeface = this.latinFont halfHeightPaint.color = this.backgroundColor halfHeightPaint.textSize = centerTextSize halfHeightPaint.isAntiAlias = true return halfHeightPaint } private fun createWeekDayPaint() : Paint { val textSize = desiredMinimumWidth / 5.5f val paint = Paint(this.hudPaint) paint.typeface = this.kanjiFont paint.textSize = textSize return paint } private fun createDatePaint() : Paint { val textSize = desiredMinimumWidth / 5.5f val paint = Paint() paint.typeface = this.latinFont paint.color = this.backgroundColor paint.textSize = textSize paint.isAntiAlias = true return paint } fun drawTime(canvas: Canvas?, time: WatchFaceTime) { val hour12 = if (time.hour > 11) time.hour - 12 else time.hour val text = (hour12 % 10).toString() + if (time.minute > 9) time.minute.toString() else "0" + time.minute.toString() val textOffsets = getTextOffsets(getWeekDayKanji(time.weekDay), text) canvas?.drawRect(hudCellWidth * 2f + edgeOffset, edgeOffset, hudCellWidth * 4f + edgeOffset, hudCellWidth * 1f + edgeOffset, this.hudPaint ) canvas?.drawText("T", textOffsets.halfHeightTextOffset.x, textOffsets.halfHeightTextOffset.y, mHalfHeightTextPaint) if (time.hour > 11) canvas?.drawText("P", textOffsets.halfHeightTextOffset.x, textOffsets.halfHeightTextOffset.y + (edgeOffset + hudCellWidth / 3f), mHalfHeightTextPaint ) else canvas?.drawText("A", textOffsets.halfHeightTextOffset.x, textOffsets.halfHeightTextOffset.y + (edgeOffset + hudCellWidth / 3f), mHalfHeightTextPaint ) canvas?.drawText(text, textOffsets.rightTextOffset.x, textOffsets.rightTextOffset.y, mRightTextPaint) } fun drawDate(canvas: Canvas?, time: WatchFaceTime) { // Months are zero-indexed, so we have to add one in order to correct for it. val text = ((time.month % 10) + 1).toString() + (if (time.monthDay > 9) time.monthDay.toString() else "0" + time.monthDay.toString()) val textOffsets = getTextOffsets(getWeekDayKanji(time.weekDay), text) val startOffset = this.getCellOffset(0, 2) val endOffset = this.getCellOffset(1, 4) canvas?.drawRect(startOffset.x, startOffset.y, endOffset.x, endOffset.y, this.hudPaint ) canvas?.drawText("T", textOffsets.halfHeightTextOffset.x, textOffsets.halfHeightTextOffset.y, mHalfHeightTextPaint) canvas?.drawText("S", textOffsets.halfHeightTextOffset.x, textOffsets.halfHeightTextOffset.y + (edgeOffset + hudCellWidth / 3f), mHalfHeightTextPaint ) canvas?.drawText(text, textOffsets.rightTextOffset.x, textOffsets.rightTextOffset.y, mRightTextPaint) } fun drawWeekDay(canvas: Canvas?, time: WatchFaceTime) { val text = ((time.month % 10) + 1).toString() + (if (time.monthDay > 9) time.monthDay.toString() else "0" + time.monthDay.toString()) val textOffsets = getTextOffsets(getWeekDayKanji(time.weekDay), text) canvas?.drawText(getWeekDayKanji(time.weekDay), textOffsets.leftTextOffset.x, textOffsets.leftTextOffset.y, mLeftTextPaint) } private fun getWeekDayKanji(num: Int): String { var c: String = "" when (num) { 0 -> c = "曰" 1 -> c = "月" 2 -> c = "火" 3 -> c = "水" 4 -> c = "木" 5 -> c = "金" 6 -> c = "土" } return c } }
mit
48efbb6a3bc1132b8e5747a21b93f170
42.528662
123
0.650717
4.386393
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/stats/refresh/lists/StatsListViewModel.kt
1
10378
package org.wordpress.android.ui.stats.refresh.lists import androidx.annotation.StringRes import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.delay import org.wordpress.android.R import org.wordpress.android.analytics.AnalyticsTracker.Stat import org.wordpress.android.modules.UI_THREAD import org.wordpress.android.ui.stats.refresh.DAY_STATS_USE_CASE import org.wordpress.android.ui.stats.refresh.INSIGHTS_USE_CASE import org.wordpress.android.ui.stats.refresh.MONTH_STATS_USE_CASE import org.wordpress.android.ui.stats.refresh.NavigationTarget import org.wordpress.android.ui.stats.refresh.NavigationTarget.ViewInsightsManagement import org.wordpress.android.ui.stats.refresh.StatsViewModel.DateSelectorUiModel import org.wordpress.android.ui.stats.refresh.TOTAL_COMMENTS_DETAIL_USE_CASE import org.wordpress.android.ui.stats.refresh.TOTAL_FOLLOWERS_DETAIL_USE_CASE import org.wordpress.android.ui.stats.refresh.TOTAL_LIKES_DETAIL_USE_CASE import org.wordpress.android.ui.stats.refresh.VIEWS_AND_VISITORS_USE_CASE import org.wordpress.android.ui.stats.refresh.WEEK_STATS_USE_CASE import org.wordpress.android.ui.stats.refresh.YEAR_STATS_USE_CASE import org.wordpress.android.ui.stats.refresh.lists.StatsListViewModel.StatsSection.DAYS import org.wordpress.android.ui.stats.refresh.lists.StatsListViewModel.StatsSection.INSIGHTS import org.wordpress.android.ui.stats.refresh.lists.StatsListViewModel.StatsSection.MONTHS import org.wordpress.android.ui.stats.refresh.lists.StatsListViewModel.StatsSection.WEEKS import org.wordpress.android.ui.stats.refresh.lists.StatsListViewModel.StatsSection.YEARS import org.wordpress.android.ui.stats.refresh.utils.ActionCardHandler import org.wordpress.android.ui.stats.refresh.utils.ItemPopupMenuHandler import org.wordpress.android.ui.stats.refresh.utils.NewsCardHandler import org.wordpress.android.ui.stats.refresh.utils.StatsDateSelector import org.wordpress.android.util.analytics.AnalyticsTrackerWrapper import org.wordpress.android.util.mapNullable import org.wordpress.android.util.merge import org.wordpress.android.util.mergeNotNull import org.wordpress.android.util.throttle import org.wordpress.android.viewmodel.Event import org.wordpress.android.viewmodel.ScopedViewModel import javax.inject.Inject import javax.inject.Named const val SCROLL_EVENT_DELAY = 2000L abstract class StatsListViewModel( defaultDispatcher: CoroutineDispatcher, private val statsUseCase: BaseListUseCase, private val analyticsTracker: AnalyticsTrackerWrapper, protected val dateSelector: StatsDateSelector, popupMenuHandler: ItemPopupMenuHandler? = null, private val newsCardHandler: NewsCardHandler? = null, actionCardHandler: ActionCardHandler? = null ) : ScopedViewModel(defaultDispatcher) { private var trackJob: Job? = null private var isInitialized = false enum class StatsSection(@StringRes val titleRes: Int) { INSIGHTS(R.string.stats_insights), DAYS(R.string.stats_timeframe_days), WEEKS(R.string.stats_timeframe_weeks), MONTHS(R.string.stats_timeframe_months), YEARS(R.string.stats_timeframe_years), DETAIL(R.string.stats), INSIGHT_DETAIL(R.string.stats_insights_views_and_visitors), TOTAL_LIKES_DETAIL(R.string.stats_view_total_likes), TOTAL_COMMENTS_DETAIL(R.string.stats_view_total_comments), TOTAL_FOLLOWERS_DETAIL(R.string.stats_view_total_followers), ANNUAL_STATS(R.string.stats_insights_annual_site_stats); } val selectedDate = dateSelector.selectedDate private val mutableNavigationTarget = MutableLiveData<Event<NavigationTarget>>() val navigationTarget: LiveData<Event<NavigationTarget>> = mergeNotNull( statsUseCase.navigationTarget, mutableNavigationTarget ) val listSelected = statsUseCase.listSelected val uiModel: LiveData<UiModel?> by lazy { statsUseCase.data.throttle(viewModelScope, distinct = true) } val dateSelectorData: LiveData<DateSelectorUiModel> = dateSelector.dateSelectorData.mapNullable { it ?: DateSelectorUiModel(false) } val typesChanged = merge( popupMenuHandler?.typeMoved, newsCardHandler?.cardDismissed, actionCardHandler?.actionCard ) val scrollTo = newsCardHandler?.scrollTo val scrollToNewCard = statsUseCase.scrollTo override fun onCleared() { statsUseCase.onCleared() super.onCleared() } fun onScrolledToBottom() { if (trackJob?.isCompleted != false) { trackJob = launch { analyticsTracker.track(Stat.STATS_SCROLLED_TO_BOTTOM) delay(SCROLL_EVENT_DELAY) } } } fun onNextDateSelected() { launch(Dispatchers.Default) { dateSelector.onNextDateSelected() } } fun onPreviousDateSelected() { launch(Dispatchers.Default) { dateSelector.onPreviousDateSelected() } } fun onRetryClick() { launch { statsUseCase.refreshData(true) } } fun onDateChanged(selectedSection: StatsSection) { launch { statsUseCase.onDateChanged(selectedSection) } } fun onListSelected() { dateSelector.updateDateSelector() } fun onEmptyInsightsButtonClicked() { mutableNavigationTarget.value = Event(ViewInsightsManagement) } fun onAddNewStatsButtonClicked() { newsCardHandler?.dismiss() analyticsTracker.track(Stat.STATS_INSIGHTS_MANAGEMENT_ACCESSED, mapOf("source" to "button")) mutableNavigationTarget.value = Event(ViewInsightsManagement) } fun start() { if (!isInitialized) { isInitialized = true launch { statsUseCase.loadData() dateSelector.updateDateSelector() } } dateSelector.updateDateSelector() } sealed class UiModel { data class Success(val data: List<StatsBlock>) : UiModel() data class Error(val message: Int = R.string.stats_loading_error) : UiModel() data class Empty( val title: Int, val subtitle: Int? = null, val image: Int? = null, val showButton: Boolean = false ) : UiModel() } fun onTypesChanged() { launch { statsUseCase.refreshTypes() } } } class InsightsListViewModel @Inject constructor( @Named(UI_THREAD) mainDispatcher: CoroutineDispatcher, @Named(INSIGHTS_USE_CASE) private val insightsUseCase: BaseListUseCase, analyticsTracker: AnalyticsTrackerWrapper, dateSelectorFactory: StatsDateSelector.Factory, popupMenuHandler: ItemPopupMenuHandler, newsCardHandler: NewsCardHandler, actionCardHandler: ActionCardHandler ) : StatsListViewModel( mainDispatcher, insightsUseCase, analyticsTracker, dateSelectorFactory.build(INSIGHTS), popupMenuHandler, newsCardHandler, actionCardHandler ) class YearsListViewModel @Inject constructor( @Named(UI_THREAD) mainDispatcher: CoroutineDispatcher, @Named(YEAR_STATS_USE_CASE) statsUseCase: BaseListUseCase, analyticsTracker: AnalyticsTrackerWrapper, dateSelectorFactory: StatsDateSelector.Factory ) : StatsListViewModel(mainDispatcher, statsUseCase, analyticsTracker, dateSelectorFactory.build(YEARS)) class MonthsListViewModel @Inject constructor( @Named(UI_THREAD) mainDispatcher: CoroutineDispatcher, @Named(MONTH_STATS_USE_CASE) statsUseCase: BaseListUseCase, analyticsTracker: AnalyticsTrackerWrapper, dateSelectorFactory: StatsDateSelector.Factory ) : StatsListViewModel(mainDispatcher, statsUseCase, analyticsTracker, dateSelectorFactory.build(MONTHS)) class WeeksListViewModel @Inject constructor( @Named(UI_THREAD) mainDispatcher: CoroutineDispatcher, @Named(WEEK_STATS_USE_CASE) statsUseCase: BaseListUseCase, analyticsTracker: AnalyticsTrackerWrapper, dateSelectorFactory: StatsDateSelector.Factory ) : StatsListViewModel(mainDispatcher, statsUseCase, analyticsTracker, dateSelectorFactory.build(WEEKS)) class DaysListViewModel @Inject constructor( @Named(UI_THREAD) mainDispatcher: CoroutineDispatcher, @Named(DAY_STATS_USE_CASE) statsUseCase: BaseListUseCase, analyticsTracker: AnalyticsTrackerWrapper, dateSelectorFactory: StatsDateSelector.Factory ) : StatsListViewModel(mainDispatcher, statsUseCase, analyticsTracker, dateSelectorFactory.build(DAYS)) // Using Weeks granularity on new insight details screens class InsightsDetailListViewModel @Inject constructor( @Named(UI_THREAD) mainDispatcher: CoroutineDispatcher, @Named(VIEWS_AND_VISITORS_USE_CASE) statsUseCase: BaseListUseCase, analyticsTracker: AnalyticsTrackerWrapper, dateSelectorFactory: StatsDateSelector.Factory ) : StatsListViewModel(mainDispatcher, statsUseCase, analyticsTracker, dateSelectorFactory.build(WEEKS)) class TotalLikesDetailListViewModel @Inject constructor( @Named(UI_THREAD) mainDispatcher: CoroutineDispatcher, @Named(TOTAL_LIKES_DETAIL_USE_CASE) statsUseCase: BaseListUseCase, analyticsTracker: AnalyticsTrackerWrapper, dateSelectorFactory: StatsDateSelector.Factory ) : StatsListViewModel(mainDispatcher, statsUseCase, analyticsTracker, dateSelectorFactory.build(WEEKS)) class TotalCommentsDetailListViewModel @Inject constructor( @Named(UI_THREAD) mainDispatcher: CoroutineDispatcher, @Named(TOTAL_COMMENTS_DETAIL_USE_CASE) statsUseCase: BaseListUseCase, analyticsTracker: AnalyticsTrackerWrapper, dateSelectorFactory: StatsDateSelector.Factory ) : StatsListViewModel(mainDispatcher, statsUseCase, analyticsTracker, dateSelectorFactory.build(WEEKS)) class TotalFollowersDetailListViewModel @Inject constructor( @Named(UI_THREAD) mainDispatcher: CoroutineDispatcher, @Named(TOTAL_FOLLOWERS_DETAIL_USE_CASE) statsUseCase: BaseListUseCase, analyticsTracker: AnalyticsTrackerWrapper, dateSelectorFactory: StatsDateSelector.Factory ) : StatsListViewModel(mainDispatcher, statsUseCase, analyticsTracker, dateSelectorFactory.build(WEEKS))
gpl-2.0
f603a2f432bd0e95317054e43739cbb8
39.698039
105
0.759009
4.523976
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInsight/codevision/KotlinCodeVisionLimitedHint.kt
1
6007
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.codeInsight.codevision import com.intellij.codeInsight.hints.settings.InlayHintsConfigurable import com.intellij.codeInsight.navigation.actions.GotoDeclarationAction import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiElement import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeInsight.codevision.KotlinCodeVisionUsagesCollector.Companion.CLASS_LOCATION import org.jetbrains.kotlin.idea.codeInsight.codevision.KotlinCodeVisionUsagesCollector.Companion.FUNCTION_LOCATION import org.jetbrains.kotlin.idea.codeInsight.codevision.KotlinCodeVisionUsagesCollector.Companion.INTERFACE_LOCATION import org.jetbrains.kotlin.idea.codeInsight.codevision.KotlinCodeVisionUsagesCollector.Companion.PROPERTY_LOCATION import org.jetbrains.kotlin.idea.codeInsight.codevision.KotlinCodeVisionUsagesCollector.Companion.logInheritorsClicked import org.jetbrains.kotlin.idea.codeInsight.codevision.KotlinCodeVisionUsagesCollector.Companion.logSettingsClicked import org.jetbrains.kotlin.idea.codeInsight.codevision.KotlinCodeVisionUsagesCollector.Companion.logUsagesClicked import org.jetbrains.kotlin.idea.highlighter.markers.OVERRIDDEN_FUNCTION import org.jetbrains.kotlin.idea.highlighter.markers.OVERRIDDEN_PROPERTY import org.jetbrains.kotlin.idea.highlighter.markers.SUBCLASSED_CLASS import org.jetbrains.kotlin.psi.KtClass import org.jetbrains.kotlin.psi.KtFunction import org.jetbrains.kotlin.psi.KtProperty import java.awt.event.MouseEvent abstract class KotlinCodeVisionHint(hintKey: String) { open val regularText: String = KotlinBundle.message(hintKey) abstract fun onClick(editor: Editor, element: PsiElement, event: MouseEvent?) } abstract class KotlinCodeVisionLimitedHint(num: Int, limitReached: Boolean, regularHintKey: String, tooManyHintKey: String) : KotlinCodeVisionHint(regularHintKey) { override val regularText: String = if (limitReached) KotlinBundle.message(tooManyHintKey, num) else KotlinBundle.message(regularHintKey, num) } private const val IMPLEMENTATIONS_KEY = "hints.codevision.implementations.format" private const val IMPLEMENTATIONS_TO_MANY_KEY = "hints.codevision.implementations.too_many.format" private const val INHERITORS_KEY = "hints.codevision.inheritors.format" private const val INHERITORS_TO_MANY_KEY = "hints.codevision.inheritors.to_many.format" private const val OVERRIDES_KEY = "hints.codevision.overrides.format" private const val OVERRIDES_TOO_MANY_KEY = "hints.codevision.overrides.to_many.format" private const val USAGES_KEY = "hints.codevision.usages.format" private const val USAGES_TOO_MANY_KEY = "hints.codevision.usages.too_many.format" private const val SETTINGS_FORMAT = "hints.codevision.settings" class Usages(usagesNum: Int, limitReached: Boolean) : KotlinCodeVisionLimitedHint(usagesNum, limitReached, USAGES_KEY, USAGES_TOO_MANY_KEY) { override fun onClick(editor: Editor, element: PsiElement, event: MouseEvent?) { logUsagesClicked(editor.project) GotoDeclarationAction.startFindUsages(editor, editor.project!!, element) } } class FunctionOverrides(overridesNum: Int, limitReached: Boolean) : KotlinCodeVisionLimitedHint(overridesNum, limitReached, OVERRIDES_KEY, OVERRIDES_TOO_MANY_KEY) { override fun onClick(editor: Editor, element: PsiElement, event: MouseEvent?) { logInheritorsClicked(editor.project, FUNCTION_LOCATION) val navigationHandler = OVERRIDDEN_FUNCTION.navigationHandler navigationHandler.navigate(event, (element as KtFunction).nameIdentifier) } } class FunctionImplementations(implNum: Int, limitReached: Boolean) : KotlinCodeVisionLimitedHint(implNum, limitReached, IMPLEMENTATIONS_KEY, IMPLEMENTATIONS_TO_MANY_KEY) { override fun onClick(editor: Editor, element: PsiElement, event: MouseEvent?) { logInheritorsClicked(editor.project, FUNCTION_LOCATION) val navigationHandler = OVERRIDDEN_FUNCTION.navigationHandler navigationHandler.navigate(event, (element as KtFunction).nameIdentifier) } } class PropertyOverrides(overridesNum: Int, limitReached: Boolean) : KotlinCodeVisionLimitedHint(overridesNum, limitReached, OVERRIDES_KEY, OVERRIDES_TOO_MANY_KEY) { override fun onClick(editor: Editor, element: PsiElement, event: MouseEvent?) { logInheritorsClicked(editor.project, PROPERTY_LOCATION) val navigationHandler = OVERRIDDEN_PROPERTY.navigationHandler navigationHandler.navigate(event, (element as KtProperty).nameIdentifier) } } class ClassInheritors(inheritorsNum: Int, limitReached: Boolean) : KotlinCodeVisionLimitedHint(inheritorsNum, limitReached, INHERITORS_KEY, INHERITORS_TO_MANY_KEY) { override fun onClick(editor: Editor, element: PsiElement, event: MouseEvent?) { logInheritorsClicked(editor.project, CLASS_LOCATION) val navigationHandler = SUBCLASSED_CLASS.navigationHandler navigationHandler.navigate(event, (element as KtClass).nameIdentifier) } } class InterfaceImplementations(implNum: Int, limitReached: Boolean) : KotlinCodeVisionLimitedHint(implNum, limitReached, IMPLEMENTATIONS_KEY, IMPLEMENTATIONS_TO_MANY_KEY) { override fun onClick(editor: Editor, element: PsiElement, event: MouseEvent?) { logInheritorsClicked(editor.project, INTERFACE_LOCATION) val navigationHandler = SUBCLASSED_CLASS.navigationHandler navigationHandler.navigate(event, (element as KtClass).nameIdentifier) } } class SettingsHint : KotlinCodeVisionHint(SETTINGS_FORMAT) { override fun onClick(editor: Editor, element: PsiElement, event: MouseEvent?) { val project = element.project logSettingsClicked(project) InlayHintsConfigurable.showSettingsDialogForLanguage(project, element.language) } }
apache-2.0
a040d4e16ed8bf615f086714868f0bf2
50.350427
158
0.801731
4.324694
false
false
false
false
android/nowinandroid
core/data/src/test/java/com/google/samples/apps/nowinandroid/core/data/testdoubles/TestNewsResourceDao.kt
1
4765
/* * Copyright 2022 The Android Open Source Project * * 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 * * https://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. */ package com.google.samples.apps.nowinandroid.core.data.testdoubles import com.google.samples.apps.nowinandroid.core.database.dao.NewsResourceDao import com.google.samples.apps.nowinandroid.core.database.model.AuthorEntity import com.google.samples.apps.nowinandroid.core.database.model.NewsResourceAuthorCrossRef import com.google.samples.apps.nowinandroid.core.database.model.NewsResourceEntity import com.google.samples.apps.nowinandroid.core.database.model.NewsResourceTopicCrossRef import com.google.samples.apps.nowinandroid.core.database.model.PopulatedNewsResource import com.google.samples.apps.nowinandroid.core.database.model.TopicEntity import com.google.samples.apps.nowinandroid.core.model.data.NewsResourceType.Video import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.update import kotlinx.datetime.Instant val filteredInterestsIds = setOf("1") val nonPresentInterestsIds = setOf("2") /** * Test double for [NewsResourceDao] */ class TestNewsResourceDao : NewsResourceDao { private var entitiesStateFlow = MutableStateFlow( listOf( NewsResourceEntity( id = "1", title = "news", content = "Hilt", url = "url", headerImageUrl = "headerImageUrl", type = Video, publishDate = Instant.fromEpochMilliseconds(1), ) ) ) internal var topicCrossReferences: List<NewsResourceTopicCrossRef> = listOf() internal var authorCrossReferences: List<NewsResourceAuthorCrossRef> = listOf() override fun getNewsResourcesStream(): Flow<List<PopulatedNewsResource>> = entitiesStateFlow.map { it.map(NewsResourceEntity::asPopulatedNewsResource) } override fun getNewsResourcesStream( filterAuthorIds: Set<String>, filterTopicIds: Set<String> ): Flow<List<PopulatedNewsResource>> = getNewsResourcesStream() .map { resources -> resources.filter { resource -> resource.topics.any { it.id in filterTopicIds } || resource.authors.any { it.id in filterAuthorIds } } } override suspend fun insertOrIgnoreNewsResources( entities: List<NewsResourceEntity> ): List<Long> { entitiesStateFlow.value = entities // Assume no conflicts on insert return entities.map { it.id.toLong() } } override suspend fun updateNewsResources(entities: List<NewsResourceEntity>) { throw NotImplementedError("Unused in tests") } override suspend fun upsertNewsResources(newsResourceEntities: List<NewsResourceEntity>) { entitiesStateFlow.value = newsResourceEntities } override suspend fun insertOrIgnoreTopicCrossRefEntities( newsResourceTopicCrossReferences: List<NewsResourceTopicCrossRef> ) { topicCrossReferences = newsResourceTopicCrossReferences } override suspend fun insertOrIgnoreAuthorCrossRefEntities( newsResourceAuthorCrossReferences: List<NewsResourceAuthorCrossRef> ) { authorCrossReferences = newsResourceAuthorCrossReferences } override suspend fun deleteNewsResources(ids: List<String>) { val idSet = ids.toSet() entitiesStateFlow.update { entities -> entities.filterNot { idSet.contains(it.id) } } } } private fun NewsResourceEntity.asPopulatedNewsResource() = PopulatedNewsResource( entity = this, authors = listOf( AuthorEntity( id = "id", name = "name", imageUrl = "imageUrl", twitter = "twitter", mediumPage = "mediumPage", bio = "bio", ) ), topics = listOf( TopicEntity( id = filteredInterestsIds.random(), name = "name", shortDescription = "short description", longDescription = "long description", url = "URL", imageUrl = "image URL", ) ), )
apache-2.0
10eda518e620d7194ce19e1ca1c38497
34.559701
94
0.680588
4.862245
false
false
false
false
micolous/metrodroid
src/commonMain/kotlin/au/id/micolous/metrodroid/transit/clipper/ClipperTrip.kt
1
4385
/* * ClipperTrip.kt * * Copyright 2011 "an anonymous contributor" * Copyright 2011-2014 Eric Butler <[email protected]> * Copyright 2018 Michael Farrell <[email protected]> * Copyright 2018 Google * * Thanks to: * An anonymous contributor for reverse engineering Clipper data and providing * most of the code here. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package au.id.micolous.metrodroid.transit.clipper import au.id.micolous.metrodroid.multi.FormattedString import au.id.micolous.metrodroid.multi.Parcelize import au.id.micolous.metrodroid.time.Timestamp import au.id.micolous.metrodroid.transit.Station import au.id.micolous.metrodroid.transit.TransitCurrency import au.id.micolous.metrodroid.transit.Trip import au.id.micolous.metrodroid.util.NumberUtils import au.id.micolous.metrodroid.util.ImmutableByteArray @Parcelize class ClipperTrip (private val mTimestamp: Long, private val mExitTimestamp: Long, private val mFare: Int, private val mAgency: Int, private val mFrom: Int, private val mTo: Int, private val mRoute: Int, private val mVehicleNum: Int, private val mTransportCode: Int): Trip() { override val startTimestamp: Timestamp? get() = ClipperTransitData.clipperTimestampToCalendar(mTimestamp) override val endTimestamp: Timestamp? get() = ClipperTransitData.clipperTimestampToCalendar(mExitTimestamp) // Bus doesn't record line override val routeName: FormattedString? get() = ClipperData.getRouteName(mAgency, mRoute) override val humanReadableRouteID: String? get() = if (mAgency == ClipperData.AGENCY_GG_FERRY) { NumberUtils.intToHex(mRoute) } else null override val vehicleID: String? get() = when (mVehicleNum) { 0, 0xffff -> null in 1..9999 -> mVehicleNum.toString() // For LRV4 Muni vehicles with newer Clipper readers, it stores a 4-digit vehicle number followed // by a letter. For example 0d20461 is vehicle number 2046A, 0d20462 is 2046B, and so on. else -> (mVehicleNum / 10).toString() + ((mVehicleNum % 10) + 9).toString(16).toUpperCase() } override val fare: TransitCurrency? get() = TransitCurrency.USD(mFare) override val startStation: Station? get() = ClipperData.getStation(mAgency, mFrom, false) override val endStation: Station? get() = ClipperData.getStation(mAgency, mTo, true) override val mode: Trip.Mode get() = when (mTransportCode) { 0x62 -> { when (mAgency) { ClipperData.AGENCY_BAY_FERRY, ClipperData.AGENCY_GG_FERRY -> Trip.Mode.FERRY ClipperData.AGENCY_CALTRAIN, ClipperData.AGENCY_SMART -> Trip.Mode.TRAIN else -> Trip.Mode.TRAM } } 0x6f -> Trip.Mode.METRO 0x61, 0x75 -> Trip.Mode.BUS 0x73 -> Trip.Mode.FERRY else -> Trip.Mode.OTHER } internal constructor(useData: ImmutableByteArray): this( mAgency = useData.byteArrayToInt(0x2, 2), mFare = useData.byteArrayToInt(0x6, 2), mVehicleNum = useData.byteArrayToInt(0xa, 2), mTimestamp = useData.byteArrayToLong(0xc, 4), mExitTimestamp = useData.byteArrayToLong(0x10, 4), mFrom = useData.byteArrayToInt(0x14, 2), mTo = useData.byteArrayToInt(0x16, 2), mRoute = useData.byteArrayToInt(0x1c, 2), mTransportCode = useData.byteArrayToInt(0x1e, 2) ) override fun getAgencyName(isShort: Boolean) = ClipperData.getAgencyName(mAgency, isShort) }
gpl-3.0
7b913475a7d3d20457dc1a79ed6de3c9
38.863636
109
0.664766
4.015568
false
false
false
false
AberrantFox/hotbot
src/main/kotlin/me/aberrantfox/hotbot/services/APIRateLimiter.kt
1
1146
package me.aberrantfox.hotbot.services import com.google.gson.Gson import org.joda.time.DateTime import java.io.File import kotlin.concurrent.timer private data class Datum(var current: Int) data class APIRateLimiter(private val limit: Int, private var current: Int, val name: String) { private val gson = Gson() private val file = File(configPath("ratelimit/$name.json")) init { val parent = file.parentFile if( !(parent.exists()) ) { parent.mkdirs() } if(file.exists()) { val datum = gson.fromJson(file.readText(), Datum::class.java) current = datum.current } timer(name, false, 0.toLong(), 60 * 1000 * 60 * 24) { checkReset() } } fun increment() { current++ val text = gson.toJson(Datum(current)) file.writeText(text) } fun left() = limit - current fun canCall() = limit != current && limit > current private fun checkReset() = if(DateTime.now().toLocalDate().dayOfMonth == 25) { file.writeText(gson.toJson(Datum(0))) current = 0 } else { Unit } }
mit
c7150d7854cb97f48db2a964e91235ff
25.045455
95
0.598604
4.006993
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/notification/notificationUtils.kt
2
2252
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.notification import com.intellij.notification.Notification import com.intellij.notification.Notifications import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.impl.NonBlockingReadActionImpl import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import org.jetbrains.kotlin.idea.compiler.configuration.KotlinPluginLayout import org.jetbrains.kotlin.idea.migration.KotlinMigrationBundle fun catchNotificationText(project: Project, action: () -> Unit): String? { val notifications = catchNotifications(project, action).ifEmpty { return null } return notifications.single().content } fun catchNotifications(project: Project, action: () -> Unit): List<Notification> { val myDisposable = Disposer.newDisposable() try { val notifications = mutableListOf<Notification>() val connection = project.messageBus.connect(myDisposable) connection.subscribe(Notifications.TOPIC, object : Notifications { override fun notify(notification: Notification) { notifications += notification } }) action() connection.deliverImmediately() ApplicationManager.getApplication().invokeAndWait { NonBlockingReadActionImpl.waitForAsyncTaskCompletion() } return notifications } finally { Disposer.dispose(myDisposable) } } val Notification.asText: String get() = "Title: '$title'\nContent: '$content'" fun List<Notification>.asText(filterNotificationAboutNewKotlinVersion: Boolean = true): String = sortedBy { it.content } .filter { !filterNotificationAboutNewKotlinVersion || !it.content.contains( KotlinMigrationBundle.message( "kotlin.external.compiler.updates.notification.content.0", KotlinPluginLayout.standaloneCompilerVersion.kotlinVersion ) ) } .joinToString(separator = "\n-----\n", transform = Notification::asText)
apache-2.0
8b665ed904f2252f6122d69ecb374df6
44.04
120
0.699822
5.200924
false
false
false
false