repo_name
stringlengths
7
81
path
stringlengths
4
242
copies
stringclasses
95 values
size
stringlengths
1
6
content
stringlengths
3
991k
license
stringclasses
15 values
ozbek/quran_android
app/src/warsh/java/com/quran/labs/androidquran/data/QuranFileConstants.kt
2
685
package com.quran.labs.androidquran.data import com.quran.labs.androidquran.ui.util.TypefaceManager import com.quran.labs.androidquran.database.DatabaseHandler object QuranFileConstants { // server urls const val FONT_TYPE = TypefaceManager.TYPE_UTHMANIC_WARSH // arabic database const val ARABIC_DATABASE = "quran.ar.warsh.db" const val ARABIC_SHARE_TABLE = DatabaseHandler.ARABIC_TEXT_TABLE const val ARABIC_SHARE_TEXT_HAS_BASMALLAH = true const val FETCH_QUARTER_NAMES_FROM_DATABASE = true const val FALLBACK_PAGE_TYPE = "warsh" const val SEARCH_EXTRA_REPLACEMENTS = "\u0626" var ICON_RESOURCE_ID = com.quran.labs.androidquran.pages.warsh.R.drawable.icon }
gpl-3.0
ingokegel/intellij-community
platform/lang-impl/src/com/intellij/lang/documentation/DocumentationResultData.kt
8
1555
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.lang.documentation import com.intellij.lang.documentation.DocumentationResult.Data import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.emptyFlow import org.jetbrains.annotations.VisibleForTesting import java.awt.Image @VisibleForTesting data class DocumentationResultData internal constructor( internal val content: DocumentationContentData, internal val links: LinkData = LinkData(), val anchor: String? = null, internal val updates: Flow<DocumentationContentData> = emptyFlow(), ) : Data { val html: String get() = content.html override fun html(html: String): Data { return content(content.copy(html = html)) } override fun images(images: Map<String, Image>): Data { return content(content.copy(imageResolver = imageResolver(images))) } override fun content(content: DocumentationContent): Data { return copy(content = content as DocumentationContentData) } override fun anchor(anchor: String?): Data { return copy(anchor = anchor) } override fun externalUrl(externalUrl: String?): Data { return copy(links = links.copy(externalUrl = externalUrl)) } override fun updates(updates: Flow<DocumentationContent>): Data { @Suppress("UNCHECKED_CAST") return copy(updates = updates as Flow<DocumentationContentData>) } override fun updates(updater: DocumentationContentUpdater): Data { return updates(updater.asFlow()) } }
apache-2.0
mdaniel/intellij-community
plugins/kotlin/idea/tests/testData/intentions/convertPropertyInitializerToGetter/propertyWithInitializerWithSetter.kt
13
110
// SKIP_ERRORS_AFTER class A { var a = <caret>1 set(value) { field = value } }
apache-2.0
zdary/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/controlFlow/impl/VariableNameDescriptor.kt
13
479
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.lang.psi.controlFlow.impl import org.jetbrains.plugins.groovy.lang.psi.controlFlow.VariableDescriptor data class VariableNameDescriptor(val variableName: String): VariableDescriptor { override fun getName(): String = variableName override fun toString(): String { return variableName } }
apache-2.0
feelfreelinux/WykopMobilny
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/profile/microblog/comments/MicroblogCommentsModule.kt
1
748
package io.github.feelfreelinux.wykopmobilny.ui.modules.profile.microblog.comments import dagger.Module import dagger.Provides import io.github.feelfreelinux.wykopmobilny.api.entries.EntriesApi import io.github.feelfreelinux.wykopmobilny.api.profile.ProfileApi import io.github.feelfreelinux.wykopmobilny.base.Schedulers import io.github.feelfreelinux.wykopmobilny.ui.fragments.entrycomments.EntryCommentInteractor @Module class MicroblogCommentsModule { @Provides fun providesPresenter( schedulers: Schedulers, profileApi: ProfileApi, entriesApi: EntriesApi, entryCommentsInteractor: EntryCommentInteractor ) = MicroblogCommentsPresenter(schedulers, profileApi, entriesApi, entryCommentsInteractor) }
mit
siosio/intellij-community
plugins/kotlin/idea/tests/testData/intentions/removeArgumentName/MixedNamedArgumentsInTheirOwnPosition/namedArgumentBefore2.kt
4
177
// COMPILER_ARGUMENTS: -XXLanguage:+MixedNamedArgumentsInTheirOwnPosition fun foo(name1: Int, name2: Int, name3: Int) {} fun usage() { foo(1, name2 = 2, <caret>name3 = 3) }
apache-2.0
siosio/intellij-community
plugins/kotlin/jps/jps-plugin/src/org/jetbrains/kotlin/jps/incremental/JpsIncrementalCache.kt
1
2747
// 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.jps.incremental import org.jetbrains.jps.builders.storage.BuildDataPaths import org.jetbrains.jps.builders.storage.StorageProvider import org.jetbrains.jps.incremental.ModuleBuildTarget import org.jetbrains.jps.incremental.storage.BuildDataManager import org.jetbrains.jps.incremental.storage.StorageOwner import org.jetbrains.kotlin.incremental.IncrementalCacheCommon import org.jetbrains.kotlin.incremental.IncrementalJsCache import org.jetbrains.kotlin.incremental.IncrementalJvmCache import org.jetbrains.kotlin.incremental.storage.FileToPathConverter import org.jetbrains.kotlin.jps.build.KotlinBuilder import org.jetbrains.kotlin.jps.targets.KotlinModuleBuildTarget import org.jetbrains.kotlin.serialization.js.JsSerializerProtocol import java.io.File interface JpsIncrementalCache : IncrementalCacheCommon, StorageOwner { fun addJpsDependentCache(cache: JpsIncrementalCache) } class JpsIncrementalJvmCache( target: ModuleBuildTarget, paths: BuildDataPaths, pathConverter: FileToPathConverter ) : IncrementalJvmCache(paths.getTargetDataRoot(target), target.outputDir, pathConverter), JpsIncrementalCache { override fun addJpsDependentCache(cache: JpsIncrementalCache) { if (cache is JpsIncrementalJvmCache) { addDependentCache(cache) } } override fun debugLog(message: String) { KotlinBuilder.LOG.debug(message) } } class JpsIncrementalJsCache( target: ModuleBuildTarget, paths: BuildDataPaths, pathConverter: FileToPathConverter ) : IncrementalJsCache(paths.getTargetDataRoot(target), pathConverter, JsSerializerProtocol), JpsIncrementalCache { override fun addJpsDependentCache(cache: JpsIncrementalCache) { if (cache is JpsIncrementalJsCache) { addDependentCache(cache) } } } private class KotlinIncrementalStorageProvider( private val target: KotlinModuleBuildTarget<*>, private val paths: BuildDataPaths ) : StorageProvider<JpsIncrementalCache>() { init { check(target.hasCaches) } override fun equals(other: Any?) = other is KotlinIncrementalStorageProvider && target == other.target override fun hashCode() = target.hashCode() override fun createStorage(targetDataDir: File): JpsIncrementalCache = target.createCacheStorage(paths) } fun BuildDataManager.getKotlinCache(target: KotlinModuleBuildTarget<*>?): JpsIncrementalCache? = if (target == null || !target.hasCaches) null else getStorage(target.jpsModuleBuildTarget, KotlinIncrementalStorageProvider(target, dataPaths))
apache-2.0
chemouna/Nearby
app/src/androidTest/java/rx/plugins/RxJavaSchedulersTestRule.kt
1
1659
package rx.plugins import org.junit.rules.TestRule import org.junit.runner.Description import org.junit.runners.model.Statement import rx.Scheduler import rx.android.plugins.RxAndroidPlugins import rx.android.plugins.RxAndroidSchedulersHook import rx.schedulers.Schedulers /** * A {@link TestRule} to apply to tests that have observables that subscribe/observe on * RxJava/RxAndroid schedulers. * * NOTE: we needed to put in package rx.plugins to be able to access reset method that has * a package private (there's currently an issue on RxJava to make it public). */ public class RxJavaSchedulersTestRule : TestRule { override fun apply(base: Statement, description: Description): Statement { return object : Statement() { @Throws(Throwable::class) override fun evaluate() { resetPlugins() RxJavaPlugins.getInstance().registerSchedulersHook(TestRxJavaSchedulersHook()) RxAndroidPlugins.getInstance().registerSchedulersHook(TestRxAndroidSchedulersHook()) base.evaluate() resetPlugins() } } } private fun resetPlugins() { RxJavaPlugins.getInstance().reset() RxAndroidPlugins.getInstance().reset() } private inner class TestRxAndroidSchedulersHook : RxAndroidSchedulersHook() { override fun getMainThreadScheduler(): Scheduler { return Schedulers.immediate() } } private inner class TestRxJavaSchedulersHook : RxJavaSchedulersHook() { override fun getIOScheduler(): Scheduler { return Schedulers.immediate() } } }
apache-2.0
siosio/intellij-community
plugins/kotlin/idea/tests/testData/quickfix/surroundWithNullCheck/unsafeCallInsideAnonymous.kt
4
132
// "Surround with null check" "true" // WITH_RUNTIME fun Int.bar() = this fun foo(arg: Int?) { run(fun() = arg<caret>.bar()) }
apache-2.0
jwren/intellij-community
platform/platform-tests/testSrc/com/intellij/ide/plugins/PluginModelValidator.kt
1
24377
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.plugins import com.fasterxml.jackson.core.JsonFactory import com.fasterxml.jackson.core.JsonGenerator import com.intellij.openapi.application.PathManager.getHomePath import com.intellij.util.getErrorsAsString import com.intellij.util.io.jackson.array import com.intellij.util.io.jackson.obj import com.intellij.util.xml.dom.XmlElement import com.intellij.util.xml.dom.readXmlAsModel import java.io.StringWriter import java.nio.file.Files import java.nio.file.NoSuchFileException import java.nio.file.Path import java.util.* import kotlin.io.path.div private val emptyPath by lazy { Path.of("/") } internal val homePath by lazy { Path.of(getHomePath()) } @Suppress("ReplaceJavaStaticMethodWithKotlinAnalog") private val moduleSkipList = java.util.Set.of( "fleet", "intellij.indexing.shared.ultimate.plugin.internal.generator", "intellij.indexing.shared.ultimate.plugin.public", "kotlin-ultimate.appcode-kmm.main", /* Used only when running from sources */ "intellij.javaFX.community", "intellij.lightEdit", "intellij.webstorm", "intellij.cwm.plugin", /* platform/cwm-plugin/resources/META-INF/plugin.xml doesn't have `id` - ignore for now */ "intellij.osgi", /* no particular package prefix to choose */ "intellij.hunspell", /* MP-3656 Marketplace doesn't allow uploading plugins without dependencies */ "kotlin.resources-fir", /* Kotlin FIR IDE Plugin has the same plugin id as the plain Kotlin plugin */ ) class PluginModelValidator(sourceModules: List<Module>) { interface Module { val name: String val sourceRoots: List<Path> } private val pluginIdToInfo = LinkedHashMap<String, ModuleInfo>() private val _errors = mutableListOf<Throwable>() val errors: List<Throwable> get() = java.util.List.copyOf(_errors) val errorsAsString: CharSequence get() = if (_errors.isEmpty()) "" else getErrorsAsString(_errors, includeStackTrace = false) init { // 1. collect plugin and module file info set val sourceModuleNameToFileInfo = sourceModules.associate { it.name to ModuleDescriptorFileInfo(it) } for (module in sourceModules) { val moduleName = module.name if (moduleName.startsWith("fleet.") || moduleSkipList.contains(moduleName)) { continue } for (sourceRoot in module.sourceRoots) { updateFileInfo( moduleName, sourceRoot, sourceModuleNameToFileInfo[moduleName]!! ) } } val moduleNameToInfo = HashMap<String, ModuleInfo>() // 2. process plugins - process content to collect modules for ((sourceModuleName, moduleMetaInfo) in sourceModuleNameToFileInfo) { // interested only in plugins val descriptor = moduleMetaInfo.pluginDescriptor ?: continue val descriptorFile = moduleMetaInfo.pluginDescriptorFile ?: continue val id = descriptor.getChild("id")?.content ?: descriptor.getChild("name")?.content if (id == null) { _errors.add(PluginValidationError( "Plugin id is not specified", mapOf( "descriptorFile" to descriptorFile ), )) continue } val moduleInfo = ModuleInfo(pluginId = id, name = null, sourceModuleName = sourceModuleName, descriptorFile = descriptorFile, packageName = descriptor.getAttributeValue("package"), descriptor = descriptor) val prev = pluginIdToInfo.put(id, moduleInfo) if (prev != null) { throw PluginValidationError( "Duplicated plugin id: $id", mapOf( "prev" to prev, "current" to moduleInfo, ), ) } descriptor.getChild("content")?.let { contentElement -> checkContent(content = contentElement, referencingModuleInfo = moduleInfo, sourceModuleNameToFileInfo = sourceModuleNameToFileInfo, moduleNameToInfo = moduleNameToInfo) } } // 3. check dependencies - we are aware about all modules now for (pluginInfo in pluginIdToInfo.values) { val descriptor = pluginInfo.descriptor val dependenciesElements = descriptor.children("dependencies").toList() if (dependenciesElements.size > 1) { _errors.add(PluginValidationError( "The only `dependencies` tag is expected", mapOf( "descriptorFile" to pluginInfo.descriptorFile, ), )) } else if (dependenciesElements.size == 1) { checkDependencies(dependenciesElements.first(), pluginInfo, pluginInfo, moduleNameToInfo, sourceModuleNameToFileInfo) } // in the end after processing content and dependencies if (pluginInfo.packageName == null && hasContentOrDependenciesInV2Format(descriptor)) { // some plugins cannot be yet fully migrated val error = PluginValidationError( "Plugin ${pluginInfo.pluginId} is not fully migrated: package is not specified", mapOf( "pluginId" to pluginInfo.pluginId, "descriptor" to pluginInfo.descriptorFile, ), ) System.err.println(error.message) } if (pluginInfo.packageName != null) { descriptor.children.firstOrNull { it.name == "depends" && it.getAttributeValue("optional") == null }?.let { _errors.add(PluginValidationError( "The old format should not be used for a plugin with the specified package prefix, but `depends` tag is used." + " Please use the new format (see https://github.com/JetBrains/intellij-community/blob/master/docs/plugin.md#the-dependencies-element)", mapOf( "descriptorFile" to pluginInfo.descriptorFile, "depends" to it, ), )) } } for (contentModuleInfo in pluginInfo.content) { contentModuleInfo.descriptor.getChild("dependencies")?.let { dependencies -> checkDependencies(dependencies, contentModuleInfo, pluginInfo, moduleNameToInfo, sourceModuleNameToFileInfo) } contentModuleInfo.descriptor.getChild("depends")?.let { _errors.add(PluginValidationError( "Old format must be not used for a module but `depends` tag is used", mapOf( "descriptorFile" to contentModuleInfo.descriptorFile, "depends" to it, ), )) } } } } fun graphAsString(): CharSequence { val stringWriter = StringWriter() val writer = JsonFactory().createGenerator(stringWriter) writer.useDefaultPrettyPrinter() writer.use { writer.obj { val entries = pluginIdToInfo.entries.toMutableList() entries.sortBy { it.value.sourceModuleName } for (entry in entries) { val item = entry.value if (item.packageName == null && !hasContentOrDependenciesInV2Format(item.descriptor)) { continue } writer.writeFieldName(item.sourceModuleName) writeModuleInfo(writer, item) } } } return stringWriter.buffer } fun writeGraph(outFile: Path) { PluginGraphWriter(pluginIdToInfo).write(outFile) } private fun checkDependencies(element: XmlElement, referencingModuleInfo: ModuleInfo, referencingPluginInfo: ModuleInfo, moduleNameToInfo: Map<String, ModuleInfo>, sourceModuleNameToFileInfo: Map<String, ModuleDescriptorFileInfo>) { if (referencingModuleInfo.packageName == null && !knownNotFullyMigratedPluginIds.contains(referencingModuleInfo.pluginId)) { _errors.add(PluginValidationError( "`dependencies` must be specified only for plugin in a new format: package prefix is not specified", mapOf( "referencingDescriptorFile" to referencingModuleInfo.descriptorFile, ))) } for (child in element.children) { fun getErrorInfo(): Map<String, Any?> { return mapOf( "entry" to child, "referencingDescriptorFile" to referencingModuleInfo.descriptorFile, ) } if (child.name != "module") { if (child.name == "plugin") { // todo check that the referenced plugin exists val id = child.getAttributeValue("id") if (id == null) { _errors.add(PluginValidationError( "Id is not specified for dependency on plugin", getErrorInfo(), )) continue } if (id == "com.intellij.modules.java") { _errors.add(PluginValidationError( "Use com.intellij.java id instead of com.intellij.modules.java", getErrorInfo(), )) continue } if (id == "com.intellij.modules.platform") { _errors.add(PluginValidationError( "No need to specify dependency on $id", getErrorInfo(), )) continue } if (id == referencingPluginInfo.pluginId) { _errors.add(PluginValidationError( "Do not add dependency on a parent plugin", getErrorInfo(), )) continue } val dependency = pluginIdToInfo[id] if (!id.startsWith("com.intellij.modules.") && dependency == null) { _errors.add(PluginValidationError( "Plugin not found: $id", getErrorInfo(), )) continue } val ref = Reference( name = id, isPlugin = true, moduleInfo = dependency ?: ModuleInfo(null, id, "", emptyPath, null, XmlElement("", Collections.emptyMap(), Collections.emptyList(), null)) ) if (referencingModuleInfo.dependencies.contains(ref)) { _errors.add(PluginValidationError( "Referencing module dependencies contains $id: $id", getErrorInfo(), )) continue } referencingModuleInfo.dependencies.add(ref) continue } if (referencingModuleInfo.isPlugin) { _errors.add(PluginValidationError( "Unsupported dependency type: ${child.name}", getErrorInfo(), )) continue } } val moduleName = child.getAttributeValue("name") if (moduleName == null) { _errors.add(PluginValidationError( "Module name is not specified", getErrorInfo(), )) continue } if (moduleName == "intellij.platform.commercial.verifier") { continue } if (child.attributes.size > 1) { _errors.add(PluginValidationError( "Unknown attributes: ${child.attributes.entries.filter { it.key != "name" }}", getErrorInfo(), )) continue } val moduleInfo = moduleNameToInfo[moduleName] if (moduleInfo == null) { val moduleDescriptorFileInfo = sourceModuleNameToFileInfo[moduleName] if (moduleDescriptorFileInfo != null) { if (moduleDescriptorFileInfo.pluginDescriptor != null) { _errors.add(PluginValidationError( message = "Dependency on plugin must be specified using `plugin` and not `module`", params = getErrorInfo(), fix = """ Change dependency element to: <plugin id="${moduleDescriptorFileInfo.pluginDescriptor!!.getChild("id")?.content}"/> """, )) continue } } _errors.add(PluginValidationError("Module not found: $moduleName", getErrorInfo())) continue } referencingModuleInfo.dependencies.add(Reference(moduleName, isPlugin = false, moduleInfo)) for (dependsElement in referencingModuleInfo.descriptor.children) { if (dependsElement.name != "depends") { continue } if (dependsElement.getAttributeValue("config-file")?.removePrefix("/META-INF/") == moduleInfo.descriptorFile.fileName.toString()) { _errors.add(PluginValidationError( "Module, that used as dependency, must be not specified in `depends`", getErrorInfo(), )) break } } } } // for plugin two variants: // 1) depends + dependency on plugin in a referenced descriptor = optional descriptor. In old format: depends tag // 2) no depends + no dependency on plugin in a referenced descriptor = directly injected into plugin (separate classloader is not created // during transition period). In old format: xi:include (e.g. <xi:include href="dockerfile-language.xml"/>). private fun checkContent(content: XmlElement, referencingModuleInfo: ModuleInfo, sourceModuleNameToFileInfo: Map<String, ModuleDescriptorFileInfo>, moduleNameToInfo: MutableMap<String, ModuleInfo>) { for (child in content.children) { fun getErrorInfo(): Map<String, Any> { return mapOf( "entry" to child, "referencingDescriptorFile" to referencingModuleInfo.descriptorFile, ) } if (child.name != "module") { _errors.add(PluginValidationError( "Unexpected element: $child", getErrorInfo(), )) continue } val moduleName = child.getAttributeValue("name") if (moduleName == null) { _errors.add(PluginValidationError( "Module name is not specified", getErrorInfo(), )) continue } if (child.attributes.size > 1) { _errors.add(PluginValidationError( "Unknown attributes: ${child.attributes.entries.filter { it.key != "name" }}", getErrorInfo(), )) continue } if (moduleName == "intellij.platform.commercial.verifier") { _errors.add(PluginValidationError( "intellij.platform.commercial.verifier is not supposed to be used as content of plugin", getErrorInfo(), )) continue } // ignore null - getModule reports error val moduleDescriptorFileInfo = getModuleDescriptorFileInfo(moduleName, referencingModuleInfo, sourceModuleNameToFileInfo) ?: continue val moduleDescriptor = moduleDescriptorFileInfo.moduleDescriptor!! val packageName = moduleDescriptor.getAttributeValue("package") if (packageName == null) { _errors.add(PluginValidationError( "Module package is not specified", mapOf( "descriptorFile" to moduleDescriptorFileInfo.moduleDescriptorFile!!, ), )) continue } val moduleInfo = ModuleInfo(pluginId = null, name = moduleName, sourceModuleName = moduleDescriptorFileInfo.sourceModule.name, descriptorFile = moduleDescriptorFileInfo.moduleDescriptorFile!!, packageName = packageName, descriptor = moduleDescriptor) moduleNameToInfo[moduleName] = moduleInfo referencingModuleInfo.content.add(moduleInfo) @Suppress("GrazieInspection") // check that not specified using `depends` tag for (dependsElement in referencingModuleInfo.descriptor.children) { if (dependsElement.name != "depends") { continue } if (dependsElement.getAttributeValue("config-file")?.removePrefix("/META-INF/") == moduleInfo.descriptorFile.fileName.toString()) { _errors.add(PluginValidationError( "Module must be not specified in `depends`.", getErrorInfo() + mapOf( "referencedDescriptorFile" to moduleInfo.descriptorFile ), )) continue } } moduleDescriptor.getChild("content")?.let { _errors.add(PluginValidationError( "Module cannot define content", getErrorInfo() + mapOf( "referencedDescriptorFile" to moduleInfo.descriptorFile ), )) } } } private fun getModuleDescriptorFileInfo(moduleName: String, referencingModuleInfo: ModuleInfo, sourceModuleNameToFileInfo: Map<String, ModuleDescriptorFileInfo>): ModuleDescriptorFileInfo? { var module = sourceModuleNameToFileInfo[moduleName] if (module != null) { return module } fun getErrorInfo(): Map<String, Path> { return mapOf( "referencingDescriptorFile" to referencingModuleInfo.descriptorFile ) } val prefix = referencingModuleInfo.sourceModuleName + "/" if (!moduleName.startsWith(prefix)) { _errors.add(PluginValidationError( "Cannot find module $moduleName", getErrorInfo(), )) return null } val slashIndex = prefix.length - 1 val containingModuleName = moduleName.substring(0, slashIndex) module = sourceModuleNameToFileInfo[containingModuleName] if (module == null) { _errors.add(PluginValidationError( "Cannot find module $containingModuleName", getErrorInfo(), )) return null } val fileName = "$containingModuleName.${moduleName.substring(slashIndex + 1)}.xml" val result = loadFileInModule(sourceModule = module.sourceModule, fileName = fileName) if (result == null) { _errors.add(PluginValidationError( message = "Module ${module.sourceModule.name} doesn't have descriptor file", params = mapOf( "expectedFile" to fileName, "referencingDescriptorFile" to referencingModuleInfo.descriptorFile, ), fix = """ Create file $fileName in ${pathToShortString(module.sourceModule.sourceRoots.first())} with content: <idea-plugin package="REPLACE_BY_MODULE_PACKAGE"> </idea-plugin> """ )) } return result } private fun updateFileInfo( moduleName: String, sourceRoot: Path, fileInfo: ModuleDescriptorFileInfo, ) { val metaInf = sourceRoot / "META-INF" val moduleXml = metaInf / "$moduleName.xml" if (Files.exists(moduleXml)) { _errors.add(PluginValidationError( "Module descriptor must be in the root of module root", mapOf( "module" to moduleName, "moduleDescriptor" to moduleXml, ), )) return } val pluginDescriptorFile = metaInf / "plugin.xml" val pluginDescriptor = pluginDescriptorFile.readXmlAsModel() val moduleDescriptorFile = sourceRoot / "$moduleName.xml" val moduleDescriptor = moduleDescriptorFile.readXmlAsModel() if (pluginDescriptor == null && moduleDescriptor == null) { return } if (fileInfo.pluginDescriptorFile != null && pluginDescriptor != null) { _errors.add(PluginValidationError( "Duplicated plugin.xml", mapOf( "module" to moduleName, "firstPluginDescriptor" to fileInfo.pluginDescriptorFile, "secondPluginDescriptor" to pluginDescriptorFile, ), )) return } if (fileInfo.pluginDescriptorFile != null) { _errors.add(PluginValidationError( "Module cannot have both plugin.xml and module descriptor", mapOf( "module" to moduleName, "pluginDescriptor" to fileInfo.pluginDescriptorFile, "moduleDescriptor" to moduleDescriptorFile, ), )) return } if (fileInfo.moduleDescriptorFile != null && pluginDescriptor != null) { _errors.add(PluginValidationError( "Module cannot have both plugin.xml and module descriptor", mapOf( "module" to moduleName, "pluginDescriptor" to pluginDescriptorFile, "moduleDescriptor" to fileInfo.moduleDescriptorFile, ), )) return } if (pluginDescriptor == null) { fileInfo.moduleDescriptorFile = moduleDescriptorFile fileInfo.moduleDescriptor = moduleDescriptor } else { fileInfo.pluginDescriptorFile = pluginDescriptorFile fileInfo.pluginDescriptor = pluginDescriptor } } } internal data class ModuleInfo( val pluginId: String?, val name: String?, val sourceModuleName: String, val descriptorFile: Path, val packageName: String?, val descriptor: XmlElement, ) { val content = mutableListOf<ModuleInfo>() val dependencies = mutableListOf<Reference>() val isPlugin: Boolean get() = pluginId != null } internal data class Reference(val name: String, val isPlugin: Boolean, val moduleInfo: ModuleInfo) private data class PluginInfo(val pluginId: String, val sourceModuleName: String, val descriptor: XmlElement, val descriptorFile: Path) private class ModuleDescriptorFileInfo(val sourceModule: PluginModelValidator.Module) { var pluginDescriptorFile: Path? = null var moduleDescriptorFile: Path? = null var pluginDescriptor: XmlElement? = null var moduleDescriptor: XmlElement? = null } private fun writeModuleInfo(writer: JsonGenerator, item: ModuleInfo) { writer.obj { writer.writeStringField("name", item.name ?: item.sourceModuleName) writer.writeStringField("package", item.packageName) writer.writeStringField("descriptor", pathToShortString(item.descriptorFile)) if (!item.content.isEmpty()) { writer.array("content") { for (child in item.content) { writeModuleInfo(writer, child) } } } if (!item.dependencies.isEmpty()) { writer.array("dependencies") { writeDependencies(item.dependencies, writer) } } } } internal fun pathToShortString(file: Path): String { return when { file === emptyPath -> "" homePath.fileSystem === file.fileSystem -> homePath.relativize(file).toString() else -> file.toString() } } private fun writeDependencies(items: List<Reference>, writer: JsonGenerator) { for (entry in items) { writer.obj { writer.writeStringField(if (entry.isPlugin) "plugin" else "module", entry.name) } } } private class PluginValidationError private constructor(message: String) : RuntimeException(message) { constructor( message: String, params: Map<String, Any?> = mapOf(), fix: String? = null, ) : this( params.entries.joinToString( prefix = "$message (\n ", separator = ",\n ", postfix = "\n)" + (fix?.let { "\n\nProposed fix:\n\n" + fix.trimIndent() + "\n\n" } ?: "") ) { it.key + "=" + paramValueToString(it.value) } ) } private fun paramValueToString(value: Any?): String { return when (value) { is Path -> pathToShortString(value) else -> value.toString() } } private fun loadFileInModule(sourceModule: PluginModelValidator.Module, fileName: String): ModuleDescriptorFileInfo? { for (sourceRoot in sourceModule.sourceRoots) { val moduleDescriptorFile = sourceRoot / fileName val moduleDescriptor = moduleDescriptorFile.readXmlAsModel() if (moduleDescriptor != null) { return ModuleDescriptorFileInfo(sourceModule).also { it.moduleDescriptor = moduleDescriptor it.moduleDescriptorFile = moduleDescriptorFile } } } return null } private fun Path.readXmlAsModel(): XmlElement? { return try { Files.newInputStream(this).use(::readXmlAsModel) } catch (ignore: NoSuchFileException) { null } } internal fun hasContentOrDependenciesInV2Format(descriptor: XmlElement): Boolean { return descriptor.children.any { it.name == "content" || it.name == "dependencies" } }
apache-2.0
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveSingleExpressionStringTemplateIntention.kt
2
2118
// 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.intentions import com.intellij.openapi.editor.Editor import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.inspections.IntentionBasedInspection import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.KtStringTemplateExpression import org.jetbrains.kotlin.psi.createExpressionByPattern import org.jetbrains.kotlin.resolve.calls.util.getType private fun KtStringTemplateExpression.singleExpressionOrNull() = children.singleOrNull()?.children?.firstOrNull() as? KtExpression class RemoveSingleExpressionStringTemplateInspection : IntentionBasedInspection<KtStringTemplateExpression>( RemoveSingleExpressionStringTemplateIntention::class, additionalChecker = { templateExpression -> templateExpression.singleExpressionOrNull()?.let { KotlinBuiltIns.isString(it.getType(it.analyze())) } ?: false } ) { override val problemText = KotlinBundle.message("redundant.string.template") } class RemoveSingleExpressionStringTemplateIntention : SelfTargetingOffsetIndependentIntention<KtStringTemplateExpression>( KtStringTemplateExpression::class.java, KotlinBundle.lazyMessage("remove.single.expression.string.template") ) { override fun isApplicableTo(element: KtStringTemplateExpression) = element.singleExpressionOrNull() != null override fun applyTo(element: KtStringTemplateExpression, editor: Editor?) { val expression = element.singleExpressionOrNull() ?: return val type = expression.getType(expression.analyze()) val newElement = if (KotlinBuiltIns.isString(type)) expression else KtPsiFactory(element).createExpressionByPattern("$0.$1()", expression, "toString") element.replace(newElement) } }
apache-2.0
jwren/intellij-community
platform/platform-impl/src/com/intellij/openapi/application/rw/cancellableReadAction.kt
1
1891
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("TestOnlyProblems") // KTIJ-19938 package com.intellij.openapi.application.rw import com.intellij.openapi.application.ReadAction.CannotReadException import com.intellij.openapi.application.ex.ApplicationManagerEx import com.intellij.openapi.progress.ensureCurrentJob import com.intellij.openapi.progress.executeWithJobAndCompleteIt import com.intellij.openapi.progress.util.ProgressIndicatorUtils.runActionAndCancelBeforeWrite import kotlinx.coroutines.Job import kotlinx.coroutines.ensureActive import kotlin.coroutines.cancellation.CancellationException internal fun <X> cancellableReadAction(action: () -> X): X = ensureCurrentJob { currentJob -> try { cancellableReadActionInternal(currentJob, action) } catch (e: CancellationException) { throw e.cause as? CannotReadException // cancelled normally by a write action ?: e // exception from the computation } } internal fun <X> cancellableReadActionInternal(currentJob: Job, action: () -> X): X { // A child Job is started to be externally cancellable by a write action without cancelling the current Job. val readJob = Job(parent = currentJob) var resultRef: Value<X>? = null val application = ApplicationManagerEx.getApplicationEx() runActionAndCancelBeforeWrite(application, readJob::cancelReadJob) { readJob.ensureActive() application.tryRunReadAction { readJob.ensureActive() resultRef = Value(executeWithJobAndCompleteIt(readJob, action)) } } val result = resultRef if (result == null) { readJob.ensureActive() error("read job must've been cancelled") } return result.value } private fun Job.cancelReadJob() { cancel(cause = CancellationException(CannotReadException())) } private class Value<T>(val value: T)
apache-2.0
K0zka/kerub
src/main/kotlin/com/github/kerubistan/kerub/services/VmFromTemplateRequest.kt
2
366
package com.github.kerubistan.kerub.services import com.github.kerubistan.kerub.model.AssetOwner import java.util.UUID data class VmFromTemplateRequest( /** * The name of the new VM, or null of automatic name requested - in this case it will come from the template. */ val vmName: String? = null, val templateId: UUID, val owner: AssetOwner? = null )
apache-2.0
stoyicker/dinger
app/src/main/kotlin/app/home/seen/SeenFragment.kt
1
1771
package app.home.seen import android.arch.lifecycle.Observer import android.arch.paging.PagedList import android.arch.paging.PagedListAdapter import android.content.Context import android.os.Bundle import android.support.v4.app.Fragment import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import domain.recommendation.DomainRecommendationUser import domain.seen.SeenRecommendationsViewModel import org.stoyicker.dinger.R import javax.inject.Inject internal class SeenFragment : Fragment() { @Inject lateinit var viewModel: SeenRecommendationsViewModel @Inject lateinit var observer: Observer<PagedList<DomainRecommendationUser>> @Inject lateinit var seenAdapter: PagedListAdapter<DomainRecommendationUser, SeenRecommendationViewHolder> @Inject lateinit var layoutManager: RecyclerView.LayoutManager override fun onCreateView(inflater: LayoutInflater, parent: ViewGroup?, savedInstanceState: Bundle?) = inflater.inflate(R.layout.fragment_seen, parent, false)!! override fun onAttach(context: Context?) { super.onAttach(context) if (context != null) { inject(context) } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { viewModel.filter() .observe(this@SeenFragment, observer) (view as RecyclerView).apply { adapter = seenAdapter layoutManager = [email protected] } } private fun inject(context: Context) = DaggerSeenComponent.builder() .fragment(this) .context(context) .build() .inject(this) companion object { fun newInstance() = SeenFragment() } }
mit
gorrotowi/BitsoPriceChecker
app/src/main/java/com/chilangolabs/bitsopricechecker/models/ItemCoin.kt
1
527
package com.chilangolabs.bitsopricechecker.models import android.support.annotation.DrawableRes /** * @author Gorro * @since 14/06/17 */ data class ItemCoin(val coin: String? = "BTC", val value: String? = "42000", val currency: String? = "MXN", val min: String? = "40200", val max: String? = "42024", val ask: String? = "2134", val bid: String? = "23413", @DrawableRes val bg: Int?)
apache-2.0
kamerok/Orny
app/src/main/kotlin/com/kamer/orny/presentation/addexpense/errors/NoChangesException.kt
1
114
package com.kamer.orny.presentation.addexpense.errors class NoChangesException() : Exception("No changes found")
apache-2.0
taigua/exercism
kotlin/hello-world/src/test/kotlin/HelloWorldTest.kt
1
757
import kotlin.test.assertEquals import org.junit.Test class HelloWorldTest { @Test fun helloNoName() { assertEquals("Hello, World!", HelloWorld.hello()) } @Test fun helloBlankName() { assertEquals("Hello, World!", HelloWorld.hello("")) assertEquals("Hello, World!", HelloWorld.hello(" ")) } @Test fun helloNullName() { //This isn't advised in Kotlin but demonstrates the null safety in Kotlin assertEquals("Hello, World!", HelloWorld.hello(null)) } @Test fun helloSampleName() { assertEquals("Hello, Alice!", HelloWorld.hello("Alice")) } @Test fun helloAnotherSampleName() { assertEquals("Hello, Bob!", HelloWorld.hello("Bob")) } }
mit
pokk/SSFM
app/src/main/kotlin/taiwan/no1/app/ssfm/features/preference/PreferenceItemViewModel.kt
1
1328
package taiwan.no1.app.ssfm.features.preference import android.databinding.ObservableField import android.databinding.ObservableInt import android.view.View import com.devrapid.adaptiverecyclerview.AdaptiveViewHolder import taiwan.no1.app.ssfm.features.base.BaseViewModel import taiwan.no1.app.ssfm.misc.extension.recyclerview.MultipleTypeAdapter import taiwan.no1.app.ssfm.models.entities.PreferenceEntity /** * A [AdaptiveViewHolder] for controlling the main preference items with an option selection. * * @author jieyi * @since 9/8/17 */ class PreferenceItemViewModel(private val adapter: MultipleTypeAdapter, private val position: Int, private val entity: PreferenceEntity) : BaseViewModel() { val title by lazy { ObservableField<String>() } val icon by lazy { ObservableInt() } val selected by lazy { ObservableField<String>() } init { title.set(entity.title) icon.set(entity.icon) selected.set(entity.attributes) } fun onClick(view: View) { val newPosition by lazy { adapter.calculateIndex(position) } if (adapter.isExpanded(newPosition)) { adapter.collapse(position, newPosition) } else { adapter.expand(position, newPosition) } } }
apache-2.0
lnr0626/cfn-templates
aws/src/main/kotlin/com/lloydramey/cfn/model/aws/autoscaling/MetricsCollection.kt
1
758
/* * Copyright 2017 Lloyd Ramey <[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.lloydramey.cfn.model.aws.autoscaling data class MetricsCollection(val granularity: String, val metrics: List<String> = emptyList())
apache-2.0
OnyxDevTools/onyx-database-parent
onyx-database-tests/src/main/kotlin/streams/BasicQueryStream.kt
1
524
package streams import com.onyx.persistence.manager.PersistenceManager import com.onyx.persistence.stream.QueryStream import entities.identifiers.ImmutableSequenceIdentifierEntityForDelete /** * Created by Tim Osborn on 7/14/16. */ class BasicQueryStream : QueryStream<ImmutableSequenceIdentifierEntityForDelete> { override fun accept(entity: ImmutableSequenceIdentifierEntityForDelete, persistenceManager: PersistenceManager) { entity.correlation = 99 persistenceManager.saveEntity(entity) } }
agpl-3.0
GunoH/intellij-community
platform/workspaceModel/storage/gen/com/intellij/workspaceModel/storage/bridgeEntities/ContentRootEntityImpl.kt
2
21236
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.workspaceModel.storage.bridgeEntities import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.EntityLink import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.containers.MutableWorkspaceList import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList import com.intellij.workspaceModel.storage.impl.extractOneToManyChildren import com.intellij.workspaceModel.storage.impl.extractOneToManyParent import com.intellij.workspaceModel.storage.impl.extractOneToOneChild import com.intellij.workspaceModel.storage.impl.updateOneToManyChildrenOfParent import com.intellij.workspaceModel.storage.impl.updateOneToManyParentOfChild import com.intellij.workspaceModel.storage.impl.updateOneToOneChildOfParent import com.intellij.workspaceModel.storage.url.VirtualFileUrl import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class ContentRootEntityImpl(val dataSource: ContentRootEntityData) : ContentRootEntity, WorkspaceEntityBase() { companion object { internal val MODULE_CONNECTION_ID: ConnectionId = ConnectionId.create(ModuleEntity::class.java, ContentRootEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, false) internal val EXCLUDEDURLS_CONNECTION_ID: ConnectionId = ConnectionId.create(ContentRootEntity::class.java, ExcludeUrlEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, true) internal val SOURCEROOTS_CONNECTION_ID: ConnectionId = ConnectionId.create(ContentRootEntity::class.java, SourceRootEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, false) internal val SOURCEROOTORDER_CONNECTION_ID: ConnectionId = ConnectionId.create(ContentRootEntity::class.java, SourceRootOrderEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ONE, false) val connections = listOf<ConnectionId>( MODULE_CONNECTION_ID, EXCLUDEDURLS_CONNECTION_ID, SOURCEROOTS_CONNECTION_ID, SOURCEROOTORDER_CONNECTION_ID, ) } override val module: ModuleEntity get() = snapshot.extractOneToManyParent(MODULE_CONNECTION_ID, this)!! override val url: VirtualFileUrl get() = dataSource.url override val excludedUrls: List<ExcludeUrlEntity> get() = snapshot.extractOneToManyChildren<ExcludeUrlEntity>(EXCLUDEDURLS_CONNECTION_ID, this)!!.toList() override val excludedPatterns: List<String> get() = dataSource.excludedPatterns override val sourceRoots: List<SourceRootEntity> get() = snapshot.extractOneToManyChildren<SourceRootEntity>(SOURCEROOTS_CONNECTION_ID, this)!!.toList() override val sourceRootOrder: SourceRootOrderEntity? get() = snapshot.extractOneToOneChild(SOURCEROOTORDER_CONNECTION_ID, this) override val entitySource: EntitySource get() = dataSource.entitySource override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(result: ContentRootEntityData?) : ModifiableWorkspaceEntityBase<ContentRootEntity, ContentRootEntityData>( result), ContentRootEntity.Builder { constructor() : this(ContentRootEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity ContentRootEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // After adding entity data to the builder, we need to unbind it and move the control over entity data to builder // Builder may switch to snapshot at any moment and lock entity data to modification this.currentEntityData = null index(this, "url", this.url) // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } if (_diff != null) { if (_diff.extractOneToManyParent<WorkspaceEntityBase>(MODULE_CONNECTION_ID, this) == null) { error("Field ContentRootEntity#module should be initialized") } } else { if (this.entityLinks[EntityLink(false, MODULE_CONNECTION_ID)] == null) { error("Field ContentRootEntity#module should be initialized") } } if (!getEntityData().isUrlInitialized()) { error("Field ContentRootEntity#url should be initialized") } // Check initialization for list with ref type if (_diff != null) { if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(EXCLUDEDURLS_CONNECTION_ID, this) == null) { error("Field ContentRootEntity#excludedUrls should be initialized") } } else { if (this.entityLinks[EntityLink(true, EXCLUDEDURLS_CONNECTION_ID)] == null) { error("Field ContentRootEntity#excludedUrls should be initialized") } } if (!getEntityData().isExcludedPatternsInitialized()) { error("Field ContentRootEntity#excludedPatterns should be initialized") } // Check initialization for list with ref type if (_diff != null) { if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(SOURCEROOTS_CONNECTION_ID, this) == null) { error("Field ContentRootEntity#sourceRoots should be initialized") } } else { if (this.entityLinks[EntityLink(true, SOURCEROOTS_CONNECTION_ID)] == null) { error("Field ContentRootEntity#sourceRoots should be initialized") } } } override fun connectionIdList(): List<ConnectionId> { return connections } override fun afterModification() { val collection_excludedPatterns = getEntityData().excludedPatterns if (collection_excludedPatterns is MutableWorkspaceList<*>) { collection_excludedPatterns.cleanModificationUpdateAction() } } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as ContentRootEntity if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource if (this.url != dataSource.url) this.url = dataSource.url if (this.excludedPatterns != dataSource.excludedPatterns) this.excludedPatterns = dataSource.excludedPatterns.toMutableList() if (parents != null) { val moduleNew = parents.filterIsInstance<ModuleEntity>().single() if ((this.module as WorkspaceEntityBase).id != (moduleNew as WorkspaceEntityBase).id) { this.module = moduleNew } } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData(true).entitySource = value changedProperty.add("entitySource") } override var module: ModuleEntity get() { val _diff = diff return if (_diff != null) { _diff.extractOneToManyParent(MODULE_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, MODULE_CONNECTION_ID)]!! as ModuleEntity } else { this.entityLinks[EntityLink(false, MODULE_CONNECTION_ID)]!! as ModuleEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*, *> && value.diff == null) { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*, *>) { val data = (value.entityLinks[EntityLink(true, MODULE_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, MODULE_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*, *> || value.diff != null)) { _diff.updateOneToManyParentOfChild(MODULE_CONNECTION_ID, this, value) } else { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*, *>) { val data = (value.entityLinks[EntityLink(true, MODULE_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, MODULE_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(false, MODULE_CONNECTION_ID)] = value } changedProperty.add("module") } override var url: VirtualFileUrl get() = getEntityData().url set(value) { checkModificationAllowed() getEntityData(true).url = value changedProperty.add("url") val _diff = diff if (_diff != null) index(this, "url", value) } // List of non-abstract referenced types var _excludedUrls: List<ExcludeUrlEntity>? = emptyList() override var excludedUrls: List<ExcludeUrlEntity> get() { // Getter of the list of non-abstract referenced types val _diff = diff return if (_diff != null) { _diff.extractOneToManyChildren<ExcludeUrlEntity>(EXCLUDEDURLS_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(true, EXCLUDEDURLS_CONNECTION_ID)] as? List<ExcludeUrlEntity> ?: emptyList()) } else { this.entityLinks[EntityLink(true, EXCLUDEDURLS_CONNECTION_ID)] as? List<ExcludeUrlEntity> ?: emptyList() } } set(value) { // Setter of the list of non-abstract referenced types checkModificationAllowed() val _diff = diff if (_diff != null) { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*, *> && (item_value as? ModifiableWorkspaceEntityBase<*, *>)?.diff == null) { // Backref setup before adding to store if (item_value is ModifiableWorkspaceEntityBase<*, *>) { item_value.entityLinks[EntityLink(false, EXCLUDEDURLS_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(item_value) } } _diff.updateOneToManyChildrenOfParent(EXCLUDEDURLS_CONNECTION_ID, this, value) } else { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*, *>) { item_value.entityLinks[EntityLink(false, EXCLUDEDURLS_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable } this.entityLinks[EntityLink(true, EXCLUDEDURLS_CONNECTION_ID)] = value } changedProperty.add("excludedUrls") } private val excludedPatternsUpdater: (value: List<String>) -> Unit = { value -> changedProperty.add("excludedPatterns") } override var excludedPatterns: MutableList<String> get() { val collection_excludedPatterns = getEntityData().excludedPatterns if (collection_excludedPatterns !is MutableWorkspaceList) return collection_excludedPatterns if (diff == null || modifiable.get()) { collection_excludedPatterns.setModificationUpdateAction(excludedPatternsUpdater) } else { collection_excludedPatterns.cleanModificationUpdateAction() } return collection_excludedPatterns } set(value) { checkModificationAllowed() getEntityData(true).excludedPatterns = value excludedPatternsUpdater.invoke(value) } // List of non-abstract referenced types var _sourceRoots: List<SourceRootEntity>? = emptyList() override var sourceRoots: List<SourceRootEntity> get() { // Getter of the list of non-abstract referenced types val _diff = diff return if (_diff != null) { _diff.extractOneToManyChildren<SourceRootEntity>(SOURCEROOTS_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(true, SOURCEROOTS_CONNECTION_ID)] as? List<SourceRootEntity> ?: emptyList()) } else { this.entityLinks[EntityLink(true, SOURCEROOTS_CONNECTION_ID)] as? List<SourceRootEntity> ?: emptyList() } } set(value) { // Setter of the list of non-abstract referenced types checkModificationAllowed() val _diff = diff if (_diff != null) { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*, *> && (item_value as? ModifiableWorkspaceEntityBase<*, *>)?.diff == null) { // Backref setup before adding to store if (item_value is ModifiableWorkspaceEntityBase<*, *>) { item_value.entityLinks[EntityLink(false, SOURCEROOTS_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(item_value) } } _diff.updateOneToManyChildrenOfParent(SOURCEROOTS_CONNECTION_ID, this, value) } else { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*, *>) { item_value.entityLinks[EntityLink(false, SOURCEROOTS_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable } this.entityLinks[EntityLink(true, SOURCEROOTS_CONNECTION_ID)] = value } changedProperty.add("sourceRoots") } override var sourceRootOrder: SourceRootOrderEntity? get() { val _diff = diff return if (_diff != null) { _diff.extractOneToOneChild(SOURCEROOTORDER_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true, SOURCEROOTORDER_CONNECTION_ID)] as? SourceRootOrderEntity } else { this.entityLinks[EntityLink(true, SOURCEROOTORDER_CONNECTION_ID)] as? SourceRootOrderEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*, *> && value.diff == null) { if (value is ModifiableWorkspaceEntityBase<*, *>) { value.entityLinks[EntityLink(false, SOURCEROOTORDER_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*, *> || value.diff != null)) { _diff.updateOneToOneChildOfParent(SOURCEROOTORDER_CONNECTION_ID, this, value) } else { if (value is ModifiableWorkspaceEntityBase<*, *>) { value.entityLinks[EntityLink(false, SOURCEROOTORDER_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(true, SOURCEROOTORDER_CONNECTION_ID)] = value } changedProperty.add("sourceRootOrder") } override fun getEntityClass(): Class<ContentRootEntity> = ContentRootEntity::class.java } } class ContentRootEntityData : WorkspaceEntityData<ContentRootEntity>() { lateinit var url: VirtualFileUrl lateinit var excludedPatterns: MutableList<String> fun isUrlInitialized(): Boolean = ::url.isInitialized fun isExcludedPatternsInitialized(): Boolean = ::excludedPatterns.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<ContentRootEntity> { val modifiable = ContentRootEntityImpl.Builder(null) modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() return modifiable } override fun createEntity(snapshot: EntityStorage): ContentRootEntity { return getCached(snapshot) { val entity = ContentRootEntityImpl(this) entity.snapshot = snapshot entity.id = createEntityId() entity } } override fun clone(): ContentRootEntityData { val clonedEntity = super.clone() clonedEntity as ContentRootEntityData clonedEntity.excludedPatterns = clonedEntity.excludedPatterns.toMutableWorkspaceList() return clonedEntity } override fun getEntityInterface(): Class<out WorkspaceEntity> { return ContentRootEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return ContentRootEntity(url, excludedPatterns, entitySource) { this.module = parents.filterIsInstance<ModuleEntity>().single() } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() res.add(ModuleEntity::class.java) return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as ContentRootEntityData if (this.entitySource != other.entitySource) return false if (this.url != other.url) return false if (this.excludedPatterns != other.excludedPatterns) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as ContentRootEntityData if (this.url != other.url) return false if (this.excludedPatterns != other.excludedPatterns) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + url.hashCode() result = 31 * result + excludedPatterns.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + url.hashCode() result = 31 * result + excludedPatterns.hashCode() return result } override fun equalsByKey(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as ContentRootEntityData if (this.url != other.url) return false return true } override fun hashCodeByKey(): Int { var result = javaClass.hashCode() result = 31 * result + url.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { this.url?.let { collector.add(it::class.java) } this.excludedPatterns?.let { collector.add(it::class.java) } collector.sameForAllEntities = false } }
apache-2.0
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/quickfix/autoImports/unaryMinusOperator.before.Main.kt
3
159
// "Import extension function 'H.unaryMinus'" "true" // ERROR: Unresolved reference: - package h interface H fun f(h: H?) { <caret>-h } /* IGNORE_FIR */
apache-2.0
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/FoldIfToFunctionCallIntention.kt
2
6912
// Copyright 2000-2021 JetBrains s.r.o. 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.intentions.branchedTransformations.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.util.reformatted import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention import org.jetbrains.kotlin.idea.intentions.* import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelectorOrThis import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.calls.model.ArgumentMatch import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class FoldIfToFunctionCallIntention : SelfTargetingRangeIntention<KtIfExpression>( KtIfExpression::class.java, KotlinBundle.lazyMessage("lift.function.call.out.of.if"), ) { override fun applicabilityRange(element: KtIfExpression): TextRange? = if (canFoldToFunctionCall(element)) element.ifKeyword.textRange else null override fun applyTo(element: KtIfExpression, editor: Editor?) { foldToFunctionCall(element) } companion object { fun branches(expression: KtExpression): List<KtExpression>? { val branches = when (expression) { is KtIfExpression -> expression.branches is KtWhenExpression -> expression.entries.map { it.expression } else -> emptyList() } val branchesSize = branches.size if (branchesSize < 2) return null return branches.filterNotNull().takeIf { it.size == branchesSize } } private fun canFoldToFunctionCall(element: KtExpression): Boolean { val branches = branches(element) ?: return false val callExpressions = branches.mapNotNull { it.callExpression() } if (branches.size != callExpressions.size) return false if (differentArgumentIndex(callExpressions) == null) return false val headCall = callExpressions.first() val tailCalls = callExpressions.drop(1) val context = headCall.analyze(BodyResolveMode.PARTIAL) val (headFunctionFqName, headFunctionParameters) = headCall.fqNameAndParameters(context) ?: return false return tailCalls.all { call -> val (fqName, parameters) = call.fqNameAndParameters(context) ?: return@all false fqName == headFunctionFqName && parameters.zip(headFunctionParameters).all { it.first == it.second } } } private fun foldToFunctionCall(element: KtExpression) { val branches = branches(element) ?: return val callExpressions = branches.mapNotNull { it.callExpression() } val headCall = callExpressions.first() val argumentIndex = differentArgumentIndex(callExpressions) ?: return val hasNamedArgument = callExpressions.any { call -> call.valueArguments.any { it.getArgumentName() != null } } val copiedIf = element.copy() as KtIfExpression copiedIf.branches.forEach { branch -> val call = branch.callExpression() ?: return val argument = call.valueArguments[argumentIndex].getArgumentExpression() ?: return call.getQualifiedExpressionForSelectorOrThis().replace(argument) } headCall.valueArguments[argumentIndex].getArgumentExpression()?.replace(copiedIf) if (hasNamedArgument) { headCall.valueArguments.forEach { if (it.getArgumentName() == null) AddNameToArgumentIntention.apply(it, givenResolvedCall = null) } } element.replace(headCall.getQualifiedExpressionForSelectorOrThis()).reformatted() } private fun differentArgumentIndex(callExpressions: List<KtCallExpression>): Int? { val headCall = callExpressions.first() val headCalleeText = headCall.calleeText() val tailCalls = callExpressions.drop(1) if (headCall.valueArguments.any { it is KtLambdaArgument }) return null val headArguments = headCall.valueArguments.mapNotNull { it.getArgumentExpression()?.text } val headArgumentsSize = headArguments.size if (headArgumentsSize != headCall.valueArguments.size) return null val differentArgumentIndexes = tailCalls.mapNotNull { call -> if (call.calleeText() != headCalleeText) return@mapNotNull null val arguments = call.valueArguments.mapNotNull { it.getArgumentExpression()?.text } if (arguments.size != headArgumentsSize) return@mapNotNull null val differentArgumentIndexes = arguments.zip(headArguments).mapIndexedNotNull { index, (arg, headArg) -> if (arg != headArg) index else null } differentArgumentIndexes.singleOrNull() } if (differentArgumentIndexes.size != tailCalls.size || differentArgumentIndexes.distinct().size != 1) return null return differentArgumentIndexes.first() } private fun KtExpression?.callExpression(): KtCallExpression? { return when (val expression = if (this is KtBlockExpression) statements.singleOrNull() else this) { is KtCallExpression -> expression is KtQualifiedExpression -> expression.callExpression else -> null }?.takeIf { it.calleeExpression != null } } private fun KtCallExpression.calleeText(): String { val parent = this.parent val (receiver, op) = if (parent is KtQualifiedExpression) { parent.receiverExpression.text to parent.operationSign.value } else { "" to "" } return "$receiver$op${calleeExpression?.text.orEmpty()}" } private fun KtCallExpression.fqNameAndParameters(context: BindingContext): Pair<FqName, List<ValueParameterDescriptor>>? { val resolvedCall = getResolvedCall(context) ?: return null val fqName = resolvedCall.resultingDescriptor.fqNameOrNull() ?: return null val parameters = valueArguments.mapNotNull { (resolvedCall.getArgumentMapping(it) as? ArgumentMatch)?.valueParameter } return fqName to parameters } } }
apache-2.0
siosio/intellij-community
platform/platform-impl/src/com/intellij/application/options/editor/fonts/AppEditorFontOptionsPanel.kt
1
9215
// 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 com.intellij.application.options.editor.fonts import com.intellij.application.options.colors.AbstractFontOptionsPanel import com.intellij.application.options.colors.ColorAndFontOptions import com.intellij.application.options.colors.ColorAndFontSettingsListener import com.intellij.ide.DataManager import com.intellij.openapi.application.ApplicationBundle import com.intellij.openapi.editor.colors.EditorColorsScheme import com.intellij.openapi.editor.colors.FontPreferences import com.intellij.openapi.editor.colors.ModifiableFontPreferences import com.intellij.openapi.editor.colors.impl.AppEditorFontOptions import com.intellij.openapi.editor.colors.impl.FontPreferencesImpl import com.intellij.openapi.editor.impl.FontFamilyService import com.intellij.openapi.options.Configurable import com.intellij.openapi.options.OptionsBundle import com.intellij.openapi.options.colors.pages.GeneralColorsPage import com.intellij.openapi.options.ex.Settings import com.intellij.openapi.ui.DialogPanel import com.intellij.ui.AbstractFontCombo import com.intellij.ui.components.ActionLink import com.intellij.ui.layout.* import com.intellij.util.ObjectUtils import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import java.awt.Dimension import java.util.function.Consumer import javax.swing.JComponent class AppEditorFontOptionsPanel(private val scheme: EditorColorsScheme) : AbstractFontOptionsPanel() { private val defaultPreferences = FontPreferencesImpl() private lateinit var restoreDefaults: ActionLink private var regularWeightCombo: FontWeightCombo? = null private var boldWeightCombo: FontWeightCombo? = null init { addListener(object : ColorAndFontSettingsListener.Abstract() { override fun fontChanged() { updateFontPreferences() } }) AppEditorFontOptions.initDefaults(defaultPreferences) updateOptionsList() } override fun isReadOnly(): Boolean { return false } override fun isDelegating(): Boolean { return false } override fun getFontPreferences(): FontPreferences { return scheme.fontPreferences } override fun setFontSize(fontSize: Int) { scheme.editorFontSize = fontSize } override fun getLineSpacing(): Float { return scheme.lineSpacing } override fun setCurrentLineSpacing(lineSpacing: Float) { scheme.lineSpacing = lineSpacing } override fun createPrimaryFontCombo(): AbstractFontCombo<*>? { return if (isAdvancedFontFamiliesUI()) { FontFamilyCombo(true) } else { super.createPrimaryFontCombo() } } override fun createSecondaryFontCombo(): AbstractFontCombo<*>? { return if (isAdvancedFontFamiliesUI()) { FontFamilyCombo(false) } else { super.createSecondaryFontCombo() } } fun updateOnChangedFont() { updateOptionsList() fireFontChanged() } private fun restoreDefaults() { AppEditorFontOptions.initDefaults(fontPreferences as ModifiableFontPreferences) updateOnChangedFont() } override fun createControls(): JComponent { return panel { row(primaryLabel) { component(primaryCombo) } row(sizeLabel) { component(editorFontSizeField) component(lineSpacingLabel).withLargeLeftGap() component(lineSpacingField) } fullRow { component(enableLigaturesCheckbox) component(enableLigaturesHintLabel).withLeftGap() } row { hyperlink(ApplicationBundle.message("comment.use.ligatures.with.reader.mode"), style = UIUtil.ComponentStyle.SMALL, color = UIUtil.getLabelFontColor(UIUtil.FontColor.BRIGHTER)) { goToReaderMode() } } row { restoreDefaults = ActionLink(ApplicationBundle.message("settings.editor.font.restored.defaults")) { restoreDefaults() } component(restoreDefaults) } row { component(createTypographySettings()) } }.withBorder(JBUI.Borders.empty(BASE_INSET)) } fun updateFontPreferences() { restoreDefaults.isEnabled = defaultPreferences != fontPreferences regularWeightCombo?.apply { update(fontPreferences) } boldWeightCombo?.apply { update(fontPreferences) } } private fun createTypographySettings(): DialogPanel { return panel { hideableRow(ApplicationBundle.message("settings.editor.font.typography.settings"), incrementsIndent = false) { if (isAdvancedFontFamiliesUI()) { row(ApplicationBundle.message("settings.editor.font.main.weight")) { val component = createRegularWeightCombo() regularWeightCombo = component component(component) } row(ApplicationBundle.message("settings.editor.font.bold.weight")) { val component = createBoldWeightCombo() boldWeightCombo = component component(component) } row("") { hyperlink(ApplicationBundle.message("settings.editor.font.bold.weight.hint"), style = UIUtil.ComponentStyle.SMALL, color = UIUtil.getContextHelpForeground()) { navigateToColorSchemeTextSettings() } } // .largeGapAfter() doesn't work now } row { val secondaryFont = label(ApplicationBundle.message("secondary.font")) setSecondaryFontLabel(secondaryFont.component) component(secondaryCombo) } row("") { val description = label(ApplicationBundle.message("label.fallback.fonts.list.description"), style = UIUtil.ComponentStyle.SMALL) description.component.foreground = UIUtil.getContextHelpForeground() } } } } private fun navigateToColorSchemeTextSettings() { var defaultTextOption = OptionsBundle.message("options.general.attribute.descriptor.default.text") val separator = "//" val separatorPos = defaultTextOption.lastIndexOf(separator) if (separatorPos > 0) { defaultTextOption = defaultTextOption.substring(separatorPos + separator.length) } val allSettings = Settings.KEY.getData(DataManager.getInstance().getDataContext(this)) if (allSettings != null) { val colorSchemeConfigurable = allSettings.find(ColorAndFontOptions.ID) if (colorSchemeConfigurable is ColorAndFontOptions) { val generalSettings: Configurable? = colorSchemeConfigurable.findSubConfigurable(GeneralColorsPage.getDisplayNameText()) if (generalSettings != null) { allSettings.select(generalSettings, defaultTextOption) } } } } private fun createRegularWeightCombo(): FontWeightCombo { val result = RegularFontWeightCombo() fixComboWidth(result) result.addActionListener { changeFontPreferences { preferences: ModifiableFontPreferences -> val newSubFamily = result.selectedSubFamily if (preferences.regularSubFamily != newSubFamily) { preferences.boldSubFamily = null // Reset bold subfamily for a different regular } preferences.regularSubFamily = newSubFamily } } return result } private fun createBoldWeightCombo(): FontWeightCombo { val result = BoldFontWeightCombo() fixComboWidth(result) result.addActionListener { changeFontPreferences { preferences: ModifiableFontPreferences -> preferences.boldSubFamily = result.selectedSubFamily } } return result } private fun changeFontPreferences(consumer: Consumer<ModifiableFontPreferences>) { val preferences = fontPreferences assert(preferences is ModifiableFontPreferences) consumer.accept(preferences as ModifiableFontPreferences) fireFontChanged() } private class RegularFontWeightCombo : FontWeightCombo(false) { public override fun getSubFamily(preferences: FontPreferences): String? { return preferences.regularSubFamily } public override fun getRecommendedSubFamily(family: String): String { return FontFamilyService.getRecommendedSubFamily(family) } } private inner class BoldFontWeightCombo : FontWeightCombo(true) { public override fun getSubFamily(preferences: FontPreferences): String? { return preferences.boldSubFamily } public override fun getRecommendedSubFamily(family: String): String { return FontFamilyService.getRecommendedBoldSubFamily( family, ObjectUtils.notNull(regularWeightCombo?.selectedSubFamily, FontFamilyService.getRecommendedSubFamily(family))) } } } private fun isAdvancedFontFamiliesUI(): Boolean { return AppEditorFontOptions.NEW_FONT_SELECTOR } private const val FONT_WEIGHT_COMBO_WIDTH = 250 private fun fixComboWidth(combo: FontWeightCombo) { val width = JBUI.scale(FONT_WEIGHT_COMBO_WIDTH) with(combo) { minimumSize = Dimension(width, 0) maximumSize = Dimension(width, Int.MAX_VALUE) preferredSize = Dimension(width, preferredSize.height) } }
apache-2.0
jwren/intellij-community
java/java-tests/testSrc/com/intellij/java/execution/ExternalSystemRunConfigurationJavaExtensionTest.kt
3
3931
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.java.execution import com.intellij.execution.ExecutionException import com.intellij.execution.RunConfigurationExtension import com.intellij.execution.configurations.JavaParameters import com.intellij.execution.configurations.RunConfigurationBase import com.intellij.execution.configurations.RunnerSettings import com.intellij.execution.executors.DefaultRunExecutor import com.intellij.execution.impl.FakeConfigurationFactory import com.intellij.execution.process.ProcessHandler import com.intellij.execution.runners.ExecutionEnvironmentBuilder import com.intellij.notification.Notification import com.intellij.notification.NotificationsManager import com.intellij.openapi.externalSystem.model.ProjectSystemId import com.intellij.openapi.externalSystem.service.execution.ExternalSystemRunConfiguration import com.intellij.testFramework.ExtensionTestUtil import com.intellij.testFramework.LoggedErrorProcessor import com.intellij.testFramework.runInEdtAndWait import org.hamcrest.CoreMatchers.containsString import org.hamcrest.CoreMatchers.hasItem import org.junit.Assert.assertThat class ExternalSystemRunConfigurationJavaExtensionTest : RunConfigurationJavaExtensionManagerTestCase() { override fun getTestAppPath(): String = "" override fun setUpModule() { // do nothing } fun `test ExecutionException thrown from RunConfigurationExtension#updateJavaParameters should terminate execution`() { ExtensionTestUtil.maskExtensions(RunConfigurationExtension.EP_NAME, listOf(CantUpdateJavaParametersExtension()), testRootDisposable) val configuration = createExternalSystemRunConfiguration() LoggedErrorProcessor.executeWith<RuntimeException>(object : LoggedErrorProcessor() { override fun processError(category: String, message: String?, t: Throwable?, details: Array<out String>): Boolean = t !is FakeExecutionException // don't fail this if `LOG.error()` was called for our exception somewhere }) { runInEdtAndWait { ExecutionEnvironmentBuilder.create(DefaultRunExecutor.getRunExecutorInstance(), configuration).buildAndExecute() } val notifications = NotificationsManager.getNotificationsManager().getNotificationsOfType(Notification::class.java, project) .map { it.content } assertThat(notifications, hasItem(containsString(FakeExecutionException.MESSAGE))) } } fun `test only applicable configuration extensions should be processed`() { doTestOnlyApplicableConfigurationExtensionsShouldBeProcessed(createExternalSystemRunConfiguration()) } private fun createExternalSystemRunConfiguration() = ExternalSystemRunConfiguration(ProjectSystemId("FakeExternalSystem"), project, FakeConfigurationFactory(), "FakeConfiguration").apply { settings.externalProjectPath = "" // any string to prevent NPE } private companion object { class CantUpdateJavaParametersExtension : RunConfigurationExtension() { override fun isApplicableFor(configuration: RunConfigurationBase<*>): Boolean = true override fun <T : RunConfigurationBase<*>?> updateJavaParameters(configuration: T, params: JavaParameters, runnerSettings: RunnerSettings?) { throw FakeExecutionException() } override fun attachToProcess(configuration: RunConfigurationBase<*>, handler: ProcessHandler, runnerSettings: RunnerSettings?) { // 'attachToProcess' is called after 'updateJavaParameters' fail("Should not be here") } } class FakeExecutionException : ExecutionException(MESSAGE) { companion object { const val MESSAGE = "Fake Execution Exception" } } } }
apache-2.0
jwren/intellij-community
plugins/kotlin/base/indices/src/org/jetbrains/kotlin/idea/stubindex/KotlinExtensionsInObjectsByReceiverTypeIndex.kt
4
662
// 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.stubindex import com.intellij.psi.stubs.StubIndexKey import org.jetbrains.kotlin.psi.KtCallableDeclaration object KotlinExtensionsInObjectsByReceiverTypeIndex : KotlinExtensionsByReceiverTypeIndex() { private val KEY: StubIndexKey<String, KtCallableDeclaration> = StubIndexKey.createIndexKey("org.jetbrains.kotlin.idea.stubindex.KotlinExtensionsInObjectsByReceiverTypeIndex") override fun getKey(): StubIndexKey<String, KtCallableDeclaration> = KEY }
apache-2.0
jwren/intellij-community
plugins/kotlin/idea/tests/testData/codeInsight/lineMarker/runMarkers/jUnit3TestFileWithJUnit4.kt
5
822
// CONFIGURE_LIBRARY: JUnit3 // CONFIGURE_LIBRARY: JUnit4 package testing import junit.framework.TestCase import java.awt.event.ActionEvent import javax.swing.AbstractAction import javax.swing.Action abstract class <lineMarker descr="Run Test" icon="runConfigurations/testState/run_run.svg"><lineMarker descr="*">AbstractSessionTest</lineMarker></lineMarker>: TestCase() {// LIGHT_CLASS_FALLBACK } class <lineMarker descr="Run Test" icon="runConfigurations/testState/run_run.svg">SessionTest</lineMarker>: AbstractSessionTest() { // LIGHT_CLASS_FALLBACK fun <lineMarker descr="Run Test" icon="runConfigurations/testState/run.svg">testSessionCreateDelete</lineMarker>() { // LIGHT_CLASS_FALLBACK } } fun String.foo() {} class EmptySession data class TestUserSession(val userId: String, val cart: List<String>)
apache-2.0
jwren/intellij-community
plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/quickfix/ChangeVariableMutabilityFix.kt
3
4496
// 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.quickfix import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.lexer.KtModifierKeywordToken import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType class ChangeVariableMutabilityFix( element: KtValVarKeywordOwner, private val makeVar: Boolean, private val actionText: String? = null, private val deleteInitializer: Boolean = false ) : KotlinPsiOnlyQuickFixAction<KtValVarKeywordOwner>(element) { override fun getText() = actionText ?: (if (makeVar) KotlinBundle.message("change.to.var") else KotlinBundle.message("change.to.val")) + if (deleteInitializer) KotlinBundle.message("and.delete.initializer") else "" override fun getFamilyName(): String = text override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean { val element = element ?: return false val valOrVar = element.valOrVarKeyword?.node?.elementType ?: return false return (valOrVar == KtTokens.VAR_KEYWORD) != makeVar } override fun invoke(project: Project, editor: Editor?, file: KtFile) { val element = element ?: return val factory = KtPsiFactory(project) val newKeyword = if (makeVar) factory.createVarKeyword() else factory.createValKeyword() element.valOrVarKeyword!!.replace(newKeyword) if (deleteInitializer) { (element as? KtProperty)?.initializer = null } if (makeVar) { (element as? KtModifierListOwner)?.removeModifier(KtTokens.CONST_KEYWORD) } } companion object { val VAL_WITH_SETTER_FACTORY: QuickFixesPsiBasedFactory<KtPropertyAccessor> = quickFixesPsiBasedFactory { psiElement: KtPropertyAccessor -> listOf(ChangeVariableMutabilityFix(psiElement.property, true)) } val VAR_OVERRIDDEN_BY_VAL_FACTORY: QuickFixesPsiBasedFactory<PsiElement> = quickFixesPsiBasedFactory { psiElement: PsiElement -> when (psiElement) { is KtProperty, is KtParameter -> listOf(ChangeVariableMutabilityFix(psiElement as KtValVarKeywordOwner, true)) else -> emptyList() } } val VAR_ANNOTATION_PARAMETER_FACTORY: QuickFixesPsiBasedFactory<KtParameter> = quickFixesPsiBasedFactory { psiElement: KtParameter -> listOf(ChangeVariableMutabilityFix(psiElement, false)) } val LATEINIT_VAL_FACTORY: QuickFixesPsiBasedFactory<KtModifierListOwner> = quickFixesPsiBasedFactory { psiElement: KtModifierListOwner -> val property = psiElement as? KtProperty ?: return@quickFixesPsiBasedFactory emptyList() if (property.valOrVarKeyword.text != "val") { emptyList() } else { listOf(ChangeVariableMutabilityFix(property, makeVar = true)) } } val CONST_VAL_FACTORY: QuickFixesPsiBasedFactory<PsiElement> = quickFixesPsiBasedFactory { psiElement: PsiElement -> if (psiElement.node.elementType as? KtModifierKeywordToken != KtTokens.CONST_KEYWORD) return@quickFixesPsiBasedFactory emptyList() val property = psiElement.getStrictParentOfType<KtProperty>() ?: return@quickFixesPsiBasedFactory emptyList() listOf(ChangeVariableMutabilityFix(property, makeVar = false)) } val MUST_BE_INITIALIZED_FACTORY: QuickFixesPsiBasedFactory<PsiElement> = quickFixesPsiBasedFactory { psiElement: PsiElement -> val property = psiElement as? KtProperty ?: return@quickFixesPsiBasedFactory emptyList() val getter = property.getter ?: return@quickFixesPsiBasedFactory emptyList() if (!getter.hasBody()) return@quickFixesPsiBasedFactory emptyList() if (getter.hasBlockBody() && property.typeReference == null) return@quickFixesPsiBasedFactory emptyList() listOf(ChangeVariableMutabilityFix(property, makeVar = false)) } } }
apache-2.0
JetBrains/kotlin-native
backend.native/tests/codegen/inline/inline1.kt
4
459
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ package codegen.inline.inline1 import kotlin.test.* @Suppress("NOTHING_TO_INLINE") inline fun foo(s4: String, s5: String): String { return s4 + s5 } fun bar(s1: String, s2: String, s3: String): String { return s1 + foo(s2, s3) } @Test fun runTest() { println(bar("Hello ", "wor", "ld")) }
apache-2.0
GunoH/intellij-community
plugins/kotlin/base/scripting/src/org/jetbrains/kotlin/idea/core/script/KotlinScriptExternalLibrariesNodesProvider.kt
1
3221
// 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 import com.intellij.ide.projectView.ViewSettings import com.intellij.ide.projectView.impl.nodes.ExternalLibrariesWorkspaceModelNodesProvider import com.intellij.ide.projectView.impl.nodes.SyntheticLibraryElementNode import com.intellij.ide.util.treeView.AbstractTreeNode import com.intellij.navigation.ItemPresentation import com.intellij.openapi.project.Project import com.intellij.openapi.roots.SyntheticLibrary import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.workspaceModel.ide.impl.virtualFile import com.intellij.workspaceModel.storage.bridgeEntities.LibraryRoot import com.intellij.workspaceModel.storage.bridgeEntities.LibraryRootTypeId import org.jetbrains.kotlin.idea.KotlinIcons import org.jetbrains.kotlin.idea.core.script.ucache.KotlinScriptEntity import org.jetbrains.kotlin.idea.core.script.ucache.relativeName import org.jetbrains.kotlin.idea.core.script.ucache.scriptsAsEntities import java.nio.file.Path import javax.swing.Icon class KotlinScriptExternalLibrariesNodesProvider: ExternalLibrariesWorkspaceModelNodesProvider<KotlinScriptEntity> { override fun getWorkspaceClass(): Class<KotlinScriptEntity> = KotlinScriptEntity::class.java override fun createNode(entity: KotlinScriptEntity, project: Project, settings: ViewSettings?): AbstractTreeNode<*>? { if (!scriptsAsEntities) return null val dependencies = entity.listDependencies() val scriptFile = VirtualFileManager.getInstance().findFileByNioPath(Path.of(entity.path)) ?: error("Cannot find file: ${entity.path}") val library = KotlinScriptDependenciesLibrary("Script: ${scriptFile.relativeName(project)}", dependencies.compiled, dependencies.sources) return SyntheticLibraryElementNode(project, library, library, settings) } } private data class KotlinScriptDependenciesLibrary(val name: String, val classes: Collection<VirtualFile>, val sources: Collection<VirtualFile>) : SyntheticLibrary(), ItemPresentation { override fun getBinaryRoots(): Collection<VirtualFile> = classes override fun getSourceRoots(): Collection<VirtualFile> = sources override fun getPresentableText(): String = name override fun getIcon(unused: Boolean): Icon = KotlinIcons.SCRIPT } private fun KotlinScriptEntity.listDependencies(): ScriptDependencies { fun List<LibraryRoot>.files() = asSequence() .mapNotNull { it.url.virtualFile } .filter { it.isValid } .toList() val (compiledRoots, sourceRoots) = dependencies.asSequence() .flatMap { it.roots } .partition { it.type == LibraryRootTypeId.COMPILED } return ScriptDependencies(Pair(compiledRoots.files(), sourceRoots.files())) } @JvmInline private value class ScriptDependencies(private val compiledAndSources: Pair<List<VirtualFile>, List<VirtualFile>>) { val compiled get() = compiledAndSources.first val sources get() = compiledAndSources.second }
apache-2.0
smmribeiro/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrArrayInitializerImpl.kt
9
1414
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.lang.psi.impl import com.intellij.lang.ASTNode import com.intellij.psi.PsiElement import com.intellij.psi.PsiListLikeElement import com.intellij.psi.tree.TokenSet import com.intellij.psi.util.childrenOfType import org.jetbrains.plugins.groovy.lang.psi.GroovyElementTypes import org.jetbrains.plugins.groovy.lang.psi.GroovyElementTypes.T_LBRACE import org.jetbrains.plugins.groovy.lang.psi.GroovyElementVisitor import org.jetbrains.plugins.groovy.lang.psi.api.GrArrayInitializer import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression class GrArrayInitializerImpl(node: ASTNode) : GroovyPsiElementImpl(node), GrArrayInitializer, PsiListLikeElement { override fun toString(): String = "Array initializer" override fun accept(visitor: GroovyElementVisitor): Unit = visitor.visitArrayInitializer(this) override fun getLBrace(): PsiElement = findNotNullChildByType(T_LBRACE) override fun isEmpty(): Boolean = node.getChildren(TokenSet.ANY).none { it.psi is GrExpression } override fun getExpressions(): List<GrExpression> = childrenOfType() override fun getRBrace(): PsiElement? = findChildByType(GroovyElementTypes.T_RBRACE) override fun getComponents(): List<PsiElement> = expressions }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/intentions/convertToRawStringTemplate/basic.kt
13
42
val foo = "abc\n" <caret>+ "xyz"
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/refactoring/introduceParameter/classUsedParameter.kt
13
145
// TARGET: class A(val a: Int, s: String) { val x = a + 2 fun foo() = (<selection>a + 1</selection>) * 2 } fun test() { A(1, "2") }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/maven/tests/testData/languageFeature/enableInlineClassesWithXFlag/src.kt
26
28
inline class My(val x: Int)
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/j2k/new/tests/testData/newJ2k/issues/kt-543-mixed.kt
13
124
package demo internal class Test { fun putInt(i: Int?) {} fun test() { val i = 10 putInt(i) } }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/quickfix/increaseVisibility/invisibleFake/methodToProtected2.kt
13
168
// "Make 'doSth' protected" "true" open class A { private fun doSth() { } } open class B : A() class C : B() { fun bar() { <caret>doSth() } }
apache-2.0
ianhanniballake/muzei
main/src/main/java/com/google/android/apps/muzei/settings/EffectsScreenFragment.kt
2
6964
/* * Copyright 2018 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.muzei.settings import android.content.SharedPreferences import android.os.Bundle import android.view.View import android.widget.SeekBar import androidx.core.content.edit import androidx.core.os.bundleOf import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import com.google.android.apps.muzei.render.MuzeiBlurRenderer import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.launch import net.nurik.roman.muzei.R import net.nurik.roman.muzei.databinding.EffectsScreenFragmentBinding /** * Fragment for allowing the user to configure advanced settings. */ class EffectsScreenFragment : Fragment(R.layout.effects_screen_fragment) { companion object { private const val PREF_BLUR = "pref_blur" private const val PREF_DIM = "pref_dim" private const val PREF_GREY = "pref_grey" internal fun create( prefBlur: String, prefDim: String, prefGrey: String ) = EffectsScreenFragment().apply { arguments = bundleOf( PREF_BLUR to prefBlur, PREF_DIM to prefDim, PREF_GREY to prefGrey ) } } private lateinit var blurPref: String private lateinit var dimPref: String private lateinit var greyPref: String private lateinit var blurOnPreferenceChangeListener: SharedPreferences.OnSharedPreferenceChangeListener private lateinit var dimOnPreferenceChangeListener: SharedPreferences.OnSharedPreferenceChangeListener private lateinit var greyOnPreferenceChangeListener: SharedPreferences.OnSharedPreferenceChangeListener private var updateBlur: Job? = null private var updateDim: Job? = null private var updateGrey: Job? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) blurPref = requireArguments().getString(PREF_BLUR) ?: throw IllegalArgumentException("Missing required argument $PREF_BLUR") dimPref = requireArguments().getString(PREF_DIM) ?: throw IllegalArgumentException("Missing required argument $PREF_DIM") greyPref = requireArguments().getString(PREF_GREY) ?: throw IllegalArgumentException("Missing required argument $PREF_GREY") } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { val binding = EffectsScreenFragmentBinding.bind(view) val prefs = Prefs.getSharedPreferences(requireContext()) binding.content.blurAmount.progress = prefs.getInt(blurPref, MuzeiBlurRenderer.DEFAULT_BLUR) binding.content.blurAmount.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar, value: Int, fromUser: Boolean) { if (fromUser) { updateBlur?.cancel() updateBlur = lifecycleScope.launch { delay(750) prefs.edit { putInt(blurPref, binding.content.blurAmount.progress) } } } } override fun onStartTrackingTouch(seekBar: SeekBar) {} override fun onStopTrackingTouch(seekBar: SeekBar) {} }) blurOnPreferenceChangeListener = SharedPreferences.OnSharedPreferenceChangeListener { _, _ -> binding.content.blurAmount.progress = prefs.getInt(blurPref, MuzeiBlurRenderer.DEFAULT_BLUR) } prefs.registerOnSharedPreferenceChangeListener(blurOnPreferenceChangeListener) binding.content.dimAmount.progress = prefs.getInt(dimPref, MuzeiBlurRenderer.DEFAULT_MAX_DIM) binding.content.dimAmount.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar, value: Int, fromUser: Boolean) { if (fromUser) { updateDim?.cancel() updateDim = lifecycleScope.launch { delay(750) prefs.edit { putInt(dimPref, binding.content.dimAmount.progress) } } } } override fun onStartTrackingTouch(seekBar: SeekBar) {} override fun onStopTrackingTouch(seekBar: SeekBar) {} }) dimOnPreferenceChangeListener = SharedPreferences.OnSharedPreferenceChangeListener { _, _ -> binding.content.dimAmount.progress = prefs.getInt(dimPref, MuzeiBlurRenderer.DEFAULT_MAX_DIM) } prefs.registerOnSharedPreferenceChangeListener(dimOnPreferenceChangeListener) binding.content.greyAmount.progress = prefs.getInt(greyPref, MuzeiBlurRenderer.DEFAULT_GREY) binding.content.greyAmount.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar, value: Int, fromUser: Boolean) { if (fromUser) { updateGrey?.cancel() updateGrey = lifecycleScope.launch { delay(750) prefs.edit { putInt(greyPref, binding.content.greyAmount.progress) } } } } override fun onStartTrackingTouch(seekBar: SeekBar) {} override fun onStopTrackingTouch(seekBar: SeekBar) {} }) greyOnPreferenceChangeListener = SharedPreferences.OnSharedPreferenceChangeListener { _, _ -> binding.content.greyAmount.progress = prefs.getInt(greyPref, MuzeiBlurRenderer.DEFAULT_GREY) } prefs.registerOnSharedPreferenceChangeListener(greyOnPreferenceChangeListener) } override fun onDestroyView() { super.onDestroyView() Prefs.getSharedPreferences(requireContext()).apply { unregisterOnSharedPreferenceChangeListener(blurOnPreferenceChangeListener) unregisterOnSharedPreferenceChangeListener(dimOnPreferenceChangeListener) unregisterOnSharedPreferenceChangeListener(greyOnPreferenceChangeListener) } } }
apache-2.0
erdo/asaf-project
example-kt-03adapters/src/androidTest/java/foo/bar/example/foreadapterskt/ui/playlist/StateBuilder.kt
1
2928
package foo.bar.example.foreadapterskt.ui.playlist import androidx.test.rule.ActivityTestRule import co.early.fore.adapters.mutable.UpdateSpec import co.early.fore.core.time.SystemTimeWrapper import co.early.fore.kt.core.delegate.Fore import co.early.fore.kt.core.delegate.TestDelegateDefault import foo.bar.example.foreadapterskt.OG import foo.bar.example.foreadapterskt.feature.playlist.mutable.MutablePlaylistModel import foo.bar.example.foreadapterskt.feature.playlist.immutable.ImmutablePlaylistModel import foo.bar.example.foreadapterskt.feature.playlist.Track import io.mockk.CapturingSlot import io.mockk.every import io.mockk.mockk /** * */ class StateBuilder internal constructor(private val mockMutablePlaylistModel: MutablePlaylistModel, private val mockImmutablePlaylistModel: ImmutablePlaylistModel) { init { val updateSpec = UpdateSpec(UpdateSpec.UpdateType.FULL_UPDATE, 0, 0, mockk<SystemTimeWrapper>(relaxed = true)) every { mockMutablePlaylistModel.getAndClearLatestUpdateSpec(any()) } returns updateSpec } internal fun withUpdatablePlaylistHavingTracks(numberOfTracks: Int): StateBuilder { every { mockMutablePlaylistModel.itemCount } returns numberOfTracks every { mockMutablePlaylistModel.isEmpty() } returns (numberOfTracks == 0) var slot = CapturingSlot<Int>() every { mockMutablePlaylistModel.hasAtLeastNItems(capture(slot)) } answers { numberOfTracks >= slot.captured } return this } internal fun withDiffablePlaylistHavingTracks(numberOfTracks: Int): StateBuilder { every { mockImmutablePlaylistModel.getItemCount() } returns numberOfTracks every { mockImmutablePlaylistModel.isEmpty() } returns (numberOfTracks == 0) var slot = CapturingSlot<Int>() every { mockImmutablePlaylistModel.hasAtLeastNItems(capture(slot)) } answers { numberOfTracks >= slot.captured } return this } internal fun withPlaylistsContainingTrack(track: Track): StateBuilder { every { mockMutablePlaylistModel.getItem(any()) } returns track every { mockImmutablePlaylistModel.getItem(any()) } returns track return this } internal fun createRule(): ActivityTestRule<PlaylistsActivity> { return object : ActivityTestRule<PlaylistsActivity>(PlaylistsActivity::class.java) { override fun beforeActivityLaunched() { Fore.setDelegate(TestDelegateDefault()) //inject our mocks so our UI layer will pick them up OG.putMock(MutablePlaylistModel::class.java, mockMutablePlaylistModel) OG.putMock(ImmutablePlaylistModel::class.java, mockImmutablePlaylistModel) } } } }
apache-2.0
Jire/Charlatano
src/main/kotlin/com/charlatano/settings/Scripts.kt
1
1765
/* * Charlatano: Free and open-source (FOSS) cheat for CS:GO/CS:CO * Copyright (C) 2017 - Thomas G. P. Nappo, Jonathan Beaudoin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.charlatano.settings /** * Enables the bunny hop script. * * When using "LEAGUE_MODE" you need to unbind the bunnyhop key, * and bind mwheelup and mwheeldown to jump. * * To do this, type the following commands into the in-game developer console: * unbind "space" * bind "mwheelup" "+jump" * bind "mwheeldown" "+jump" */ var ENABLE_BUNNY_HOP = false /** * Enables the recoil control system (RCS) script. */ var ENABLE_RCS = true /** * Enables the extra sensory perception (ESP) script. */ var ENABLE_ESP = true /** * Enables the flat aim script. * * This script uses traditional flat linear-regression smoothing. */ var ENABLE_FLAT_AIM = true /** * Enables the path aim script. * * This script uses an advanced path generation smoothing. */ var ENABLE_PATH_AIM = false /** * Enables the bone trigger bot script. */ var ENABLE_BONE_TRIGGER = false /** * Enables the bomb timer script. */ var ENABLE_BOMB_TIMER = false
agpl-3.0
stakkato95/KotlinDroidPlayer
KMusic/app/src/main/java/com/github/stakkato95/kmusic/mvp/di/component/PlayerComponent.kt
1
456
package com.github.stakkato95.kmusic.mvp.di.component import com.github.stakkato95.kmusic.mvp.di.module.PlayerModule import com.github.stakkato95.kmusic.mvp.di.scope.PlayerScope import com.github.stakkato95.kmusic.screen.player.ui.PlayerFragment import dagger.Subcomponent /** * Created by artsiomkaliaha on 05.10.17. */ @Subcomponent(modules = [PlayerModule::class]) @PlayerScope interface PlayerComponent { fun inject(fragment: PlayerFragment) }
gpl-3.0
fkorotkov/k8s-kotlin-dsl
DSLs/kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/openshift/modern.kt
1
409
// GENERATED package com.fkorotkov.openshift import io.fabric8.openshift.api.model.ModernTLSProfile as model_ModernTLSProfile import io.fabric8.openshift.api.model.TLSSecurityProfile as model_TLSSecurityProfile fun model_TLSSecurityProfile.`modern`(block: model_ModernTLSProfile.() -> Unit = {}) { if(this.`modern` == null) { this.`modern` = model_ModernTLSProfile() } this.`modern`.block() }
mit
fkorotkov/k8s-kotlin-dsl
DSLs/kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/openshift/postCommit.kt
1
704
// GENERATED package com.fkorotkov.openshift import io.fabric8.openshift.api.model.BuildConfigSpec as model_BuildConfigSpec import io.fabric8.openshift.api.model.BuildPostCommitSpec as model_BuildPostCommitSpec import io.fabric8.openshift.api.model.BuildSpec as model_BuildSpec fun model_BuildConfigSpec.`postCommit`(block: model_BuildPostCommitSpec.() -> Unit = {}) { if(this.`postCommit` == null) { this.`postCommit` = model_BuildPostCommitSpec() } this.`postCommit`.block() } fun model_BuildSpec.`postCommit`(block: model_BuildPostCommitSpec.() -> Unit = {}) { if(this.`postCommit` == null) { this.`postCommit` = model_BuildPostCommitSpec() } this.`postCommit`.block() }
mit
vector-im/vector-android
vector/src/main/java/im/vector/fragments/terms/TermsController.kt
2
1765
/* * Copyright 2019 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package im.vector.fragments.terms import android.view.View import com.airbnb.epoxy.TypedEpoxyController import im.vector.R import im.vector.ui.epoxy.genericItemHeader class TermsController(private val itemDescription: String, private val listener: Listener) : TypedEpoxyController<List<Term>>() { override fun buildModels(data: List<Term>?) { data?.let { genericItemHeader { id("header") textID(R.string.widget_integration_review_terms) } it.forEach { term -> terms { id(term.url) name(term.name) description(itemDescription) checked(term.accepted) clickListener(View.OnClickListener { listener.review(term) }) checkChangeListener { _, isChecked -> listener.setChecked(term, isChecked) } } } } //TODO error mgmt } interface Listener { fun setChecked(term: Term, isChecked: Boolean) fun review(term: Term) } }
apache-2.0
intrigus/jtransc
jtransc-gen-cpp/src/com/jtransc/gen/cpp/libs/Libs.kt
1
1223
package com.jtransc.gen.cpp.libs import com.jtransc.gen.cpp.CppCompiler import com.jtransc.io.ProcessUtils import com.jtransc.service.JTranscService import com.jtransc.vfs.ExecOptions import com.jtransc.vfs.SyncVfsFile import org.rauschig.jarchivelib.ArchiveFormat import org.rauschig.jarchivelib.ArchiverFactory import org.rauschig.jarchivelib.CompressionType import java.io.File import java.net.URL import java.nio.file.Files import java.nio.file.StandardCopyOption import java.util.* object Libs { //val LIBS = ServiceLoader.load(Lib::class.java).toList() //val LIBS = listOf(BoostLib(), BdwgcLib(), JniHeadersLib()) //val LIBS = listOf(BdwgcLib(), JniHeadersLib()) val LIBS = listOf(BdwgcLib()) val cppCommonFolder get() = CppCompiler.CPP_COMMON_FOLDER.realfile val sdkDir = CppCompiler.CPP_COMMON_FOLDER.realfile val includeFolders: List<File> get() = LIBS.flatMap { it.includeFolders } val libFolders: List<File> get() = LIBS.flatMap { it.libFolders } val libs: List<String> get() = LIBS.flatMap { it.libs } val extraDefines: List<String> get() = LIBS.flatMap { it.extraDefines } fun installIfRequired(resourcesVfs: SyncVfsFile) { for (lib in LIBS) { lib.installIfRequired(resourcesVfs) } } }
apache-2.0
bixlabs/bkotlin
bkotlin/src/main/java/com/bixlabs/bkotlin/Only.kt
1
4392
@file:Suppress("unused", "MemberVisibilityCanBePrivate") package com.bixlabs.bkotlin import android.content.Context import android.content.SharedPreferences import android.content.pm.ApplicationInfo @DslMarker annotation class OnlyDsl /** * An easy way of running tasks a specific amount of times throughout the lifespan of an app, * either between versions of itself or regardless of the same. */ object Only { private lateinit var preference: SharedPreferences private lateinit var buildVersion: String private var isDebuggable = 0 private var doOnDebugMode = false /** initialize [Only] */ fun init(context: Context) { val info = context.packageManager.getPackageInfo(context.packageName, 0) init(context, info.versionName) } /** initialize [Only], providing a specific version for the tasks. */ fun init(context: Context, version: String) { this.preference = context.applicationContext.getSharedPreferences("Only", Context.MODE_PRIVATE) this.isDebuggable = context.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE this.buildVersion = version } /** Sets if [Only] should be in debug mode. */ fun setDebugMode(debug: Boolean): Only { this.doOnDebugMode = debug return this@Only } /** Checks if [Only] is in debug mode. */ fun isDebugModeEnabled(): Boolean = doOnDebugMode && isDebuggable != 0 /** Gets the amount of times a specific task has been run. */ fun getTaskTimes(taskName: String): Int = this.preference.getInt(taskName, 0) /** Sets the amount of times a specific task has been run. */ fun setTaskTimes(taskName: String, time: Int) = this.preference.edit().putInt(taskName, time).apply() /** Gets the version of a specific task if any */ fun getTaskVersion(taskName: String): String? = preference.getString(getTaskVersionName(taskName), buildVersion) /** Clear the amount of times a specific task has been run. */ fun clearTask(taskName: String) = this.preference.edit().remove(taskName).apply() /** Clear the amount of times for all tasks. */ fun clearAllTasks() = this.preference.edit().clear().apply() /* ******************************************** * Private methods * ******************************************** */ private inline fun onDo(name: String, times: Int, crossinline onDo: () -> Unit, crossinline onDone: () -> Unit, version: String = ""): Only { checkTaskVersion(name, version) // run only onDo block when debug mode. if (isDebugModeEnabled()) { onDo() return this@Only } val persistVersion = getTaskTimes(name) if (persistVersion < times) { setTaskTimes(name, persistVersion + 1) onDo() } else { onDone() } return this@Only } private fun checkTaskVersion(taskName: String, version: String): Boolean { val theVersion = if (version.isEmpty()) buildVersion else version if (getTaskVersion(taskName).equals(theVersion)) return true setTaskTimes(taskName, 0) setTaskVersion(taskName, theVersion) return false } private fun runByBuilder(builder: Builder) = onDo(builder.name, builder.times, builder.onDo, builder.onPreviouslyDone, builder.version) private fun setTaskVersion(name: String, version: String) = this.preference.edit().putString(getTaskVersionName(name), version).apply() private fun getTaskVersionName(name: String): String = "${name}_version" @OnlyDsl class Builder internal constructor(val name: String, val times: Int = 1) { var onDo: () -> Unit = { } var onPreviouslyDone: () -> Unit = { } var version: String = "" fun onDo(onDo: () -> Unit): Builder = apply { this.onDo = onDo } fun onPreviouslyDone(onDone: () -> Unit): Builder = apply { this.onPreviouslyDone = onDone } fun taskVersion(version: String): Builder = apply { this.version = version } fun run() = runByBuilder(this@Builder) } } /** Run [Only] by [Only.Builder] using kotlin DSL. */ @OnlyDsl fun only(taskName: String, times: Int, block: Only.Builder.() -> Unit): Unit = Only.Builder(taskName, times) .apply(block) .run() .toUnit()
apache-2.0
intrigus/jtransc
jtransc-utils/src/com/jtransc/lang/bool.kt
2
896
package com.jtransc.lang inline fun <T> Boolean.map(t: T, f: T) = if (this) t else f fun Boolean.toBool() = (this) fun Byte.toBool() = (this.toInt() != 0) fun Char.toBool() = (this.toInt() != 0) fun Short.toBool() = (this.toInt() != 0) fun Int.toBool() = (this.toInt() != 0) fun Long.toBool() = (this.toInt() != 0) fun Float.toBool() = (this != 0f) fun Double.toBool() = (this != 0.0) fun Boolean.toByte() = this.map(1, 0).toByte() fun Boolean.toChar() = this.map(1, 0).toChar() fun Boolean.toShort() = this.map(1, 0).toShort() fun Boolean.toInt() = this.map(1, 0).toInt() fun Boolean.toLong() = this.map(1, 0).toLong() fun Boolean.toFloat() = this.map(1, 0).toFloat() fun Boolean.toDouble() = this.map(1, 0).toDouble() fun Number.toBool() = (this.toInt() != 0) val Long.high:Int get() = ((this ushr 32) and 0xFFFFFFFF).toInt() val Long.low:Int get() = ((this ushr 0) and 0xFFFFFFFF).toInt()
apache-2.0
aosp-mirror/platform_frameworks_support
room/compiler/src/main/kotlin/androidx/room/writer/DatabaseWriter.kt
1
7339
/* * Copyright (C) 2016 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 androidx.room.writer import androidx.room.ext.AndroidTypeNames import androidx.room.ext.L import androidx.room.ext.N import androidx.room.ext.RoomTypeNames import androidx.room.ext.S import androidx.room.ext.SupportDbTypeNames import androidx.room.ext.T import androidx.room.solver.CodeGenScope import androidx.room.vo.DaoMethod import androidx.room.vo.Database import com.google.auto.common.MoreElements import com.squareup.javapoet.FieldSpec import com.squareup.javapoet.MethodSpec import com.squareup.javapoet.ParameterSpec import com.squareup.javapoet.TypeName import com.squareup.javapoet.TypeSpec import stripNonJava import javax.lang.model.element.Modifier import javax.lang.model.element.Modifier.PRIVATE import javax.lang.model.element.Modifier.PROTECTED import javax.lang.model.element.Modifier.PUBLIC import javax.lang.model.element.Modifier.VOLATILE /** * Writes implementation of classes that were annotated with @Database. */ class DatabaseWriter(val database: Database) : ClassWriter(database.implTypeName) { override fun createTypeSpecBuilder(): TypeSpec.Builder { val builder = TypeSpec.classBuilder(database.implTypeName) builder.apply { addModifiers(PUBLIC) superclass(database.typeName) addMethod(createCreateOpenHelper()) addMethod(createCreateInvalidationTracker()) addMethod(createClearAllTables()) } addDaoImpls(builder) return builder } private fun createClearAllTables(): MethodSpec { val scope = CodeGenScope(this) return MethodSpec.methodBuilder("clearAllTables").apply { addStatement("super.assertNotMainThread()") val dbVar = scope.getTmpVar("_db") addStatement("final $T $L = super.getOpenHelper().getWritableDatabase()", SupportDbTypeNames.DB, dbVar) val deferVar = scope.getTmpVar("_supportsDeferForeignKeys") if (database.enableForeignKeys) { addStatement("boolean $L = $L.VERSION.SDK_INT >= $L.VERSION_CODES.LOLLIPOP", deferVar, AndroidTypeNames.BUILD, AndroidTypeNames.BUILD) } addAnnotation(Override::class.java) addModifiers(PUBLIC) returns(TypeName.VOID) beginControlFlow("try").apply { if (database.enableForeignKeys) { beginControlFlow("if (!$L)", deferVar).apply { addStatement("$L.execSQL($S)", dbVar, "PRAGMA foreign_keys = FALSE") } endControlFlow() } addStatement("super.beginTransaction()") if (database.enableForeignKeys) { beginControlFlow("if ($L)", deferVar).apply { addStatement("$L.execSQL($S)", dbVar, "PRAGMA defer_foreign_keys = TRUE") } endControlFlow() } database.entities.sortedWith(EntityDeleteComparator()).forEach { addStatement("$L.execSQL($S)", dbVar, "DELETE FROM `${it.tableName}`") } addStatement("super.setTransactionSuccessful()") } nextControlFlow("finally").apply { addStatement("super.endTransaction()") if (database.enableForeignKeys) { beginControlFlow("if (!$L)", deferVar).apply { addStatement("$L.execSQL($S)", dbVar, "PRAGMA foreign_keys = TRUE") } endControlFlow() } addStatement("$L.query($S).close()", dbVar, "PRAGMA wal_checkpoint(FULL)") beginControlFlow("if (!$L.inTransaction())", dbVar).apply { addStatement("$L.execSQL($S)", dbVar, "VACUUM") } endControlFlow() } endControlFlow() }.build() } private fun createCreateInvalidationTracker(): MethodSpec { return MethodSpec.methodBuilder("createInvalidationTracker").apply { addAnnotation(Override::class.java) addModifiers(PROTECTED) returns(RoomTypeNames.INVALIDATION_TRACKER) val tableNames = database.entities.joinToString(",") { "\"${it.tableName}\"" } addStatement("return new $T(this, $L)", RoomTypeNames.INVALIDATION_TRACKER, tableNames) }.build() } private fun addDaoImpls(builder: TypeSpec.Builder) { val scope = CodeGenScope(this) builder.apply { database.daoMethods.forEach { method -> val name = method.dao.typeName.simpleName().decapitalize().stripNonJava() val fieldName = scope.getTmpVar("_$name") val field = FieldSpec.builder(method.dao.typeName, fieldName, PRIVATE, VOLATILE).build() addField(field) addMethod(createDaoGetter(field, method)) } } } private fun createDaoGetter(field: FieldSpec, method: DaoMethod): MethodSpec { return MethodSpec.overriding(MoreElements.asExecutable(method.element)).apply { beginControlFlow("if ($N != null)", field).apply { addStatement("return $N", field) } nextControlFlow("else").apply { beginControlFlow("synchronized(this)").apply { beginControlFlow("if($N == null)", field).apply { addStatement("$N = new $T(this)", field, method.dao.implTypeName) } endControlFlow() addStatement("return $N", field) } endControlFlow() } endControlFlow() }.build() } private fun createCreateOpenHelper(): MethodSpec { val scope = CodeGenScope(this) return MethodSpec.methodBuilder("createOpenHelper").apply { addModifiers(Modifier.PROTECTED) addAnnotation(Override::class.java) returns(SupportDbTypeNames.SQLITE_OPEN_HELPER) val configParam = ParameterSpec.builder(RoomTypeNames.ROOM_DB_CONFIG, "configuration").build() addParameter(configParam) val openHelperVar = scope.getTmpVar("_helper") val openHelperCode = scope.fork() SQLiteOpenHelperWriter(database) .write(openHelperVar, configParam, openHelperCode) addCode(openHelperCode.builder().build()) addStatement("return $L", openHelperVar) }.build() } }
apache-2.0
aosp-mirror/platform_frameworks_support
navigation/safe-args-generator/src/main/kotlin/androidx/navigation/safe/args/generator/NavParser.kt
1
8153
/* * Copyright 2018 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 androidx.navigation.safe.args.generator import androidx.navigation.safe.args.generator.models.Action import androidx.navigation.safe.args.generator.models.Argument import androidx.navigation.safe.args.generator.models.Destination import androidx.navigation.safe.args.generator.models.ResReference import java.io.File import java.io.FileReader private const val TAG_NAVIGATION = "navigation" private const val TAG_ACTION = "action" private const val TAG_ARGUMENT = "argument" private const val ATTRIBUTE_ID = "id" private const val ATTRIBUTE_DESTINATION = "destination" private const val ATTRIBUTE_DEFAULT_VALUE = "defaultValue" private const val ATTRIBUTE_NAME = "name" private const val ATTRIBUTE_TYPE = "type" private const val NAMESPACE_RES_AUTO = "http://schemas.android.com/apk/res-auto" private const val NAMESPACE_ANDROID = "http://schemas.android.com/apk/res/android" internal class NavParser( private val parser: XmlPositionParser, private val context: Context, private val rFilePackage: String, private val applicationId: String ) { companion object { fun parseNavigationFile( navigationXml: File, rFilePackage: String, applicationId: String, context: Context ): Destination { FileReader(navigationXml).use { reader -> val parser = XmlPositionParser(navigationXml.path, reader, context.logger) parser.traverseStartTags { true } return NavParser(parser, context, rFilePackage, applicationId).parseDestination() } } } internal fun parseDestination(): Destination { val position = parser.xmlPosition() val type = parser.name() val name = parser.attrValue(NAMESPACE_ANDROID, ATTRIBUTE_NAME) ?: "" val idValue = parser.attrValue(NAMESPACE_ANDROID, ATTRIBUTE_ID) val args = mutableListOf<Argument>() val actions = mutableListOf<Action>() val nested = mutableListOf<Destination>() parser.traverseInnerStartTags { when { parser.name() == TAG_ACTION -> actions.add(parseAction()) parser.name() == TAG_ARGUMENT -> args.add(parseArgument()) type == TAG_NAVIGATION -> nested.add(parseDestination()) } } val id = idValue?.let { parseId(idValue, rFilePackage, position) } val className = Destination.createName(id, name, applicationId) if (className == null && (actions.isNotEmpty() || args.isNotEmpty())) { context.logger.error(NavParserErrors.UNNAMED_DESTINATION, position) return context.createStubDestination() } return Destination(id, className, type, args, actions, nested) } private fun parseArgument(): Argument { val xmlPosition = parser.xmlPosition() val name = parser.attrValueOrError(NAMESPACE_ANDROID, ATTRIBUTE_NAME) val defaultValue = parser.attrValue(NAMESPACE_ANDROID, ATTRIBUTE_DEFAULT_VALUE) val typeString = parser.attrValue(NAMESPACE_RES_AUTO, ATTRIBUTE_TYPE) if (name == null) return context.createStubArg() if (typeString == null && defaultValue != null) { return inferArgument(name, defaultValue, rFilePackage) } val type = NavType.from(typeString) if (type == null) { context.logger.error(NavParserErrors.unknownType(typeString), xmlPosition) return context.createStubArg() } if (defaultValue == null) { return Argument(name, type, null) } val defaultTypedValue = when (type) { NavType.INT -> parseIntValue(defaultValue) NavType.FLOAT -> parseFloatValue(defaultValue) NavType.BOOLEAN -> parseBoolean(defaultValue) NavType.REFERENCE -> parseReference(defaultValue, rFilePackage)?.let { ReferenceValue(it) } NavType.STRING -> StringValue(defaultValue) } if (defaultTypedValue == null) { val errorMessage = when (type) { NavType.REFERENCE -> NavParserErrors.invalidDefaultValueReference(defaultValue) else -> NavParserErrors.invalidDefaultValue(defaultValue, type) } context.logger.error(errorMessage, xmlPosition) return context.createStubArg() } return Argument(name, type, defaultTypedValue) } private fun parseAction(): Action { val idValue = parser.attrValueOrError(NAMESPACE_ANDROID, ATTRIBUTE_ID) val destValue = parser.attrValue(NAMESPACE_RES_AUTO, ATTRIBUTE_DESTINATION) val args = mutableListOf<Argument>() val position = parser.xmlPosition() parser.traverseInnerStartTags { if (parser.name() == TAG_ARGUMENT) { args.add(parseArgument()) } } val id = if (idValue != null) { parseId(idValue, rFilePackage, position) } else { context.createStubId() } val destination = destValue?.let { parseId(destValue, rFilePackage, position) } return Action(id, destination, args) } private fun parseId( xmlId: String, rFilePackage: String, xmlPosition: XmlPosition ): ResReference { val ref = parseReference(xmlId, rFilePackage) if (ref?.isId() == true) { return ref } context.logger.error(NavParserErrors.invalidId(xmlId), xmlPosition) return context.createStubId() } } internal fun inferArgument(name: String, defaultValue: String, rFilePackage: String): Argument { val reference = parseReference(defaultValue, rFilePackage) if (reference != null) { return Argument(name, NavType.REFERENCE, ReferenceValue(reference)) } val intValue = parseIntValue(defaultValue) if (intValue != null) { return Argument(name, NavType.INT, intValue) } val floatValue = parseFloatValue(defaultValue) if (floatValue != null) { return Argument(name, NavType.FLOAT, floatValue) } val boolValue = parseBoolean(defaultValue) if (boolValue != null) { return Argument(name, NavType.BOOLEAN, boolValue) } return Argument(name, NavType.STRING, StringValue(defaultValue)) } // @[+][package:]id/resource_name -> package.R.id.resource_name private val RESOURCE_REGEX = Regex("^@[+]?(.+?:)?(.+?)/(.+)$") internal fun parseReference(xmlValue: String, rFilePackage: String): ResReference? { val matchEntire = RESOURCE_REGEX.matchEntire(xmlValue) ?: return null val groups = matchEntire.groupValues val resourceName = groups.last() val resType = groups[groups.size - 2] val packageName = if (groups[1].isNotEmpty()) groups[1].removeSuffix(":") else rFilePackage return ResReference(packageName, resType, resourceName) } internal fun parseIntValue(value: String): IntValue? { try { if (value.startsWith("0x")) { Integer.parseUnsignedInt(value.substring(2), 16) } else { Integer.parseInt(value) } } catch (ex: NumberFormatException) { return null } return IntValue(value) } private fun parseFloatValue(value: String): FloatValue? = value.toFloatOrNull()?.let { FloatValue(value) } private fun parseBoolean(value: String): BooleanValue? { if (value == "true" || value == "false") { return BooleanValue(value) } return null }
apache-2.0
togglz/togglz
kotlin/src/test/kotlin/org/togglz/kotlin/EnumClassFeatureProviderTest.kt
1
1109
package org.togglz.kotlin import io.kotlintest.matchers.collections.shouldContainAll import io.kotlintest.shouldBe import org.junit.jupiter.api.Test internal class EnumClassFeatureProviderTest { private val featureProvider = EnumClassFeatureProvider(KotlinTestFeatures::class.java) @Test internal fun `should return wrapped features`() { val features = featureProvider.features features shouldContainAll setOf(FeatureEnum(KotlinTestFeatures.BAR), FeatureEnum(KotlinTestFeatures.FOO)) } @Test internal fun `should get metadata`() { val metaData = featureProvider.getMetaData(FeatureEnum(KotlinTestFeatures.FOO)) val expectedMetaData = FeatureEnumMetaData(KotlinTestFeatures.FOO, FeatureEnum(KotlinTestFeatures.FOO)) metaData!!.label shouldBe expectedMetaData.label metaData.attributes shouldBe expectedMetaData.attributes metaData.groups.map { it.label } shouldContainAll expectedMetaData.groups.map { it.label } metaData.defaultFeatureState.isEnabled shouldBe expectedMetaData.defaultFeatureState.isEnabled } }
apache-2.0
aspanu/SolutionsHackerRank
src/ClockTimes.kt
1
1037
import java.time.LocalTime.MIDNIGHT import java.time.format.DateTimeFormatter /** * Created by aspanu on 2017-09-12. */ fun main(args: Array<String>) { var currTime = MIDNIGHT var numTimes = 0 do { if (maxNumSameDigits(currTime.format(DateTimeFormatter.ofPattern("h:mm"))) >= 3) { numTimes++ println("Time: ${currTime.format(DateTimeFormatter.ofPattern("h:mm"))} has 3 or more digits.") } currTime = currTime.plusMinutes(1) } while (currTime != MIDNIGHT) println("Total number of times: $numTimes") } fun maxNumSameDigits(stringTime: String): Int { val charMap = mutableMapOf<Char, Int>() var maxNumDigits = -1 for (c in stringTime.toCharArray()) { if (c.isDigit()) { if (!charMap.containsKey(c)) { charMap.put(c, 0) } charMap.put(c, (charMap[c]!! + 1)) if (charMap[c]!! > maxNumDigits) maxNumDigits = charMap[c]!! } } return maxNumDigits }
gpl-2.0
quran/quran_android
common/di/src/main/java/com/quran/mobile/di/AyahActionFragmentProvider.kt
2
189
package com.quran.mobile.di import androidx.fragment.app.Fragment interface AyahActionFragmentProvider { val order: Int val iconResId: Int fun newAyahActionFragment(): Fragment }
gpl-3.0
hazuki0x0/YuzuBrowser
module/download/src/main/java/jp/hazuki/yuzubrowser/download/service/connection/ServiceSocket.kt
1
2808
/* * Copyright (C) 2017-2019 Hazuki * * 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 jp.hazuki.yuzubrowser.download.service.connection import android.content.Context import android.content.Intent import android.os.IBinder import android.os.Message import android.os.Messenger import android.os.RemoteException import jp.hazuki.yuzubrowser.core.service.ServiceBindHelper import jp.hazuki.yuzubrowser.core.service.ServiceConnectionHelper import jp.hazuki.yuzubrowser.core.utility.log.ErrorReport import jp.hazuki.yuzubrowser.download.service.DownloadService class ServiceSocket(private val context: Context, listener: ActivityClient.ActivityClientListener) : ServiceConnectionHelper<Messenger> { private val messenger = Messenger(ActivityClient(listener)) private val serviceHelper = ServiceBindHelper(context, this) override fun onBind(service: IBinder): Messenger { service.messenger.run { safeSend(createMessage(REGISTER_OBSERVER)) safeSend(createMessage(GET_DOWNLOAD_INFO)) return this } } override fun onUnbind(service: Messenger?) { serviceHelper.binder?.safeSend(createMessage(UNREGISTER_OBSERVER)) } fun bindService() { serviceHelper.bindService(Intent(context, DownloadService::class.java)) } fun unbindService() { serviceHelper.unbindService() } fun cancelDownload(id: Long) { serviceHelper.binder?.safeSend(createMessage(CANCEL_DOWNLOAD, id)) } fun pauseDownload(id: Long) { serviceHelper.binder?.safeSend(createMessage(PAUSE_DOWNLOAD, id)) } private fun Messenger.safeSend(message: Message) { try { send(message) } catch (e: RemoteException) { ErrorReport.printAndWriteLog(e) } } private fun createMessage(@ServiceCommand command: Int, obj: Any? = null) = Message.obtain(null, command, obj).apply { replyTo = messenger } private val IBinder.messenger get() = Messenger(this) companion object { const val REGISTER_OBSERVER = 0 const val UNREGISTER_OBSERVER = 1 const val UPDATE = 2 const val GET_DOWNLOAD_INFO = 3 const val CANCEL_DOWNLOAD = 4 const val PAUSE_DOWNLOAD = 5 } }
apache-2.0
markusfisch/BinaryEye
app/src/main/kotlin/de/markusfisch/android/binaryeye/actions/IAction.kt
1
1337
package de.markusfisch.android.binaryeye.actions import android.content.Context import android.content.Intent import de.markusfisch.android.binaryeye.content.execShareIntent import de.markusfisch.android.binaryeye.content.openUrl import de.markusfisch.android.binaryeye.widget.toast interface IAction { val iconResId: Int val titleResId: Int fun canExecuteOn(data: ByteArray): Boolean suspend fun execute(context: Context, data: ByteArray) } abstract class IntentAction : IAction { abstract val errorMsg: Int final override suspend fun execute(context: Context, data: ByteArray) { val intent = createIntent(context, data) if (intent == null) { context.toast(errorMsg) } else { context.execShareIntent(intent) } } abstract suspend fun createIntent( context: Context, data: ByteArray ): Intent? } abstract class SchemeAction : IAction { abstract val scheme: String open val buildRegex: Boolean = false final override fun canExecuteOn(data: ByteArray): Boolean { val content = String(data) return if (buildRegex) { content.matches( """^$scheme://[\w\W]+$""".toRegex( RegexOption.IGNORE_CASE ) ) } else { content.startsWith("$scheme://", ignoreCase = true) } } final override suspend fun execute(context: Context, data: ByteArray) { context.openUrl(String(data)) } }
mit
square/sqldelight
test-util/src/main/kotlin/com/squareup/sqldelight/test/util/TestEnvironment.kt
1
2273
package com.squareup.sqldelight.test.util import com.alecstrong.sql.psi.core.DialectPreset import com.alecstrong.sql.psi.core.SqlAnnotationHolder import com.alecstrong.sql.psi.core.SqlCoreEnvironment import com.intellij.psi.PsiElement import com.squareup.sqldelight.core.SqlDelightCompilationUnit import com.squareup.sqldelight.core.SqlDelightDatabaseName import com.squareup.sqldelight.core.SqlDelightDatabaseProperties import com.squareup.sqldelight.core.SqlDelightEnvironment import com.squareup.sqldelight.core.SqlDelightSourceFolder import java.io.File internal class TestEnvironment( private val outputDirectory: File = File("output"), private val deriveSchemaFromMigrations: Boolean = false, private val dialectPreset: DialectPreset = DialectPreset.SQLITE_3_18 ) { fun build(root: String): SqlCoreEnvironment { return build( root, object : SqlAnnotationHolder { override fun createErrorAnnotation(element: PsiElement, s: String) { throw IllegalStateException(s) } } ) } fun build( root: String, annotationHolder: SqlAnnotationHolder ): SqlDelightEnvironment { val compilationUnit = object : SqlDelightCompilationUnit { override val name = "test" override val outputDirectoryFile = outputDirectory override val sourceFolders = emptyList<SqlDelightSourceFolder>() } val environment = SqlDelightEnvironment( sourceFolders = listOf(File(root)), dependencyFolders = emptyList(), properties = object : SqlDelightDatabaseProperties { override val packageName = "com.example" override val className = "TestDatabase" override val dependencies = emptyList<SqlDelightDatabaseName>() override val compilationUnits = listOf(compilationUnit) override val dialectPresetName = dialectPreset.name override val deriveSchemaFromMigrations = [email protected] override val rootDirectory = File(root) }, verifyMigrations = true, // hyphen in the name tests that our module name sanitizing works correctly moduleName = "test-module", compilationUnit = compilationUnit, ) environment.annotate(annotationHolder) return environment } }
apache-2.0
Wackalooon/EcoMeter
value-domain/src/main/java/com/wackalooon/value/domain/repository/ValueRepository.kt
1
326
package com.wackalooon.value.domain.repository import com.wackalooon.value.domain.model.Value interface ValueRepository { fun getValuesForMeterId(meterId: Long): List<Value> fun addValueForMeterId(value: Value, meterId: Long) fun updateValue(valueId: Long, newValue: Double) fun deleteValue(valueId: Long) }
apache-2.0
EMResearch/EvoMaster
e2e-tests/spring-graphql/src/main/kotlin/com/foo/graphql/input/resolver/QueryResolver.kt
1
427
package com.foo.graphql.input.resolver import com.foo.graphql.input.DataRepository import com.foo.graphql.input.type.Flower import graphql.kickstart.tools.GraphQLQueryResolver import org.springframework.stereotype.Component @Component open class QueryResolver( private val dataRepo: DataRepository ) : GraphQLQueryResolver { fun flowersById(id: Int?): Flower?{ return dataRepo.findById(id) } }
lgpl-3.0
EMResearch/EvoMaster
core/src/main/kotlin/org/evomaster/core/output/oracles/SupportedCodeOracle.kt
1
6217
package org.evomaster.core.output.oracles import org.evomaster.core.logging.LoggingUtil import org.evomaster.core.output.Lines import org.evomaster.core.output.OutputFormat import org.evomaster.core.output.ObjectGenerator import org.evomaster.core.problem.rest.HttpVerb import org.evomaster.core.problem.rest.RestCallAction import org.evomaster.core.problem.httpws.service.HttpWsCallResult import org.evomaster.core.problem.rest.RestIndividual import org.evomaster.core.search.EvaluatedAction import org.evomaster.core.search.EvaluatedIndividual import org.slf4j.Logger import org.slf4j.LoggerFactory /** * The [SupportedCodeOracle] class generates an expectation and writes it to the code. * * A comparison is made between the status code of the [RestCallResult] and the supported return codes as defined * by the schema. If the actual code is not supported by the schema, the relevant expectation is generated and added * to the code. */ class SupportedCodeOracle : ImplementedOracle() { private val variableName = "sco" private lateinit var objectGenerator: ObjectGenerator private val log: Logger = LoggerFactory.getLogger(SupportedCodeOracle::class.java) override fun variableDeclaration(lines: Lines, format: OutputFormat) { lines.add("/**") lines.add("* $variableName - supported code oracle - checking that the response status code is among those supported according to the schema") lines.add("*/") when{ format.isJava() -> lines.add("private static boolean $variableName = false;") format.isKotlin() -> lines.add("private val $variableName = false") format.isJavaScript() -> lines.add("const $variableName = false;") } } override fun addExpectations(call: RestCallAction, lines: Lines, res: HttpWsCallResult, name: String, format: OutputFormat) { //if(!supportedCode(call, res)){ if(generatesExpectation(call, res)){ // The code is not among supported codes, so an expectation will be generated //val actualCode = res.getStatusCode() ?: 0 //lines.add(".that($oracleName, Arrays.asList(${getSupportedCode(call)}).contains($actualCode))") val supportedCodes = getSupportedCode(call) //BMR: this will be a problem if supportedCode contains both codes and default... if(supportedCodes.contains("0")){ lines.add("// WARNING: the code list seems to contain an unsupported code (0 is not a valid HTTP code). This could indicate a problem with the schema. The issue has been logged.") supportedCodes.remove("0") LoggingUtil.uniqueWarn(log, "The list of supported codes appears to contain an unsupported code (0 is not a valid HTTP code). This could indicate a problem with the schema.") //TODO: if a need arises for more involved checks, refactor this } val supportedCode = supportedCodes.joinToString(", ") if(supportedCode.equals("")){ lines.add("/*") lines.add(" Note: No supported codes appear to be defined. https://swagger.io/docs/specification/describing-responses/.") lines.add(" This is somewhat unexpected, so the code below is likely to lead to a failed expectation") lines.add("*/") when { format.isJava() -> lines.add(".that($variableName, Arrays.asList().contains($name.extract().statusCode()))") format.isKotlin() -> lines.add(".that($variableName, listOf<Int>().contains($name.extract().statusCode()))") } } //TODO: check here if supported code contains 0 (or maybe check against a list of "acceptable" codes else when { format.isJava() -> lines.add(".that($variableName, Arrays.asList($supportedCode).contains($name.extract().statusCode()))") format.isKotlin() -> lines.add(".that($variableName, listOf<Int>($supportedCode).contains($name.extract().statusCode()))") } } } fun supportedCode(call: RestCallAction, res: HttpWsCallResult): Boolean{ val code = res.getStatusCode().toString() val validCodes = getSupportedCode(call) return (validCodes.contains(code) || validCodes.contains("default")) } fun getSupportedCode(call: RestCallAction): MutableSet<String>{ val verb = call.verb val path = retrievePath(objectGenerator, call) val result = when (verb){ HttpVerb.GET -> path?.get HttpVerb.POST -> path?.post HttpVerb.PUT -> path?.put HttpVerb.DELETE -> path?.delete HttpVerb.PATCH -> path?.patch HttpVerb.HEAD -> path?.head HttpVerb.OPTIONS -> path?.options HttpVerb.TRACE -> path?.trace else -> null } return result?.responses?.keys ?: mutableSetOf() } override fun setObjectGenerator(gen: ObjectGenerator){ objectGenerator = gen } override fun generatesExpectation(call: RestCallAction, res: HttpWsCallResult): Boolean { if(this::objectGenerator.isInitialized){ return !supportedCode(call, res) } return false } override fun generatesExpectation(individual: EvaluatedIndividual<*>): Boolean { if(individual.individual !is RestIndividual) return false if(!this::objectGenerator.isInitialized) return false val gens = individual.evaluatedMainActions().any { !supportedCode(it.action as RestCallAction, it.result as HttpWsCallResult) } return gens } override fun selectForClustering(action: EvaluatedAction): Boolean { return if (action.result is HttpWsCallResult && action.action is RestCallAction &&this::objectGenerator.isInitialized && !(action.action as RestCallAction).skipOracleChecks ) !supportedCode(action.action as RestCallAction, action.result as HttpWsCallResult) else false } override fun getName(): String { return "CodeOracle" } }
lgpl-3.0
square/sqldelight
sqldelight-gradle-plugin/src/test/kotlin/com/squareup/sqldelight/tests/GenerateSchemaTest.kt
1
2570
package com.squareup.sqldelight.tests import com.google.common.truth.Truth.assertThat import org.gradle.testkit.runner.GradleRunner import org.junit.Test import java.io.File class GenerateSchemaTest { @Test fun `schema file generates correctly`() { val fixtureRoot = File("src/test/schema-file") val schemaFile = File(fixtureRoot, "src/main/sqldelight/databases/1.db") if (schemaFile.exists()) schemaFile.delete() GradleRunner.create() .withProjectDir(fixtureRoot) .withArguments("clean", "generateMainDatabaseSchema", "--stacktrace") .build() // verify assertThat(schemaFile.exists()) .isTrue() schemaFile.delete() } @Test fun `generateSchema task can run twice`() { val fixtureRoot = File("src/test/schema-file") val schemaFile = File(fixtureRoot, "src/main/sqldelight/databases/1.db") if (schemaFile.exists()) schemaFile.delete() GradleRunner.create() .withProjectDir(fixtureRoot) .withArguments("clean", "generateMainDatabaseSchema", "--stacktrace") .build() // verify assertThat(schemaFile.exists()) .isTrue() val lastModified = schemaFile.lastModified() while (System.currentTimeMillis() - lastModified <= 1000) { // last modified only updates per second. Thread.yield() } GradleRunner.create() .withProjectDir(fixtureRoot) .withArguments("clean", "--rerun-tasks", "generateMainDatabaseSchema", "--stacktrace") .build() // verify assertThat(schemaFile.exists()).isTrue() assertThat(schemaFile.lastModified()).isNotEqualTo(lastModified) schemaFile.delete() } @Test fun `schema file generates correctly with existing sqm files`() { val fixtureRoot = File("src/test/schema-file-sqm") GradleRunner.create() .withProjectDir(fixtureRoot) .withArguments("clean", "generateMainDatabaseSchema", "--stacktrace") .build() // verify val schemaFile = File(fixtureRoot, "src/main/sqldelight/databases/3.db") assertThat(schemaFile.exists()) .isTrue() schemaFile.delete() } @Test fun `schema file generates correctly for android`() { val fixtureRoot = File("src/test/schema-file-android") val schemaFile = File(fixtureRoot, "src/main/sqldelight/databases/1.db") if (schemaFile.exists()) schemaFile.delete() GradleRunner.create() .withProjectDir(fixtureRoot) .withArguments("clean", "generateDebugDatabaseSchema", "--stacktrace") .build() // verify assertThat(schemaFile.exists()).isTrue() } }
apache-2.0
EMResearch/EvoMaster
e2e-tests/spring-graphql/src/test/kotlin/com/foo/graphql/nullableNonNullableInInput/NullableNonNullableInInputController.kt
1
301
package com.foo.graphql.nullableNonNullableInInput import com.foo.graphql.SpringController class NullableNonNullableInInputController : SpringController(GQLNullableNonNullableInInputApplication::class.java) { override fun schemaName() = GQLNullableNonNullableInInputApplication.SCHEMA_NAME }
lgpl-3.0
FetzenRndy/Creative
projects/towers/app/src/main/kotlin/de/patrickhollweck/towers/App.kt
1
518
package de.patrickhollweck.towers import de.patrickhollweck.towers.screens.GameScreen import de.patrickhollweck.towers.screens.Screen import processing.core.PApplet fun main() { PApplet.main("de.patrickhollweck.towers.App") } class App() : PApplet() { private val screen: Screen = GameScreen() override fun settings() { size(1200, 800) } override fun setup() { frameRate(30f) screen.setup() } override fun draw() { background(255) screen.draw(this) } }
mit
luks91/Team-Bucket
app/src/main/java/com/github/luks91/teambucket/main/MainActivityComponent.kt
2
972
/** * Copyright (c) 2017-present, Team Bucket Contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See * the License for the specific language governing permissions and limitations under the License. */ package com.github.luks91.teambucket.main import dagger.Subcomponent import dagger.android.AndroidInjector @Subcomponent(modules = arrayOf(MainActivityModule::class, MainFragmentsProvider::class)) interface MainActivityComponent : AndroidInjector<MainActivity> { @Subcomponent.Builder abstract class Builder : AndroidInjector.Builder<MainActivity>() }
apache-2.0
KotlinPorts/pooled-client
postgresql-async/src/main/kotlin/com/github/mauricio/async/db/postgresql/column/ByteArrayEncoderDecoder.kt
2
3956
/* * Copyright 2013 Maurício Linhares * * Maurício Linhares licenses this file to you 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.github.mauricio.async.db.postgresql.column import com.github.mauricio.async.db.column.ColumnEncoderDecoder import com.github.mauricio.async.db.postgresql.exceptions.ByteArrayFormatNotSupportedException import com.github.mauricio.async.db.util.HexCodec import java.nio.ByteBuffer import io.netty.buffer.ByteBuf import mu.KLogging object ByteArrayEncoderDecoder : ColumnEncoderDecoder, KLogging() { val HexStart = "\\x" val HexStartChars = HexStart.toCharArray() override fun decode(value: String): ByteArray = if (value.startsWith(HexStart)) { HexCodec.decode(value, 2) } else { // Default encoding is 'escape' // Size the buffer to the length of the string, the data can't be bigger val buffer = ByteBuffer.allocate(value.length) val ci = value.iterator() while (ci.hasNext()) { val c = ci.next(); when (c) { '\\' -> { val c2 = getCharOrDie(ci) when (c2) { '\\' -> buffer.put('\\'.toByte()) else -> { val firstDigit = c2 val secondDigit = getCharOrDie(ci) val thirdDigit = getCharOrDie(ci) // Must always be in triplets buffer.put( Integer.decode( String(charArrayOf('0', firstDigit, secondDigit, thirdDigit))).toByte()) } } } else -> buffer.put(c.toByte()) } } buffer.flip() val finalArray = ByteArray(buffer.remaining()) buffer.get(finalArray) finalArray } /** * This is required since {@link Iterator#next} when {@linke Iterator#hasNext} is false is undefined. * @param ci the iterator source of the data * @return the next character * @throws IllegalArgumentException if there is no next character */ private fun getCharOrDie(ci: Iterator<Char>): Char = if (ci.hasNext()) { ci.next() } else { throw IllegalArgumentException("Expected escape sequence character, found nothing") } override fun encode(value: Any): String { val array = when (value) { is ByteArray -> value is ByteBuffer -> if (value.hasArray()) value.array() else { val arr = ByteArray(value.remaining()) value.get(arr) arr } is ByteBuf -> if (value.hasArray()) value.array() else { val arr = ByteArray(value.readableBytes()) value.getBytes(0, arr) arr } else -> throw IllegalArgumentException("not a byte array/ByteBuffer/ByteArray") } return HexCodec.encode(array, HexStartChars) } }
apache-2.0
facebook/fresco
imagepipeline/src/main/java/com/facebook/imagepipeline/datasource/AbstractProducerToDataSourceAdapter.kt
1
3451
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.imagepipeline.datasource import com.facebook.common.internal.Preconditions import com.facebook.datasource.AbstractDataSource import com.facebook.imagepipeline.listener.RequestListener2 import com.facebook.imagepipeline.producers.BaseConsumer import com.facebook.imagepipeline.producers.Consumer import com.facebook.imagepipeline.producers.Producer import com.facebook.imagepipeline.producers.ProducerContext import com.facebook.imagepipeline.producers.SettableProducerContext import com.facebook.imagepipeline.request.HasImageRequest import com.facebook.imagepipeline.request.ImageRequest import com.facebook.imagepipeline.systrace.FrescoSystrace.traceSection import javax.annotation.concurrent.ThreadSafe /** * DataSource<T> backed by a Producer<T> * * @param <T> </T></T></T> */ @ThreadSafe abstract class AbstractProducerToDataSourceAdapter<T> protected constructor( producer: Producer<T>, val settableProducerContext: SettableProducerContext, val requestListener: RequestListener2 ) : AbstractDataSource<T>(), HasImageRequest { private fun createConsumer(): Consumer<T> { return object : BaseConsumer<T>() { override fun onNewResultImpl(newResult: T?, @Consumer.Status status: Int) { [email protected]( newResult, status, settableProducerContext) } override fun onFailureImpl(throwable: Throwable) { [email protected](throwable) } override fun onCancellationImpl() { [email protected]() } override fun onProgressUpdateImpl(progress: Float) { setProgress(progress) } } } protected open fun onNewResultImpl(result: T?, status: Int, producerContext: ProducerContext) { val isLast = BaseConsumer.isLast(status) if (super.setResult(result, isLast, getExtras(producerContext))) { if (isLast) { requestListener.onRequestSuccess(settableProducerContext) } } } protected fun getExtras(producerContext: ProducerContext): Map<String, Any> = producerContext.extras private fun onFailureImpl(throwable: Throwable) { if (super.setFailure(throwable, getExtras(settableProducerContext))) { requestListener.onRequestFailure(settableProducerContext, throwable) } } @Synchronized private fun onCancellationImpl() { Preconditions.checkState(isClosed) } override val imageRequest: ImageRequest? get() = settableProducerContext.imageRequest override fun close(): Boolean { if (!super.close()) { return false } if (!super.isFinished()) { requestListener.onRequestCancellation(settableProducerContext) settableProducerContext.cancel() } return true } init { traceSection("AbstractProducerToDataSourceAdapter()") { extras = settableProducerContext.extras traceSection("AbstractProducerToDataSourceAdapter()->onRequestStart") { requestListener.onRequestStart(settableProducerContext) } traceSection("AbstractProducerToDataSourceAdapter()->produceResult") { producer.produceResults(createConsumer(), settableProducerContext) } } } }
mit
jayrave/falkon
falkon-dao-extn/src/test/kotlin/com/jayrave/falkon/dao/DaoForDeletesIntegrationTests.kt
1
5114
package com.jayrave.falkon.dao import com.jayrave.falkon.dao.testLib.TableForTest import org.assertj.core.api.Assertions.assertThat import org.junit.Test class DaoForDeletesIntegrationTests : BaseClassForIntegrationTests() { @Test fun testDeletionOfSingleModel() { val modelToBeDeleted = buildModelForTest(1) insertModelUsingInsertBuilder(table, modelToBeDeleted) insertAdditionalRandomModelsUsingInsertBuilder(table, count = 7) val numberOfRowsDeleted = table.dao.delete(modelToBeDeleted) assertAbsenceOf(table, modelToBeDeleted) assertThat(numberOfRowsDeleted).isEqualTo(1) assertThat(getNumberOfModelsInTableForTest(table)).isEqualTo(7) } @Test fun testDeletionOfVarargModels() { val modelToBeDeleted1 = buildModelForTest(1) val modelToBeDeleted2 = buildModelForTest(2) insertModelsUsingInsertBuilder(table, modelToBeDeleted1, modelToBeDeleted2) insertAdditionalRandomModelsUsingInsertBuilder(table, count = 6) val deletedModel1 = buildModelForTest(66, modelToBeDeleted1.id1, modelToBeDeleted1.id2) val deletedModel2 = buildModelForTest(99, modelToBeDeleted2.id1, modelToBeDeleted2.id2) val numberOfRowsDeleted = table.dao.delete(deletedModel1, deletedModel2) assertAbsenceOf(table, deletedModel1, deletedModel2) assertThat(numberOfRowsDeleted).isEqualTo(2) assertThat(getNumberOfModelsInTableForTest(table)).isEqualTo(6) } @Test fun testDeletionOfModelIterable() { val modelToBeDeleted1 = buildModelForTest(1) val modelToBeDeleted2 = buildModelForTest(2) insertModelsUsingInsertBuilder(table, modelToBeDeleted1, modelToBeDeleted2) insertAdditionalRandomModelsUsingInsertBuilder(table, count = 6) val deletedModel1 = buildModelForTest(55, modelToBeDeleted1.id1, modelToBeDeleted1.id2) val deletedModel2 = buildModelForTest(77, modelToBeDeleted2.id1, modelToBeDeleted2.id2) val numberOfRowsDeleted = table.dao.delete(listOf(deletedModel1, deletedModel2)) assertAbsenceOf(table, deletedModel1, deletedModel2) assertThat(numberOfRowsDeleted).isEqualTo(2) assertThat(getNumberOfModelsInTableForTest(table)).isEqualTo(6) } @Test fun testSingleModelDeleteById() { val modelToBeDeleted = buildModelForTest(1) insertModelUsingInsertBuilder(table, modelToBeDeleted) insertAdditionalRandomModelsUsingInsertBuilder(table, count = 7) val numberOfRowsDeleted = table.dao.deleteById( TableForTest.Id(modelToBeDeleted.id1, modelToBeDeleted.id2) ) assertAbsenceOf(table, modelToBeDeleted) assertThat(numberOfRowsDeleted).isEqualTo(1) assertThat(getNumberOfModelsInTableForTest(table)).isEqualTo(7) } @Test fun testVarargModelsDeleteById() { val modelToBeDeleted1 = buildModelForTest(1) val modelToBeDeleted2 = buildModelForTest(2) insertModelsUsingInsertBuilder(table, modelToBeDeleted1, modelToBeDeleted2) insertAdditionalRandomModelsUsingInsertBuilder(table, count = 6) val deletedModel1 = buildModelForTest(66, modelToBeDeleted1.id1, modelToBeDeleted1.id2) val deletedModel2 = buildModelForTest(99, modelToBeDeleted2.id1, modelToBeDeleted2.id2) val numberOfRowsDeleted = table.dao.deleteById( TableForTest.Id(deletedModel1.id1, deletedModel1.id2), TableForTest.Id(deletedModel2.id1, deletedModel2.id2) ) assertAbsenceOf(table, deletedModel1, deletedModel2) assertThat(numberOfRowsDeleted).isEqualTo(2) assertThat(getNumberOfModelsInTableForTest(table)).isEqualTo(6) } @Test fun testModelIterableDeleteById() { val modelToBeDeleted1 = buildModelForTest(1) val modelToBeDeleted2 = buildModelForTest(2) insertModelsUsingInsertBuilder(table, modelToBeDeleted1, modelToBeDeleted2) insertAdditionalRandomModelsUsingInsertBuilder(table, count = 6) val deletedModel1 = buildModelForTest(55, modelToBeDeleted1.id1, modelToBeDeleted1.id2) val deletedModel2 = buildModelForTest(77, modelToBeDeleted2.id1, modelToBeDeleted2.id2) val numberOfRowsDeleted = table.dao.deleteById(listOf( TableForTest.Id(deletedModel1.id1, deletedModel1.id2), TableForTest.Id(deletedModel2.id1, deletedModel2.id2) )) assertAbsenceOf(table, deletedModel1, deletedModel2) assertThat(numberOfRowsDeleted).isEqualTo(2) assertThat(getNumberOfModelsInTableForTest(table)).isEqualTo(6) } @Test fun testDeletionHasNoEffectIfModelDoesNotExist() { insertAdditionalRandomModelsUsingInsertBuilder(table, count = 8) val nonExistingModel = buildModelForTest(1) val numberOfRowsDeleted = table.dao.delete(nonExistingModel) assertAbsenceOf(table, nonExistingModel) assertThat(numberOfRowsDeleted).isEqualTo(0) assertThat(getNumberOfModelsInTableForTest(table)).isEqualTo(8) } }
apache-2.0
jayrave/falkon
falkon-dao/src/test/kotlin/com/jayrave/falkon/dao/insertOrReplace/InsertOrReplaceBuilderImplTest.kt
1
14504
package com.jayrave.falkon.dao.insertOrReplace import com.jayrave.falkon.dao.insertOrReplace.testLib.InsertOrReplaceSqlBuilderForTesting import com.jayrave.falkon.dao.testLib.* import com.jayrave.falkon.engine.Type import com.jayrave.falkon.engine.TypedNull import com.jayrave.falkon.sqlBuilders.InsertOrReplaceSqlBuilder import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown import org.junit.Test import com.jayrave.falkon.dao.testLib.NullableFlagPairConverter as NFPC class InsertOrReplaceBuilderImplTest { @Test fun `insert or replace with one id column`() { val bundle = Bundle.default() val table = bundle.table val engine = bundle.engine val sqlBuilder = bundle.sqlBuilder // build & compile val builder = InsertOrReplaceBuilderImpl(table, sqlBuilder).values { set(table.int, 5) } val actualInsertOrReplace = builder.build() builder.insertOrReplace() // build expected insert or replace val expectedSql = sqlBuilder.build(table.name, listOf(table.int.name), emptyList()) val expectedInsertOrReplace = InsertOrReplaceImpl(table.name, expectedSql, listOf(5)) // Verify assertEquality(actualInsertOrReplace, expectedInsertOrReplace) assertThat(engine.compiledStatementsForInsertOrReplace).hasSize(1) val statement = engine.compiledStatementsForInsertOrReplace.first() assertThat(statement.tableName).isEqualTo(table.name) assertThat(statement.sql).isEqualTo(expectedSql) assertThat(statement.boundArgs).hasSize(1) assertThat(statement.intBoundAt(1)).isEqualTo(5) } @Test fun `insert or replace with one non id column`() { val bundle = Bundle.default() val table = bundle.table val engine = bundle.engine val sqlBuilder = bundle.sqlBuilder // build & compile val builder = InsertOrReplaceBuilderImpl(table, sqlBuilder).values { set(table.float, 5F) } val actualInsertOrReplace = builder.build() builder.insertOrReplace() // build expected insert or replace val expectedSql = sqlBuilder.build(table.name, emptyList(), listOf(table.float.name)) val expectedInsertOrReplace = InsertOrReplaceImpl(table.name, expectedSql, listOf(5F)) // Verify assertEquality(actualInsertOrReplace, expectedInsertOrReplace) assertThat(engine.compiledStatementsForInsertOrReplace).hasSize(1) val statement = engine.compiledStatementsForInsertOrReplace.first() assertThat(statement.tableName).isEqualTo(table.name) assertThat(statement.sql).isEqualTo(expectedSql) assertThat(statement.boundArgs).hasSize(1) assertThat(statement.floatBoundAt(1)).isEqualTo(5F) } @Test fun `insert or replace with multiple id columns followed by multiple non id columns`() { val bundle = Bundle.default() val table = bundle.table val engine = bundle.engine val sqlBuilder = bundle.sqlBuilder // build & compile val builder = InsertOrReplaceBuilderImpl(table, sqlBuilder).values { set(table.int, 5) set(table.string, "test 6") set(table.blob, byteArrayOf(7)) set(table.nullableDouble, 8.0) } val actualInsertOrReplace = builder.build() builder.insertOrReplace() // build expected insert or replace val expectedSql = sqlBuilder.build( table.name, listOf(table.int.name, table.string.name), listOf(table.blob.name, table.nullableDouble.name) ) val expectedInsertOrReplace = InsertOrReplaceImpl( table.name, expectedSql, listOf(5, "test 6", byteArrayOf(7), 8.0) ) // Verify assertEquality(actualInsertOrReplace, expectedInsertOrReplace) assertThat(engine.compiledStatementsForInsertOrReplace).hasSize(1) val statement = engine.compiledStatementsForInsertOrReplace.first() assertThat(statement.tableName).isEqualTo(table.name) assertThat(statement.sql).isEqualTo(expectedSql) assertThat(statement.boundArgs).hasSize(4) assertThat(statement.intBoundAt(1)).isEqualTo(5) assertThat(statement.stringBoundAt(2)).isEqualTo("test 6") assertThat(statement.blobBoundAt(3)).isEqualTo(byteArrayOf(7)) assertThat(statement.doubleBoundAt(4)).isEqualTo(8.0) } @Test fun `insert or replace throws if unexpected number of rows are affected & compiled statement gets closed`() { testInsertOrReplaceThrowsIfUnexpectedNumberOfRowsAreAffectedAndCsIsClosed(-2, true) testInsertOrReplaceThrowsIfUnexpectedNumberOfRowsAreAffectedAndCsIsClosed(-1, true) testInsertOrReplaceThrowsIfUnexpectedNumberOfRowsAreAffectedAndCsIsClosed(0, true) testInsertOrReplaceThrowsIfUnexpectedNumberOfRowsAreAffectedAndCsIsClosed(1, false) testInsertOrReplaceThrowsIfUnexpectedNumberOfRowsAreAffectedAndCsIsClosed(2, true) } @Test fun `compiled statement gets closed even if insert or replace throws`() { val engine = EngineForTestingBuilders.createWithOneShotStatements( insertOrReplaceProvider = { tableName, sql -> IntReturningOneShotCompiledStatementForTest( tableName, sql, shouldThrowOnExecution = true ) } ) val table = TableForTest(configuration = defaultTableConfiguration(engine)) val builder = InsertOrReplaceBuilderImpl(table, INSERT_OR_REPLACE_SQL_BUILDER) val exceptionWasThrown = try { builder.values { set(table.int, 5) }.insertOrReplace() false } catch (e: Exception) { true } when { !exceptionWasThrown -> failBecauseExceptionWasNotThrown(Exception::class.java) else -> { // Assert that the statement was not successfully executed but closed val statement = engine.compiledStatementsForInsertOrReplace.first() assertThat(statement.wasExecutionAttempted).isTrue() assertThat(statement.isExecuted).isFalse() assertThat(statement.isClosed).isTrue() } } } @Test fun `setting value for an already set column, overrides the existing value`() { val bundle = Bundle.default() val table = bundle.table val engine = bundle.engine val sqlBuilder = bundle.sqlBuilder // build & compile val initialValue = 5 val overwritingValue = initialValue + 1 val builder = InsertOrReplaceBuilderImpl(table, sqlBuilder).values { set(table.int, initialValue) set(table.int, overwritingValue) set(table.float, initialValue.toFloat()) set(table.float, overwritingValue.toFloat()) } val actualInsertOrReplace = builder.build() builder.insertOrReplace() // build expected insert or replace val expectedSql = sqlBuilder.build( table.name, listOf(table.int.name), listOf(table.float.name) ) val expectedInsertOrReplace = InsertOrReplaceImpl(table.name, expectedSql, listOf(6, 6F)) // Verify assertEquality(actualInsertOrReplace, expectedInsertOrReplace) assertThat(engine.compiledStatementsForInsertOrReplace).hasSize(1) val statement = engine.compiledStatementsForInsertOrReplace.first() assertThat(statement.tableName).isEqualTo(table.name) assertThat(statement.sql).isEqualTo(expectedSql) assertThat(statement.boundArgs).hasSize(2) assertThat(statement.intBoundAt(1)).isEqualTo(6) assertThat(statement.floatBoundAt(2)).isEqualTo(6F) } @Test fun `setting values for columns does not fire insert or replace`() { val bundle = Bundle.default() val table = bundle.table val engine = bundle.engine val sqlBuilder = bundle.sqlBuilder InsertOrReplaceBuilderImpl(table, sqlBuilder).values { set(table.int, 5) set(table.nullableString, null) } assertThat(engine.compiledStatementsForInsertOrReplace).isEmpty() } @Test fun `all types are bound correctly`() { val bundle = Bundle.default() val table = bundle.table val engine = bundle.engine val sqlBuilder = bundle.sqlBuilder // build & compile val builder = InsertOrReplaceBuilderImpl(table, sqlBuilder).values { set(table.short, 5.toShort()) set(table.int, 6) set(table.long, 7L) set(table.float, 8F) set(table.double, 9.toDouble()) set(table.string, "test 10") set(table.blob, byteArrayOf(11)) set(table.flagPair, FlagPair(false, true)) set(table.nullableShort, null) set(table.nullableInt, null) set(table.nullableLong, null) set(table.nullableFloat, null) set(table.nullableDouble, null) set(table.nullableString, null) set(table.nullableBlob, null) set(table.nullableFlagPair, null) } val actualInsertOrReplace = builder.build() builder.insertOrReplace() // build expected insert or replace val expectedSql = sqlBuilder.build( table.name, listOf( table.short.name, table.int.name, table.string.name, table.nullableFloat.name ), listOf( table.long.name, table.float.name, table.double.name, table.blob.name, table.flagPair.name, table.nullableShort.name, table.nullableInt.name, table.nullableLong.name, table.nullableDouble.name, table.nullableString.name, table.nullableBlob.name, table.nullableFlagPair.name ) ) val expectedInsertOrReplace = InsertOrReplaceImpl( table.name, expectedSql, listOf( 5.toShort(), 6, "test 10", TypedNull(Type.FLOAT), 7L, 8F, 9.0, byteArrayOf(11), NFPC.asShort(FlagPair(false, true)), TypedNull(Type.SHORT), TypedNull(Type.INT), TypedNull(Type.LONG), TypedNull(Type.DOUBLE), TypedNull(Type.STRING), TypedNull(Type.BLOB), TypedNull(NFPC.dbType) ) ) // Verify assertEquality(actualInsertOrReplace, expectedInsertOrReplace) assertThat(engine.compiledStatementsForInsertOrReplace).hasSize(1) val statement = engine.compiledStatementsForInsertOrReplace.first() assertThat(statement.tableName).isEqualTo(table.name) assertThat(statement.sql).isEqualTo(expectedSql) assertThat(statement.boundArgs).hasSize(16) assertThat(statement.shortBoundAt(1)).isEqualTo(5.toShort()) assertThat(statement.intBoundAt(2)).isEqualTo(6) assertThat(statement.stringBoundAt(3)).isEqualTo("test 10") assertThat(statement.isNullBoundAt(4)).isTrue() assertThat(statement.longBoundAt(5)).isEqualTo(7L) assertThat(statement.floatBoundAt(6)).isEqualTo(8F) assertThat(statement.doubleBoundAt(7)).isEqualTo(9.toDouble()) assertThat(statement.blobBoundAt(8)).isEqualTo(byteArrayOf(11)) assertThat(statement.shortBoundAt(9)).isEqualTo(NFPC.asShort(FlagPair(false, true))) assertThat(statement.isNullBoundAt(10)).isTrue() assertThat(statement.isNullBoundAt(11)).isTrue() assertThat(statement.isNullBoundAt(12)).isTrue() assertThat(statement.isNullBoundAt(13)).isTrue() assertThat(statement.isNullBoundAt(14)).isTrue() assertThat(statement.isNullBoundAt(15)).isTrue() assertThat(statement.isNullBoundAt(16)).isTrue() } private class Bundle( val table: TableForTest, val engine: EngineForTestingBuilders, val sqlBuilder: InsertOrReplaceSqlBuilder) { companion object { fun default(): Bundle { val engine = EngineForTestingBuilders.createWithOneShotStatements() val table = TableForTest(configuration = defaultTableConfiguration(engine)) return Bundle(table, engine, INSERT_OR_REPLACE_SQL_BUILDER) } } } companion object { private val INSERT_OR_REPLACE_SQL_BUILDER = InsertOrReplaceSqlBuilderForTesting() private fun assertEquality(actual: InsertOrReplace, expected: InsertOrReplace) { assertThat(actual.tableName).isEqualTo(expected.tableName) assertThat(actual.sql).isEqualTo(expected.sql) assertThat(actual.arguments).containsExactlyElementsOf(expected.arguments) } /** * CS stands for compiled statement */ private fun testInsertOrReplaceThrowsIfUnexpectedNumberOfRowsAreAffectedAndCsIsClosed( numberOfRowsInsertedOrReplaced: Int, shouldThrow: Boolean) { val engine = EngineForTestingBuilders.createWithOneShotStatements( insertOrReplaceProvider = { tableName, sql -> IntReturningOneShotCompiledStatementForTest( tableName, sql, numberOfRowsInsertedOrReplaced ) } ) val table = TableForTest(configuration = defaultTableConfiguration(engine)) val builder = InsertOrReplaceBuilderImpl(table, INSERT_OR_REPLACE_SQL_BUILDER) val exceptionThrown = try { assertThat(builder.values { set(table.int, 5) }.insertOrReplace()) false } catch (e: Exception) { true } // Assert that the statement was executed and closed val statement = engine.compiledStatementsForInsertOrReplace.first() assertThat(statement.isExecuted).isTrue() assertThat(statement.isClosed).isTrue() // Assert exception was thrown if it was supposed to assertThat(exceptionThrown).isEqualTo(shouldThrow) } } }
apache-2.0
Takhion/android-extras-delegates
library/src/main/java/me/eugeniomarletti/extras/bundle/Utils.kt
1
3596
@file:Suppress("NOTHING_TO_INLINE") package me.eugeniomarletti.extras.bundle import android.os.Bundle import me.eugeniomarletti.extras.putExtra import me.eugeniomarletti.extras.readBoolean import me.eugeniomarletti.extras.readByte import me.eugeniomarletti.extras.readChar import me.eugeniomarletti.extras.readDouble import me.eugeniomarletti.extras.readFloat import me.eugeniomarletti.extras.readInt import me.eugeniomarletti.extras.readLong import me.eugeniomarletti.extras.readShort @PublishedApi internal inline fun getBoolean( receiver: Bundle, name: String ) = receiver.readBoolean( Bundle::containsKey, Bundle::getBoolean, name) @PublishedApi internal inline fun getInt( receiver: Bundle, name: String ) = receiver.readInt( Bundle::containsKey, Bundle::getInt, name) @PublishedApi internal inline fun getLong( receiver: Bundle, name: String ) = receiver.readLong( Bundle::containsKey, Bundle::getLong, name) @PublishedApi internal inline fun getShort( receiver: Bundle, name: String ) = receiver.readShort( Bundle::containsKey, Bundle::getShort, name) @PublishedApi internal inline fun getDouble( receiver: Bundle, name: String ) = receiver.readDouble( Bundle::containsKey, Bundle::getDouble, name) @PublishedApi internal inline fun getFloat( receiver: Bundle, name: String ) = receiver.readFloat( Bundle::containsKey, Bundle::getFloat, name) @PublishedApi internal inline fun getChar( receiver: Bundle, name: String ) = receiver.readChar( Bundle::containsKey, Bundle::getChar, name) @PublishedApi internal inline fun getByte( receiver: Bundle, name: String ) = receiver.readByte( Bundle::containsKey, Bundle::getByte, name) @PublishedApi internal inline fun putBoolean( receiver: Bundle, name: String, value: Boolean? ) = receiver.putExtra( Bundle::remove, Bundle::putBoolean, name, value) @PublishedApi internal inline fun putInt( receiver: Bundle, name: String, value: Int? ) = receiver.putExtra( Bundle::remove, Bundle::putInt, name, value) @PublishedApi internal inline fun putLong( receiver: Bundle, name: String, value: Long? ) = receiver.putExtra( Bundle::remove, Bundle::putLong, name, value) @PublishedApi internal inline fun putShort( receiver: Bundle, name: String, value: Short? ) = receiver.putExtra( Bundle::remove, Bundle::putShort, name, value) @PublishedApi internal inline fun putDouble( receiver: Bundle, name: String, value: Double? ) = receiver.putExtra( Bundle::remove, Bundle::putDouble, name, value) @PublishedApi internal inline fun putFloat( receiver: Bundle, name: String, value: Float? ) = receiver.putExtra( Bundle::remove, Bundle::putFloat, name, value) @PublishedApi internal inline fun putChar( receiver: Bundle, name: String, value: Char? ) = receiver.putExtra( Bundle::remove, Bundle::putChar, name, value) @PublishedApi internal inline fun putByte( receiver: Bundle, name: String, value: Byte? ) = receiver.putExtra( Bundle::remove, Bundle::putByte, name, value)
mit
upelsin/SquirrelDomain
domain/src/main/kotlin/com/squirrel/android/domain/commands/similarity/NaiveTracklistSimilarity.kt
1
1384
package com.squirrel.android.commands.similarity import rx.Observable import com.google.common.collect.ImmutableMultiset import com.google.common.collect.Multisets import com.squirrel.android.domain.model.SimilarityResult import com.squirrel.android.domain.model.Tracklist import com.squirrel.android.domain.LOGD /** * Calculates [SimilarityResult] for the two given sources of [Tracklist]s. * * Created by Alexey Dmitriev <[email protected]> on 11.01.2015. */ public open class NaiveTracklistSimilarity { fun similarities(baseTracklist: Observable<Tracklist>, otherTracklist: Observable<Tracklist>): Observable<SimilarityResult> { return Observable.combineLatest(baseTracklist, otherTracklist) {(baseTracklist, otherTracklist) -> val bt = ImmutableMultiset.copyOf(baseTracklist.getTracks()) val ot = ImmutableMultiset.copyOf(otherTracklist.getTracks()) val intersection = Multisets.intersection(bt, ot) val result = SimilarityResult( baseTracklist.owner, otherTracklist.owner, intersection.toList(), intersection.size() ) LOGD.d("Similarity for %s", result.otherChannel) result } } }
lgpl-3.0
PaleoCrafter/BitReplicator
src/main/kotlin/de/mineformers/bitreplicator/client/gui/SlotFontRenderer.kt
1
2190
package de.mineformers.bitreplicator.client.gui import de.mineformers.bitreplicator.client.getLocale import net.minecraft.client.Minecraft import net.minecraft.client.gui.FontRenderer import net.minecraft.util.ResourceLocation import java.text.NumberFormat class SlotFontRenderer : FontRenderer( Minecraft.getMinecraft().gameSettings, ResourceLocation("textures/font/ascii.png"), Minecraft.getMinecraft().textureManager, false) { private val alternative = Minecraft.getMinecraft().fontRendererObj var bypass = false override fun getStringWidth(text: String): Int { val displayedText = convertText(text) if (displayedText != text) { val oldFlag = alternative.unicodeFlag alternative.unicodeFlag = true val result = alternative.getStringWidth(displayedText) alternative.unicodeFlag = oldFlag return result } return super.getStringWidth(displayedText) } override fun drawString(text: String, x: Float, y: Float, color: Int, dropShadow: Boolean): Int { val displayedText = convertText(text) if (displayedText != text) { val oldFlag = alternative.unicodeFlag alternative.unicodeFlag = true val result = alternative.drawString(displayedText, x, y, color, dropShadow) alternative.unicodeFlag = oldFlag return result } return super.drawString(displayedText, x, y, color, dropShadow) } private fun convertText(text: String): String { if (bypass) return text if (!text.matches(Regex("\\d+"))) return text val number = text.toInt() if (number < 100) return text if (number < 1000) return " " + text val numberFormat = NumberFormat.getInstance(Minecraft.getMinecraft().getLocale()) numberFormat.maximumFractionDigits = 0 if (number < 100000) { numberFormat.maximumFractionDigits = 1 } if (number < 10000) { numberFormat.maximumFractionDigits = 2 } return numberFormat.format(number / 1000.0) + "k" } }
mit
nickthecoder/tickle
tickle-editor/src/main/kotlin/uk/co/nickthecoder/tickle/editor/scene/history/ChangePolarParameter.kt
1
2044
/* Tickle Copyright (C) 2017 Nick Robinson 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 uk.co.nickthecoder.tickle.editor.scene.history import uk.co.nickthecoder.tickle.editor.resources.DesignActorResource import uk.co.nickthecoder.tickle.editor.resources.ModificationType import uk.co.nickthecoder.tickle.editor.scene.SceneEditor import uk.co.nickthecoder.tickle.editor.util.PolarParameter class ChangePolarParameter( private val actorResource: DesignActorResource, private val parameter: PolarParameter, private var newDegrees: Double, private var newMagnitude: Double ) : Change { private val oldDegrees = parameter.angle ?: 0.0 private val oldMagnitude = parameter.magnitude ?: 0.0 override fun redo(sceneEditor: SceneEditor) { parameter.angle = newDegrees parameter.magnitude = newMagnitude sceneEditor.sceneResource.fireChange(actorResource, ModificationType.CHANGE) } override fun undo(sceneEditor: SceneEditor) { parameter.angle = oldDegrees parameter.magnitude = oldMagnitude sceneEditor.sceneResource.fireChange(actorResource, ModificationType.CHANGE) } override fun mergeWith(other: Change): Boolean { if (other is ChangePolarParameter && other.actorResource == actorResource) { other.newDegrees = newDegrees other.newMagnitude = newMagnitude return true } return false } }
gpl-3.0
danirod/rectball
app/src/main/java/es/danirod/rectball/android/AbstractPlatform.kt
1
1459
/* * This file is part of Rectball * Copyright (C) 2015-2017 Dani Rodríguez * * 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 es.danirod.rectball.android import android.content.Intent /** * This is the interface for platform code. Platform code is code that depends * on the platform that the application is running. Whenever features can only * in a particular platform, platform dependent code should be used. For * instance, adding Google APIs or Android APIs must be done in Android code * to prevent desktop releases from failing. * * @author danirod * @since 0.4.0 */ internal abstract class AbstractPlatform(val context: AndroidLauncher) { abstract fun onStart() abstract fun onStop() abstract fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) abstract val gameServices: GameServices }
gpl-3.0
Logarius/WIMM-Android
app/src/main/java/net/oschina/git/roland/wimm/common/base/WIMMConstants.kt
1
361
package net.oschina.git.roland.wimm.common.base /** * Created by Roland on 2017/4/10. */ object WIMMConstants { /** * SharedPreference */ val SHARED_PREFERENCE_NAME = "wimm" val SP_KEY_LAST_LOGIN_USER = "SP_KEY_LAST_LOGIN_USER" /** * RunningAccount Date Format */ val RUNNING_ACCOUNT_DATE_FORMAT = "yyyy-MM-dd" }
gpl-2.0
Geobert/Efficio
app/src/androidTest/kotlin/fr/geobert/efficio/EfficioTest.kt
1
6068
package fr.geobert.efficio import android.support.test.espresso.Espresso import android.support.test.espresso.Espresso.onView import android.support.test.espresso.action.ViewActions.click import android.support.test.espresso.action.ViewActions.replaceText import android.support.test.espresso.assertion.ViewAssertions.matches import android.support.test.espresso.matcher.ViewMatchers.* import android.support.test.filters.LargeTest import android.support.test.rule.ActivityTestRule import android.support.test.runner.AndroidJUnit4 import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith /** * [Testing Fundamentals](http://d.android.com/tools/testing/testing_android.html) */ @RunWith(AndroidJUnit4::class) @LargeTest class EfficioTest { @Rule @JvmField var activityRule: ActivityTestRule<MainActivity> = ActivityTestRule(MainActivity::class.java) init { MainActivity.TEST_MODE = true } @Test fun testEnterSameItem() { addItem(ITEM_A, DEP_A) checkTaskListSize(1) addItem(ITEM_A) checkTaskListSize(1) } @Test fun testEditItemName() { addItem(ITEM_A, DEP_A) clickOnTask(0) onView(withId(R.id.item_name_edt)).perform(replaceText(ITEM_B)) onView(withId(R.id.confirm)).perform(click()) onView(withText(ITEM_B)).check(matches(isDisplayed())) } // check the sort after drag an item @Test fun testSort2Items() { addItem(ITEM_A, DEP_B) checkTaskListSize(1) addItem(ITEM_B, DEP_A) checkTaskListSize(2) // check dep order in dep editor clickInDrawer(R.id.edit_departments) checkOrderOfDeps(DEP_B, DEP_A) Espresso.pressBack() pauseTest(300) // creating an item, weight = max weight + 1, so B is last checkOrderOfTask(ITEM_A, ITEM_B) // drag B above A dragTask(1, Direction.UP) checkOrderOfTask(ITEM_B, ITEM_A) // set B as done clickTickOfTaskAt(0) // B going to bottom, A should be first checkOrderOfTask(ITEM_A, COMPLETED, ITEM_B) // uncheck B, position is 2 and not 1 because of header clickTickOfTaskAt(2) // B should go back to first pos checkOrderOfTask(ITEM_B, ITEM_A) // go to dep editor and back to refresh list and check order again clickInDrawer(R.id.edit_departments) // check order, as Item B is in Dep A, Dep A should be 1st after Item B was dragged up checkOrderOfDeps(DEP_A, DEP_B) Espresso.pressBack() pauseTest(300) checkOrderOfTask(ITEM_B, ITEM_A) // change dep order clickInDrawer(R.id.edit_departments) dragDep(1, Direction.UP) checkOrderOfDeps(DEP_B, DEP_A) Espresso.pressBack() checkOrderOfTask(ITEM_A, ITEM_B) } @Test fun testSort3Items() { addItem(ITEM_A, DEP_B) addItem(ITEM_B, DEP_B) addItem(ITEM_C, DEP_B) checkOrderOfTask(ITEM_A, ITEM_B, ITEM_C) // drag C above B dragTask(2, Direction.UP) checkOrderOfTask(ITEM_A, ITEM_C, ITEM_B) clickInDrawer(R.id.edit_departments) Espresso.pressBack() pauseTest(300) checkOrderOfTask(ITEM_A, ITEM_C, ITEM_B) addItem(ITEM_D, DEP_A) checkOrderOfTask(ITEM_A, ITEM_C, ITEM_B, ITEM_D) // drag D above B dragTask(3, Direction.UP) // D has diff dep as others, so its dep going above their dep, hence D is first checkOrderOfTask(ITEM_D, ITEM_A, ITEM_C, ITEM_B) clickInDrawer(R.id.edit_departments) Espresso.pressBack() pauseTest(300) checkOrderOfTask(ITEM_D, ITEM_A, ITEM_C, ITEM_B) // tick D, should fall at the bottom clickTickOfTaskAt(0) checkOrderOfTask(ITEM_A, ITEM_C, ITEM_B, COMPLETED, ITEM_D) // tick A clickTickOfTaskAt(0) checkOrderOfTask(ITEM_C, ITEM_B, COMPLETED, ITEM_D, ITEM_A) // untick D clickTickOfTaskAt(3) checkOrderOfTask(ITEM_D, ITEM_C, ITEM_B, COMPLETED, ITEM_A) // untick A clickTickOfTaskAt(4) checkOrderOfTask(ITEM_D, ITEM_A, ITEM_C, ITEM_B) // drag D under A dragTask(0, Direction.DOWN) checkOrderOfTask(ITEM_A, ITEM_C, ITEM_B, ITEM_D) // drag C above A dragTask(1, Direction.UP) checkOrderOfTask(ITEM_C, ITEM_A, ITEM_B, ITEM_D) // tick A clickTickOfTaskAt(1) checkOrderOfTask(ITEM_C, ITEM_B, ITEM_D, COMPLETED, ITEM_A) // untick A clickTickOfTaskAt(4) checkOrderOfTask(ITEM_C, ITEM_A, ITEM_B, ITEM_D) } @Test fun testChangeItemDep() { addItem(ITEM_A, DEP_B) addItem(ITEM_B, DEP_A) addItem(ITEM_C, DEP_A) checkOrderOfTask(ITEM_A, ITEM_B, ITEM_C) // put C above A, so it get some weight dragTask(2, Direction.UP, 2) checkOrderOfTask(ITEM_C, ITEM_B, ITEM_A) // change C dep to the same as A, should reset item's weight, so under B clickOnTask(0) Espresso.closeSoftKeyboard() onView(withText(DEP_B)).perform(click()) onView(withId(R.id.confirm)).perform(click()) checkOrderOfTask(ITEM_B, ITEM_A, ITEM_C) // add 3rd dep addItem(ITEM_D, DEP_C) checkOrderOfTask(ITEM_B, ITEM_A, ITEM_C, ITEM_D) // drag D between A and C, should end between B and A dragTask(3, Direction.UP) checkOrderOfTask(ITEM_B, ITEM_D, ITEM_A, ITEM_C) dragTask(2, Direction.UP) checkOrderOfTask(ITEM_B, ITEM_A, ITEM_C, ITEM_D) dragTask(1, Direction.DOWN) checkOrderOfTask(ITEM_B, ITEM_C, ITEM_A, ITEM_D) dragTask(3, Direction.UP) checkOrderOfTask(ITEM_B, ITEM_D, ITEM_C, ITEM_A) addItem(ITEM_E, DEP_D) checkOrderOfTask(ITEM_B, ITEM_D, ITEM_C, ITEM_A, ITEM_E) dragTask(4, Direction.UP) checkOrderOfTask(ITEM_B, ITEM_D, ITEM_E, ITEM_C, ITEM_A) } }
gpl-2.0
droibit/quickly
app/src/main/kotlin/com/droibit/quickly/main/apps/AppsModule.kt
1
916
package com.droibit.quickly.main.apps import com.droibit.quickly.main.mainModule import com.github.salomonbrys.kodein.Kodein import com.github.salomonbrys.kodein.instance import com.github.salomonbrys.kodein.provider import com.github.salomonbrys.kodein.singleton import rx.subscriptions.CompositeSubscription fun appsModule(view: AppsContract.View, navigator: AppsContract.Navigator) = Kodein.Module { import(mainModule()) bind<AppsContract.View>() with instance(view) bind<AppsContract.Navigator>() with instance(navigator) bind<AppsContract.Presenter>() with provider { AppsPresenter( view = instance(), navigator = instance(), loadTask = instance(), showSettingsTask = instance(), subscriptions = instance() ) } bind<CompositeSubscription>() with singleton { CompositeSubscription() } }
apache-2.0
square/kotlinpoet
interop/kotlinx-metadata/src/test/kotlin/com/squareup/kotlinpoet/metadata/specs/NoJvmNameFacadeFile.kt
1
667
/* * Copyright (C) 2021 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.squareup.kotlinpoet.metadata.specs val prop: String = ""
apache-2.0
mbuenoferrer/barfastic
app/src/main/kotlin/com/refactorizado/barfastic/presentation/di/modules/ActivityModule.kt
1
914
package com.refactorizado.barfastic.presentation.di.modules import android.app.Activity import android.content.Context import com.refactorizado.barfastic.data.food.LocalFoodRepository import com.refactorizado.barfastic.domain.food.boundary.FoodRepository import com.refactorizado.barfastic.domain.food.usecase.GetFoodListUseCase import com.refactorizado.barfastic.presentation.di.scope.ActivityScope import com.refactorizado.barfastic.presentation.food.presenter.FoodListPresenter import dagger.Module import dagger.Provides import javax.inject.Singleton @Module class ActivityModule(private val activityContext: Activity) { @Provides @ActivityScope fun provideActivityContext(): Context { return activityContext } @Provides @ActivityScope fun provideFoodListPresenter(getFoodListUseCase: GetFoodListUseCase): FoodListPresenter = FoodListPresenter(getFoodListUseCase) }
mit
MoonCheesez/sstannouncer
sstannouncer/app/src/main/java/sst/com/anouncements/feed/ui/FeedAdapter.kt
1
1684
package sst.com.anouncements.feed.ui import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import android.widget.TextView import sst.com.anouncements.R import sst.com.anouncements.feed.model.Entry class FeedAdapter( private var entries: List<Entry>, private val onItemClickListener: (Entry) -> Unit ) : RecyclerView.Adapter<FeedAdapter.FeedViewHolder>() { class FeedViewHolder(feedView: ViewGroup) : RecyclerView.ViewHolder(feedView) { val titleTextView: TextView = feedView.findViewById(R.id.title_text_view) val excerptTextView: TextView = feedView.findViewById(R.id.excerpt_text_view) val dateTextView: TextView = feedView.findViewById(R.id.date_text_view) val layoutView : View = feedView.findViewById(R.id.feed_item_layout) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FeedViewHolder { val feedView = LayoutInflater.from(parent.context) .inflate(R.layout.recyclerview_feed_item, parent, false) as ViewGroup return FeedViewHolder(feedView) } override fun onBindViewHolder(holder: FeedViewHolder, position: Int) { val entry: Entry = entries[position] holder.titleTextView.text = entry.title holder.excerptTextView.text = entry.contentWithoutHTML holder.dateTextView.text = entry.relativePublishedDate holder.layoutView.setOnClickListener { onItemClickListener(entry) } } override fun getItemCount() = entries.size fun setEntries(newEntries: List<Entry>) { entries = newEntries notifyDataSetChanged() } }
mit
MichaelRocks/lightsaber
processor/src/main/java/io/michaelrocks/lightsaber/processor/commons/DependencyExtensions.kt
1
857
/* * Copyright 2018 Michael Rozumyanskiy * * 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 io.michaelrocks.lightsaber.processor.commons import io.michaelrocks.lightsaber.processor.model.Dependency fun Dependency.boxed(): Dependency { val boxedType = type.boxed() return if (boxedType === type) this else copy(type = boxedType) }
apache-2.0
uditverma5602/shangri-la
app/src/main/java/com/udit/shangri_la/utilities/extensions.kt
1
313
package com.udit.shangri_la.utilities import android.content.Context import com.udit.shangri_la.ShangriLaApplication import com.udit.shangri_la.di.components.AppComponent /** * Created by Udit on 01/10/17. */ fun Context.getAppComponent(): AppComponent = (applicationContext as ShangriLaApplication).component
apache-2.0
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/images/RomeroBrittoCommand.kt
1
503
package net.perfectdreams.loritta.morenitta.commands.vanilla.images import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.morenitta.commands.vanilla.images.base.GabrielaImageServerCommandBase class RomeroBrittoCommand(m: LorittaBot) : GabrielaImageServerCommandBase( m, listOf("romerobritto", "pintura", "painting"), 1, "commands.command.romerobritto.description", "/api/v1/images/romero-britto", "romero_britto.png", slashCommandName = "brmemes romerobritto" )
agpl-3.0
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/utils/metrics/KordMetrics.kt
1
271
package net.perfectdreams.loritta.cinnamon.discord.utils.metrics object KordMetrics : PrometheusMetrics() { val requests = createCounterWithLabels("kord_requests_count", "How many HTTP requests were made by Kord") { labelNames("route", "http_method") } }
agpl-3.0
shiraji/permissions-dispatcher-plugin
src/main/kotlin/com/github/shiraji/permissionsdispatcherplugin/data/AndroidGradleVersion.kt
1
583
package com.github.shiraji.permissionsdispatcherplugin.data class AndroidGradleVersion(versionText: String) { private var major: Int private var minor: Int init { try { major = versionText.substringBefore(".").toInt() minor = versionText.substring(versionText.indexOf(".") + 1, versionText.lastIndexOf(".")).toInt() } catch (e: NumberFormatException) { major = -1 minor = -1 } } fun isHigherThan2_2() = major > 2 || major == 2 && minor >= 2 fun isValid() = major >= 0 && minor >= 0 }
apache-2.0
luiqn2007/miaowo
app/src/main/java/org/miaowo/miaowo/other/CircleTransformation.kt
1
1319
package org.miaowo.miaowo.other import android.graphics.Bitmap import android.graphics.BitmapShader import android.graphics.Canvas import android.graphics.Matrix import android.graphics.Paint import android.graphics.Shader import com.squareup.picasso.Transformation /** * Picasso 加载剪裁圆形 * Created by luqin on 17-4-11. */ class CircleTransformation : Transformation { override fun transform(source: Bitmap): Bitmap { val width = source.width val height = source.height val size = Math.min(width, height) val r = (size / 2).toFloat() val dw = (width - size).toFloat() val dh = (height - size).toFloat() val result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888) val canvas = Canvas(result) val paint = Paint() val shader = BitmapShader(source, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP) paint.shader = shader paint.isAntiAlias = true paint.isDither = true if (dw != 0f || dh != 0f) { val centerMatrix = Matrix() centerMatrix.setTranslate(-dw / 2, -dh / 2) canvas.matrix = centerMatrix } canvas.drawCircle(r, r, r, paint) source.recycle() return result } override fun key() = "toCircle()" }
apache-2.0
usommerl/kotlin-koans
src/v_builders/_37_StringAndMapBuilders.kt
1
1054
package v_builders import util.TODO import java.util.* import kotlin.collections.HashMap fun buildStringExample(): String { fun buildString(build: StringBuilder.() -> Unit): String { val stringBuilder = StringBuilder() stringBuilder.build() return stringBuilder.toString() } return buildString { this.append("Numbers: ") for (i in 1..10) { // 'this' can be omitted append(i) } } } fun todoTask37(): Nothing = TODO( """ Task 37. Uncomment the commented code and make it compile. Add and implement function 'buildMap' with one parameter (of type extension function) creating a new HashMap, building it and returning it as a result. """ ) fun <K,V> buildMap(build: HashMap<K,V>.() -> Unit): HashMap<K,V> { val map: HashMap<K,V> = HashMap() map.build() return map } fun task37(): Map<Int, String> { return buildMap { put(0, "0") for (i in 1..10) { put(i, "$i") } } }
mit
cbeyls/fosdem-companion-android
app/src/main/java/be/digitalia/fosdem/db/entities/EventToPerson.kt
1
539
package be.digitalia.fosdem.db.entities import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.Index @Entity(tableName = EventToPerson.TABLE_NAME, primaryKeys = ["event_id", "person_id"], indices = [Index(value = ["person_id"], name = "event_person_person_id_idx")]) class EventToPerson( @ColumnInfo(name = "event_id") val eventId: Long, @ColumnInfo(name = "person_id") val personId: Long ) { companion object { const val TABLE_NAME = "events_persons" } }
apache-2.0
eugeis/ee
ee-system/src/main/kotlin/ee/system/task/SystemTaskRegistry.kt
1
1924
package ee.system.task import ee.system.dev.BuildRequest import ee.system.dev.BuildToolFactory import ee.task.PathResolver import ee.task.TaskRepository open class SystemTaskRegistry : SystemTaskRegistryBase { companion object { val EMPTY = SystemTaskRegistryBase.EMPTY } constructor() : super() { } constructor(pathResolver: PathResolver, buildToolFactory: BuildToolFactory) : super(pathResolver, buildToolFactory) { } override fun register(repo: TaskRepository) { registerBuildTaskFactories(repo) } private fun registerBuildTaskFactories(repo: TaskRepository) { repo.register(BuildTaskFactory("build", "Build", pathResolver, buildToolFactory, BuildRequest().build())) repo.register(BuildTaskFactory("clean", "Build", pathResolver, buildToolFactory, BuildRequest().clean())) repo.register( BuildTaskFactory("cleanBuild", "Build", pathResolver, buildToolFactory, BuildRequest().clean().build())) repo.register(BuildTaskFactory("test", "Build", pathResolver, buildToolFactory, BuildRequest().test())) repo.register( BuildTaskFactory("buildTest", "Build", pathResolver, buildToolFactory, BuildRequest().build().test())) repo.register(BuildTaskFactory("cleanBuildTest", "Build", pathResolver, buildToolFactory, BuildRequest().clean().build().test())) repo.register(BuildTaskFactory("eclipse", "Eclipse", pathResolver, buildToolFactory, BuildRequest().task("eclipse").profile("eclipse"))) repo.register(BuildTaskFactory("cleanEclipse", "Eclipse", pathResolver, buildToolFactory, BuildRequest().task("cleanEclipse").profile("eclipse"))) } private fun registerServiceTaskFactories(repo: TaskRepository) { repo.register(BuildTaskFactory("start", "Service", pathResolver, buildToolFactory, BuildRequest().build())) } }
apache-2.0
daring2/fms
zabbix/core/src/main/kotlin/com/gitlab/daring/fms/zabbix/sender/ZabbixSender.kt
1
1099
package com.gitlab.daring.fms.zabbix.sender import com.gitlab.daring.fms.common.json.JsonUtils.JsonMapper import com.gitlab.daring.fms.common.network.SocketProvider import com.gitlab.daring.fms.common.network.SocketProviderImpl import com.gitlab.daring.fms.zabbix.model.ItemValue import com.gitlab.daring.fms.zabbix.util.ZabbixProtocolUtils.parseJsonResponse import com.typesafe.config.Config class ZabbixSender( val host: String, val port: Int = 10051, val socketProvider: SocketProvider = SocketProviderImpl(3000, 10000) ) { constructor(c: Config) : this(c.getString("host"), c.getInt("port"), SocketProviderImpl(c)) fun send(req: SendRequest): SendResult { val socket = socketProvider.createSocket(host, port) socket.use { val rn = req.buildJson() JsonMapper.writeValue(it.getOutputStream(), rn) return parseJsonResponse<SendResult>(it.getInputStream()) } } fun send(vararg vs: ItemValue): SendResult { val req = SendRequest(listOf(*vs)) return send(req) } }
apache-2.0
cliffano/swaggy-jenkins
clients/kotlin-server/generated/src/main/kotlin/org/openapitools/server/models/FreeStyleBuild.kt
1
1658
/** * Swaggy Jenkins * Jenkins API clients generated from Swagger / Open API specification * * The version of the OpenAPI document: 1.5.1-pre.0 * Contact: [email protected] * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package org.openapitools.server.models import org.openapitools.server.models.CauseAction import org.openapitools.server.models.EmptyChangeLogSet /** * * @param propertyClass * @param number * @param url * @param actions * @param building * @param description * @param displayName * @param duration * @param estimatedDuration * @param executor * @param fullDisplayName * @param id * @param keepLog * @param queueId * @param result * @param timestamp * @param builtOn * @param changeSet */ data class FreeStyleBuild( val propertyClass: kotlin.String? = null, val number: kotlin.Int? = null, val url: kotlin.String? = null, val actions: kotlin.collections.List<CauseAction>? = null, val building: kotlin.Boolean? = null, val description: kotlin.String? = null, val displayName: kotlin.String? = null, val duration: kotlin.Int? = null, val estimatedDuration: kotlin.Int? = null, val executor: kotlin.String? = null, val fullDisplayName: kotlin.String? = null, val id: kotlin.String? = null, val keepLog: kotlin.Boolean? = null, val queueId: kotlin.Int? = null, val result: kotlin.String? = null, val timestamp: kotlin.Int? = null, val builtOn: kotlin.String? = null, val changeSet: EmptyChangeLogSet? = null )
mit
jsargent7089/android
src/main/java/com/nextcloud/client/jobs/OfflineSyncWork.kt
1
6237
/* * Nextcloud Android client application * * @author Mario Danic * @author Chris Narkiewicz * Copyright (C) 2018 Mario Danic * Copyright (C) 2020 Chris Narkiewicz <[email protected]> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE * License as published by the Free Software Foundation; either * version 3 of the License, or 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 AFFERO GENERAL PUBLIC LICENSE for more details. * * You should have received a copy of the GNU Affero General Public * License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.nextcloud.client.jobs import android.content.ContentResolver import android.content.Context import android.os.Build import android.os.PowerManager import android.os.PowerManager.WakeLock import androidx.work.Worker import androidx.work.WorkerParameters import com.nextcloud.client.account.User import com.nextcloud.client.account.UserAccountManager import com.nextcloud.client.device.PowerManagementService import com.nextcloud.client.network.ConnectivityService import com.owncloud.android.MainApp import com.owncloud.android.datamodel.FileDataStorageManager import com.owncloud.android.datamodel.OCFile import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode import com.owncloud.android.lib.common.utils.Log_OC import com.owncloud.android.lib.resources.files.CheckEtagRemoteOperation import com.owncloud.android.operations.SynchronizeFileOperation import com.owncloud.android.utils.FileStorageUtils import java.io.File @Suppress("LongParameterList") // Legacy code class OfflineSyncWork constructor( private val context: Context, params: WorkerParameters, private val contentResolver: ContentResolver, private val userAccountManager: UserAccountManager, private val connectivityService: ConnectivityService, private val powerManagementService: PowerManagementService ) : Worker(context, params) { companion object { const val TAG = "OfflineSyncJob" private const val WAKELOCK_TAG_SEPARATION = ":" private const val WAKELOCK_ACQUISITION_TIMEOUT_MS = 10L * 60L * 1000L } override fun doWork(): Result { var wakeLock: WakeLock? = null if (!powerManagementService.isPowerSavingEnabled && !connectivityService.isInternetWalled) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager val wakeLockTag = MainApp.getAuthority() + WAKELOCK_TAG_SEPARATION + TAG wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, wakeLockTag) wakeLock.acquire(WAKELOCK_ACQUISITION_TIMEOUT_MS) } val users = userAccountManager.allUsers for (user in users) { val storageManager = FileDataStorageManager(user.toPlatformAccount(), contentResolver) val ocRoot = storageManager.getFileByPath(OCFile.ROOT_PATH) if (ocRoot.storagePath == null) { break } recursive(File(ocRoot.storagePath), storageManager, user) } wakeLock?.release() } return Result.success() } @Suppress("ReturnCount", "ComplexMethod") // legacy code private fun recursive(folder: File, storageManager: FileDataStorageManager, user: User) { val downloadFolder = FileStorageUtils.getSavePath(user.accountName) val folderName = folder.absolutePath.replaceFirst(downloadFolder.toRegex(), "") + OCFile.PATH_SEPARATOR Log_OC.d(TAG, "$folderName: enter") // exit if (folder.listFiles() == null) { return } val ocFolder = storageManager.getFileByPath(folderName) Log_OC.d(TAG, folderName + ": currentEtag: " + ocFolder.etag) // check for etag change, if false, skip val checkEtagOperation = CheckEtagRemoteOperation(ocFolder.encryptedFileName, ocFolder.etagOnServer) val result = checkEtagOperation.execute(user.toPlatformAccount(), context) when (result.code) { ResultCode.ETAG_UNCHANGED -> { Log_OC.d(TAG, "$folderName: eTag unchanged") return } ResultCode.FILE_NOT_FOUND -> { val removalResult = storageManager.removeFolder(ocFolder, true, true) if (!removalResult) { Log_OC.e(TAG, "removal of " + ocFolder.storagePath + " failed: file not found") } return } ResultCode.ETAG_CHANGED -> Log_OC.d(TAG, "$folderName: eTag changed") else -> Log_OC.d(TAG, "$folderName: eTag changed") } // iterate over downloaded files val files = folder.listFiles { obj: File -> obj.isFile } if (files != null) { for (file in files) { val ocFile = storageManager.getFileByLocalPath(file.path) val synchronizeFileOperation = SynchronizeFileOperation(ocFile.remotePath, user, true, context) synchronizeFileOperation.execute(storageManager, context) } } // recursive into folder val subfolders = folder.listFiles { obj: File -> obj.isDirectory } if (subfolders != null) { for (subfolder in subfolders) { recursive(subfolder, storageManager, user) } } // update eTag @Suppress("TooGenericExceptionCaught") // legacy code try { val updatedEtag = result.data[0] as String ocFolder.etagOnServer = updatedEtag storageManager.saveFile(ocFolder) } catch (e: Exception) { Log_OC.e(TAG, "Failed to update etag on " + folder.absolutePath, e) } } }
gpl-2.0
DUCodeWars/TournamentFramework
src/main/java/org/DUCodeWars/framework/server/net/packets/notifications/NotificationPacketSer.kt
2
1096
package org.DUCodeWars.framework.server.net.packets.notifications import com.google.gson.JsonObject import org.DUCodeWars.framework.server.net.packets.JsonSerialiser import org.DUCodeWars.framework.server.net.packets.PacketSer import org.DUCodeWars.framework.server.net.packets.Request abstract class NotificationPacketSer<I : NotificationRequest>(action: String) : PacketSer<I, NotificationResponse>( action) { final override val resSer = NotificationResSer() } class NotificationResSer : JsonSerialiser<NotificationResponse>() { override fun ser(packet: NotificationResponse): JsonObject { val json = JsonObject() json.addProperty("received", 1) return json } override fun deserialise(json: JsonObject): NotificationResponse { val received = json["received"].asInt return if (received == 1) { val action = json["action"].asString!! NotificationResponse(action) } else { throw InvalidResponseException("Notification Response contained received = $received") } } }
mit
PizzaGames/emulio
core/src/main/com/github/emulio/ui/screens/dialogs/MainMenuDialog.kt
1
6841
package com.github.emulio.ui.screens.dialogs import com.badlogic.gdx.Gdx import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.graphics.g2d.TextureRegion import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator import com.badlogic.gdx.scenes.scene2d.InputEvent import com.badlogic.gdx.scenes.scene2d.Stage import com.badlogic.gdx.scenes.scene2d.ui.Label import com.badlogic.gdx.scenes.scene2d.ui.List import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane import com.badlogic.gdx.scenes.scene2d.utils.ClickListener import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable import com.github.emulio.Emulio import com.github.emulio.model.config.InputConfig import com.github.emulio.ui.screens.* import com.github.emulio.ui.screens.wizard.PlatformWizardScreen import com.github.emulio.utils.translate import mu.KotlinLogging val logger = KotlinLogging.logger { } class MainMenuDialog(emulio: Emulio, private val backCallback: () -> EmulioScreen, screen: EmulioScreen, private val stg: Stage = screen.stage) : EmulioDialog("Main Menu".translate(), emulio, "main-menu") { // we need to cache this font! private val mainFont = FreeTypeFontGenerator(Gdx.files.internal("fonts/RopaSans-Regular.ttf")).generateFont(FreeTypeFontGenerator.FreeTypeFontParameter().apply { size = 40 color = Color.WHITE }) private val listView: List<String> private val listScrollPane: ScrollPane private val menuItems = mapOf( "Scraper".translate() to { closeDialog(true) InfoDialog("Not yet implemented", "Not yet implemented", emulio).show(stg) }, "General Settings".translate() to { closeDialog(true) InfoDialog("Not yet implemented", "Not yet implemented", emulio).show(stg) }, "Input settings".translate() to { closeDialog(true) screen.switchScreen(InputConfigScreen(emulio, backCallback)) }, "Platform Config".translate() to { closeDialog(true) YesNoDialog("Platform Config".translate(), """ The platforms can be edited/configured using a Wizard or editing manually. """.trimIndent().translate(), emulio, "Proceed to Wizard".translate(), "Edit Manually".translate(), cancelCallback = { screen.launchPlatformConfigEditor() screen.showReloadConfirmation() }, confirmCallback = { screen.switchScreen(PlatformWizardScreen(emulio, backCallback)) }).show(stg) }, "Restart Emulio".translate() to { screen.showReloadConfirmation() }, "Quit Emulio".translate() to { showExitConfirmation(emulio, stg) } ) init { val title = titleLabel.text titleLabel.remove() titleTable.reset() titleTable.add(Label(title, emulio.skin, "title").apply { color.a = 0.8f }) listView = List<String>(List.ListStyle().apply { font = mainFont fontColorSelected = Color.WHITE fontColorUnselected = Color(0x878787FF.toInt()) val selectorTexture = createColorTexture(0x878787FF.toInt()) selection = TextureRegionDrawable(TextureRegion(selectorTexture)) }).apply { menuItems.keys.forEach { items.add(it) } width = screenWidth / 2 height = 100f addListener(object : ClickListener() { override fun clicked(event: InputEvent?, x: Float, y: Float) { performClick() } }) selectedIndex = 0 } contentTable.reset() listScrollPane = ScrollPane(listView, ScrollPane.ScrollPaneStyle()).apply { setFlickScroll(true) setScrollBarPositions(false, true) setScrollingDisabled(true, false) setSmoothScrolling(true) isTransform = true setSize(screenWidth / 2, screenHeight / 2) } contentTable.add(listScrollPane).fillX().expandX().maxHeight(screenHeight / 2).minWidth(screenWidth / 2) } private var lastSelected: Int = -1 private fun performClick() { if (lastSelected == listView.selectedIndex) { performSelectItem() } lastSelected = listView.selectedIndex } private fun performSelectItem() { closeDialog() menuItems[listView.selected]!!.invoke() } private fun selectNext(amount: Int = 1) { val nextIndex = listView.selectedIndex + amount if (amount < 0) { if (nextIndex < 0) { listView.selectedIndex = listView.items.size + amount } else { listView.selectedIndex = nextIndex } } if (amount > 0) { if (nextIndex >= listView.items.size) { listView.selectedIndex = 0 } else { listView.selectedIndex = nextIndex } } lastSelected = listView.selectedIndex checkVisible(nextIndex) } private fun checkVisible(index: Int) { val itemHeight = listView.itemHeight val selectionY = index * itemHeight val selectionY2 = selectionY + itemHeight val minItemsVisible = itemHeight * 5 val itemsPerView = listScrollPane.height / itemHeight if (listView.selectedIndex > (menuItems.size - itemsPerView)) { listScrollPane.scrollY = listView.height - listScrollPane.height return } if (listView.selectedIndex == 0) { listScrollPane.scrollY = 0f return } if ((selectionY2 + minItemsVisible) > listScrollPane.height) { listScrollPane.scrollY = (selectionY2 - listScrollPane.height) + minItemsVisible } val minScrollY = Math.max(selectionY - minItemsVisible, 0f) if (minScrollY < listScrollPane.scrollY) { listScrollPane.scrollY = minScrollY } } override fun onDownButton(input: InputConfig) { selectNext(1) } override fun onUpButton(input: InputConfig) { selectNext(-1) } override fun onPageDownButton(input: InputConfig) { selectNext(5) } override fun onPageUpButton(input: InputConfig) { selectNext(-5) } override fun onConfirmButton(input: InputConfig) { performSelectItem() } override fun onCancelButton(input: InputConfig) { closeDialog() } }
gpl-3.0
nlefler/Glucloser
Glucloser/app/src/main/kotlin/com/nlefler/glucloser/a/models/Snack.kt
1
537
package com.nlefler.glucloser.a.models import io.requery.* import java.util.* /** * Created by Nathan Lefler on 5/8/15. */ @Entity interface Snack: Persistable { @get:Key var primaryId: String var eatenDate: Date @get:ManyToOne var bolusPattern: BolusPattern? var carbs: Int var insulin: Float @get:OneToOne(mappedBy = "primaryId") @get:ForeignKey(referencedColumn = "primaryId") var beforeSugar: BloodSugar? var isCorrection: Boolean @get:OneToMany var foods: MutableList<Food> }
gpl-2.0
k0shk0sh/FastHub
app/src/main/java/com/fastaccess/ui/modules/main/notifications/FastHubNotificationDialog.kt
1
2677
package com.fastaccess.ui.modules.main.notifications import android.os.Bundle import androidx.fragment.app.FragmentManager import android.text.Html import android.view.View import butterknife.OnClick import com.fastaccess.R import com.fastaccess.data.dao.model.AbstractFastHubNotification.NotificationType import com.fastaccess.data.dao.model.FastHubNotification import com.fastaccess.helper.BundleConstant import com.fastaccess.helper.Bundler import com.fastaccess.helper.PrefGetter import com.fastaccess.ui.base.BaseDialogFragment import com.fastaccess.ui.base.mvp.BaseMvp import com.fastaccess.ui.base.mvp.presenter.BasePresenter import kotlinx.android.synthetic.main.dialog_guide_layout.* /** * Created by Kosh on 17.11.17. */ class FastHubNotificationDialog : BaseDialogFragment<BaseMvp.FAView, BasePresenter<BaseMvp.FAView>>() { init { suppressAnimation = true isCancelable = false } private val model by lazy { arguments?.getParcelable<FastHubNotification>(BundleConstant.ITEM) } @OnClick(R.id.cancel) fun onCancel() { dismiss() } override fun onFragmentCreated(view: View, savedInstanceState: Bundle?) { model?.let { title?.text = it.title description?.text = Html.fromHtml(it.body) it.isRead = true FastHubNotification.update(it) } ?: dismiss() } override fun providePresenter(): BasePresenter<BaseMvp.FAView> = BasePresenter() override fun fragmentLayout(): Int = R.layout.dialog_guide_layout companion object { @JvmStatic private val TAG = FastHubNotificationDialog::class.java.simpleName fun newInstance(model: FastHubNotification): FastHubNotificationDialog { val fragment = FastHubNotificationDialog() fragment.arguments = Bundler.start() .put(BundleConstant.ITEM, model) .end() return fragment } fun show(fragmentManager: FragmentManager, model: FastHubNotification? = null) { val notification = model ?: FastHubNotification.getLatest() notification?.let { if (it.type == NotificationType.PROMOTION || it.type == NotificationType.PURCHASE && model == null) { if (PrefGetter.isProEnabled()) { it.isRead = true FastHubNotification.update(it) return } } newInstance(it).show(fragmentManager, TAG) } } fun show(fragmentManager: FragmentManager) { show(fragmentManager, null) } } }
gpl-3.0
siempredelao/Distance-From-Me-Android
app/src/main/java/gc/david/dfm/PreferencesProvider.kt
1
792
/* * Copyright (c) 2019 David Aguiar Gonzalez * * 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 gc.david.dfm /** * Created by david on 10.01.17. */ interface PreferencesProvider { fun shouldShowElevationChart(): Boolean // TODO: 10.01.17 add rest of methods }
apache-2.0
cFerg/CloudStorming
ObjectAvoidance/kotlin/src/elite/gils/Base.kt
1
1345
package elite.gils class Base { val bits: Int get() = 0 val value: Int get() = 0 fun getBaseValue(c: Char): Short { when (c) { 0 -> return 0 1 -> return 1 2 -> return 2 3 -> return 3 4 -> return 4 5 -> return 5 6 -> return 6 7 -> return 7 8 -> return 8 9 -> return 9 'a', 'A' -> return 10 'b', 'B' -> return 11 'c', 'C' -> return 12 'd', 'D' -> return 13 'e', 'E' -> return 14 'f', 'F' -> return 15 'g', 'G' -> return 16 'h', 'H' -> return 17 'i', 'I' -> return 18 'j', 'J' -> return 19 'k', 'K' -> return 20 'l', 'L' -> return 21 'm', 'M' -> return 22 'n', 'N' -> return 23 'o', 'O' -> return 24 'p', 'P' -> return 25 'q', 'Q' -> return 26 'r', 'R' -> return 27 's', 'S' -> return 28 't', 'T' -> return 29 'u', 'U' -> return 30 'v', 'V' -> return 31 'w', 'W' -> return 32 'x', 'X' -> return 33 'y', 'Y' -> return 34 'z', 'Z' -> return 35 } return 0 } }
bsd-3-clause
anthologist/Simple-Gallery
app/src/main/kotlin/com/simplemobiletools/gallery/activities/EditActivity.kt
1
9446
package com.simplemobiletools.gallery.activities import android.app.Activity import android.content.Intent import android.graphics.Bitmap import android.graphics.Bitmap.CompressFormat import android.graphics.Point import android.net.Uri import android.os.Bundle import android.provider.MediaStore import android.view.Menu import android.view.MenuItem import com.simplemobiletools.commons.extensions.* import com.simplemobiletools.commons.helpers.OTG_PATH import com.simplemobiletools.commons.helpers.PERMISSION_WRITE_STORAGE import com.simplemobiletools.commons.helpers.REAL_FILE_PATH import com.simplemobiletools.commons.models.FileDirItem import com.simplemobiletools.gallery.R import com.simplemobiletools.gallery.dialogs.ResizeDialog import com.simplemobiletools.gallery.dialogs.SaveAsDialog import com.simplemobiletools.gallery.extensions.openEditor import com.theartofdev.edmodo.cropper.CropImageView import kotlinx.android.synthetic.main.view_crop_image.* import java.io.* class EditActivity : SimpleActivity(), CropImageView.OnCropImageCompleteListener { private val ASPECT_X = "aspectX" private val ASPECT_Y = "aspectY" private val CROP = "crop" private lateinit var uri: Uri private lateinit var saveUri: Uri private var resizeWidth = 0 private var resizeHeight = 0 private var isCropIntent = false private var isEditingWithThirdParty = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.view_crop_image) handlePermission(PERMISSION_WRITE_STORAGE) { if (it) { initEditActivity() } else { toast(R.string.no_storage_permissions) finish() } } } private fun initEditActivity() { if (intent.data == null) { toast(R.string.invalid_image_path) finish() return } uri = intent.data if (uri.scheme != "file" && uri.scheme != "content") { toast(R.string.unknown_file_location) finish() return } if (intent.extras?.containsKey(REAL_FILE_PATH) == true) { val realPath = intent.extras.getString(REAL_FILE_PATH) uri = when { realPath.startsWith(OTG_PATH) -> Uri.parse(realPath) realPath.startsWith("file:/") -> Uri.parse(realPath) else -> Uri.fromFile(File(realPath)) } } else { (getRealPathFromURI(uri))?.apply { uri = Uri.fromFile(File(this)) } } saveUri = when { intent.extras?.containsKey(MediaStore.EXTRA_OUTPUT) == true -> intent.extras!!.get(MediaStore.EXTRA_OUTPUT) as Uri else -> uri } isCropIntent = intent.extras?.get(CROP) == "true" crop_image_view.apply { setOnCropImageCompleteListener(this@EditActivity) setImageUriAsync(uri) if (isCropIntent && shouldCropSquare()) setFixedAspectRatio(true) } } override fun onResume() { super.onResume() isEditingWithThirdParty = false } override fun onStop() { super.onStop() if (isEditingWithThirdParty) { finish() } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu_editor, menu) menu.findItem(R.id.resize).isVisible = !isCropIntent return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.save_as -> crop_image_view.getCroppedImageAsync() R.id.rotate -> crop_image_view.rotateImage(90) R.id.resize -> resizeImage() R.id.flip_horizontally -> flipImage(true) R.id.flip_vertically -> flipImage(false) R.id.edit -> editWith() else -> return super.onOptionsItemSelected(item) } return true } private fun resizeImage() { val point = getAreaSize() if (point == null) { toast(R.string.unknown_error_occurred) return } ResizeDialog(this, point) { resizeWidth = it.x resizeHeight = it.y crop_image_view.getCroppedImageAsync() } } private fun shouldCropSquare(): Boolean { val extras = intent.extras return if (extras != null && extras.containsKey(ASPECT_X) && extras.containsKey(ASPECT_Y)) { extras.getInt(ASPECT_X) == extras.getInt(ASPECT_Y) } else { false } } private fun getAreaSize(): Point? { val rect = crop_image_view.cropRect ?: return null val rotation = crop_image_view.rotatedDegrees return if (rotation == 0 || rotation == 180) { Point(rect.width(), rect.height()) } else { Point(rect.height(), rect.width()) } } override fun onCropImageComplete(view: CropImageView, result: CropImageView.CropResult) { if (result.error == null) { if (isCropIntent) { if (saveUri.scheme == "file") { saveBitmapToFile(result.bitmap, saveUri.path) } else { var inputStream: InputStream? = null var outputStream: OutputStream? = null try { val stream = ByteArrayOutputStream() result.bitmap.compress(CompressFormat.JPEG, 100, stream) inputStream = ByteArrayInputStream(stream.toByteArray()) outputStream = contentResolver.openOutputStream(saveUri) inputStream.copyTo(outputStream) } finally { inputStream?.close() outputStream?.close() } Intent().apply { addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) setResult(RESULT_OK, this) } finish() } } else if (saveUri.scheme == "file") { SaveAsDialog(this, saveUri.path, true) { saveBitmapToFile(result.bitmap, it) } } else if (saveUri.scheme == "content") { var newPath = applicationContext.getRealPathFromURI(saveUri) ?: "" var shouldAppendFilename = true if (newPath.isEmpty()) { val filename = applicationContext.getFilenameFromContentUri(saveUri) ?: "" if (filename.isNotEmpty()) { val path = if (intent.extras?.containsKey(REAL_FILE_PATH) == true) intent.getStringExtra(REAL_FILE_PATH).getParentPath() else internalStoragePath newPath = "$path/$filename" shouldAppendFilename = false } } if (newPath.isEmpty()) { newPath = "$internalStoragePath/${getCurrentFormattedDateTime()}.${saveUri.toString().getFilenameExtension()}" shouldAppendFilename = false } SaveAsDialog(this, newPath, shouldAppendFilename) { saveBitmapToFile(result.bitmap, it) } } else { toast(R.string.unknown_file_location) } } else { toast("${getString(R.string.image_editing_failed)}: ${result.error.message}") } } private fun saveBitmapToFile(bitmap: Bitmap, path: String) { try { Thread { val file = File(path) val fileDirItem = FileDirItem(path, path.getFilenameFromPath()) getFileOutputStream(fileDirItem, true) { if (it != null) { saveBitmap(file, bitmap, it) } else { toast(R.string.image_editing_failed) } } }.start() } catch (e: Exception) { showErrorToast(e) } catch (e: OutOfMemoryError) { toast(R.string.out_of_memory_error) } } private fun saveBitmap(file: File, bitmap: Bitmap, out: OutputStream) { toast(R.string.saving) if (resizeWidth > 0 && resizeHeight > 0) { val resized = Bitmap.createScaledBitmap(bitmap, resizeWidth, resizeHeight, false) resized.compress(file.absolutePath.getCompressionFormat(), 90, out) } else { bitmap.compress(file.absolutePath.getCompressionFormat(), 90, out) } setResult(Activity.RESULT_OK, intent) scanFinalPath(file.absolutePath) out.close() } private fun flipImage(horizontally: Boolean) { if (horizontally) { crop_image_view.flipImageHorizontally() } else { crop_image_view.flipImageVertically() } } private fun editWith() { openEditor(uri.toString()) isEditingWithThirdParty = true } private fun scanFinalPath(path: String) { scanPath(path) { setResult(Activity.RESULT_OK, intent) toast(R.string.file_saved) finish() } } }
apache-2.0
iZettle/wrench
wrench-app/src/main/java/com/izettle/wrench/dialogs/enumvalue/FragmentEnumValueViewModel.kt
1
2058
package com.izettle.wrench.dialogs.enumvalue import androidx.lifecycle.LiveData import androidx.lifecycle.ViewModel import com.izettle.wrench.database.* import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import java.util.* class FragmentEnumValueViewModel constructor( private val configurationDao: WrenchConfigurationDao, private val configurationValueDao: WrenchConfigurationValueDao, private val predefinedConfigurationValueDao: WrenchPredefinedConfigurationValueDao) : ViewModel() { internal val configuration: LiveData<WrenchConfiguration> by lazy { configurationDao.getConfiguration(configurationId) } internal val selectedConfigurationValueLiveData: LiveData<WrenchConfigurationValue> by lazy { configurationValueDao.getConfigurationValue(configurationId, scopeId) } internal val predefinedValues: LiveData<List<WrenchPredefinedConfigurationValue>> by lazy { predefinedConfigurationValueDao.getByConfigurationId(configurationId) } private var configurationId: Long = 0 private var scopeId: Long = 0 internal var selectedConfigurationValue: WrenchConfigurationValue? = null internal fun init(configurationId: Long, scopeId: Long) { this.configurationId = configurationId this.scopeId = scopeId } fun updateConfigurationValue(value: String) { GlobalScope.launch { if (selectedConfigurationValue != null) { configurationValueDao.updateConfigurationValue(configurationId, scopeId, value) } else { val wrenchConfigurationValue = WrenchConfigurationValue(0, configurationId, value, scopeId) wrenchConfigurationValue.id = configurationValueDao.insert(wrenchConfigurationValue) } configurationDao.touch(configurationId, Date()) } } internal fun deleteConfigurationValue() { GlobalScope.launch { configurationValueDao.delete(selectedConfigurationValue!!) } } }
mit
toastkidjp/Jitte
app/src/test/java/jp/toastkid/yobidashi/search/clip/SearchWithClipTest.kt
2
2022
/* * Copyright (c) 2021 toastkidjp. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompany this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html. */ package jp.toastkid.yobidashi.search.clip import android.content.ClipboardManager import android.view.View import io.mockk.MockKAnnotations import io.mockk.every import io.mockk.impl.annotations.InjectMockKs import io.mockk.impl.annotations.MockK import io.mockk.unmockkAll import io.mockk.verify import jp.toastkid.lib.BrowserViewModel import jp.toastkid.lib.preference.ColorPair import jp.toastkid.lib.preference.PreferenceApplier import org.junit.After import org.junit.Before import org.junit.Test class SearchWithClipTest { @InjectMockKs private lateinit var searchWithClip: SearchWithClip @MockK private lateinit var clipboardManager: ClipboardManager @MockK private lateinit var parent: View @MockK private lateinit var colorPair: ColorPair @MockK private lateinit var browserViewModel: BrowserViewModel @MockK private lateinit var preferenceApplier: PreferenceApplier @Before fun setUp() { MockKAnnotations.init(this) every { clipboardManager.addPrimaryClipChangedListener(any()) }.returns(Unit) every { clipboardManager.removePrimaryClipChangedListener(any()) }.returns(Unit) every { preferenceApplier.lastClippedWord() }.returns("last") every { preferenceApplier.setLastClippedWord(any()) }.returns(Unit) } @After fun tearDown() { unmockkAll() } @Test fun testInvoke() { searchWithClip.invoke() verify(exactly = 1) { clipboardManager.addPrimaryClipChangedListener(any()) } } @Test fun testDispose() { searchWithClip.dispose() verify(exactly = 1) { clipboardManager.removePrimaryClipChangedListener(any()) } } }
epl-1.0
anton-okolelov/intellij-rust
src/main/kotlin/org/rust/lang/core/resolve/ref/RsMacroReferenceImpl.kt
2
946
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.resolve.ref import com.intellij.psi.PsiElement import org.rust.lang.core.psi.RsMacroReference import org.rust.lang.core.psi.ext.RsElement import org.rust.lang.core.resolve.collectCompletionVariants import org.rust.lang.core.resolve.collectResolveVariants import org.rust.lang.core.resolve.processMacroReferenceVariants class RsMacroReferenceImpl(pattern: RsMacroReference) : RsReferenceCached<RsMacroReference>(pattern) { override val RsMacroReference.referenceAnchor: PsiElement get() = referenceNameElement override fun getVariants(): Array<out Any> = collectCompletionVariants { processMacroReferenceVariants(element, it) } override fun resolveInner(): List<RsElement> = collectResolveVariants(element.referenceName) { processMacroReferenceVariants(element, it) } }
mit
diyaakanakry/Diyaa
Priorites.kt
1
224
/* Operations rules| Priorites rules 1- () 2- ^ 3- *, / 4- +, - 5- = */ fun main(args:Array<String>){ var n1:Int=10 var n2:Int=10 var n3:Int=5 var sum:Int? sum=(n1+n2)*n3-3; print("sum:$sum" ) }
unlicense
ModerateFish/component
framework/src/main/java/com/thornbirds/frameworkext/component/page/BasePage.kt
1
924
package com.thornbirds.frameworkext.component.page import android.view.View import android.view.ViewGroup import com.thornbirds.component.ControllerView /** * @author YangLi [email protected] */ abstract class BasePage<VIEW : View, CONTROLLER : BasePageController>( parentView: ViewGroup, controller: CONTROLLER ) : ControllerView<VIEW, CONTROLLER>(parentView, controller) { override fun startView() { super.startView() val contentView = ensureContentView if (contentView.parent == null) { mParentView.addView(contentView) } contentView.visibility = View.VISIBLE } override fun stopView() { super.stopView() ensureContentView.visibility = View.GONE } override fun release() { super.release() mParentView.removeView(ensureContentView) } fun onBackPressed(): Boolean { return false } }
apache-2.0