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
JetBrains/kotlin-native
shared/src/main/kotlin/org/jetbrains/kotlin/konan/target/Configurables.kt
1
5226
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed -> in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.konan.target import org.jetbrains.kotlin.konan.properties.* interface RelocationModeFlags : TargetableExternalStorage { val dynamicLibraryRelocationMode get() = targetString("dynamicLibraryRelocationMode").mode() val staticLibraryRelocationMode get() = targetString("staticLibraryRelocationMode").mode() val executableRelocationMode get() = targetString("executableRelocationMode").mode() private fun String?.mode(): Mode = when (this?.toLowerCase()) { null -> Mode.DEFAULT "pic" -> Mode.PIC "static" -> Mode.STATIC else -> error("Unknown relocation mode: $this") } enum class Mode { PIC, STATIC, DEFAULT } } interface ClangFlags : TargetableExternalStorage, RelocationModeFlags { val clangFlags get() = targetList("clangFlags") val clangNooptFlags get() = targetList("clangNooptFlags") val clangOptFlags get() = targetList("clangOptFlags") val clangDebugFlags get() = targetList("clangDebugFlags") } interface LldFlags : TargetableExternalStorage { val lldFlags get() = targetList("lld") } interface Configurables : TargetableExternalStorage, RelocationModeFlags { val target: KonanTarget val llvmHome get() = hostString("llvmHome") val llvmVersion get() = hostString("llvmVersion") val libffiDir get() = hostString("libffiDir") val cacheableTargets get() = hostList("cacheableTargets") val additionalCacheFlags get() = targetList("additionalCacheFlags") // TODO: Delegate to a map? val linkerOptimizationFlags get() = targetList("linkerOptimizationFlags") val linkerKonanFlags get() = targetList("linkerKonanFlags") val mimallocLinkerDependencies get() = targetList("mimallocLinkerDependencies") val linkerNoDebugFlags get() = targetList("linkerNoDebugFlags") val linkerDynamicFlags get() = targetList("linkerDynamicFlags") val targetSysRoot get() = targetString("targetSysRoot") // Notice: these ones are host-target. val targetToolchain get() = hostTargetString("targetToolchain") val absoluteTargetSysRoot get() = absolute(targetSysRoot) val absoluteTargetToolchain get() = absolute(targetToolchain) val absoluteLlvmHome get() = absolute(llvmHome) val targetCpu get() = targetString("targetCpu") val targetCpuFeatures get() = targetString("targetCpuFeatures") val llvmInlineThreshold get() = targetString("llvmInlineThreshold") val runtimeDefinitions get() = targetList("runtimeDefinitions") } interface ConfigurablesWithEmulator : Configurables { val emulatorDependency get() = hostTargetString("emulatorDependency") // TODO: We need to find a way to represent absolute path in properties. // In case of QEMU, absolute path to dynamic linker should be specified. val emulatorExecutable get() = hostTargetString("emulatorExecutable") val absoluteEmulatorExecutable get() = absolute(emulatorExecutable) } interface TargetableConfigurables : Configurables { val targetArg get() = targetString("quadruple") } interface AppleConfigurables : Configurables, ClangFlags { val arch get() = targetString("arch")!! val osVersionMin get() = targetString("osVersionMin")!! val osVersionMinFlagLd get() = targetString("osVersionMinFlagLd")!! val stripFlags get() = targetList("stripFlags") val additionalToolsDir get() = hostString("additionalToolsDir") val absoluteAdditionalToolsDir get() = absolute(additionalToolsDir) } interface MingwConfigurables : TargetableConfigurables, ClangFlags interface GccConfigurables : TargetableConfigurables, ClangFlags { val gccToolchain get() = targetString("gccToolchain") val absoluteGccToolchain get() = absolute(gccToolchain) val libGcc get() = targetString("libGcc")!! val dynamicLinker get() = targetString("dynamicLinker")!! val abiSpecificLibraries get() = targetList("abiSpecificLibraries") val crtFilesLocation get() = targetString("crtFilesLocation")!! val linker get() = hostTargetString("linker") val linkerHostSpecificFlags get() = hostTargetList("linkerHostSpecificFlags") val absoluteLinker get() = absolute(linker) val linkerGccFlags get() = targetList("linkerGccFlags") } interface AndroidConfigurables : TargetableConfigurables, ClangFlags interface WasmConfigurables : TargetableConfigurables, ClangFlags, LldFlags interface ZephyrConfigurables : TargetableConfigurables, ClangFlags { val boardSpecificClangFlags get() = targetList("boardSpecificClangFlags") val targetAbi get() = targetString("targetAbi") }
apache-2.0
jwren/intellij-community
plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/tree/workspace/MavenProjectTreeImporterToWorkspaceModel.kt
1
8981
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.idea.maven.importing.tree.workspace import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider import com.intellij.openapi.externalSystem.service.project.ProjectDataManager import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ExternalProjectSystemRegistry import com.intellij.openapi.roots.ex.ProjectRootManagerEx import com.intellij.workspaceModel.ide.JpsImportedEntitySource import com.intellij.workspaceModel.ide.WorkspaceModel import com.intellij.workspaceModel.ide.getInstance import com.intellij.workspaceModel.ide.impl.legacyBridge.module.ModuleManagerBridgeImpl.Companion.findModuleByEntity import com.intellij.workspaceModel.storage.WorkspaceEntityStorageBuilder import com.intellij.workspaceModel.storage.bridgeEntities.ModuleId import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager import org.jetbrains.idea.maven.importing.* import org.jetbrains.idea.maven.importing.configurers.MavenModuleConfigurer import org.jetbrains.idea.maven.importing.tree.MavenModuleType import org.jetbrains.idea.maven.importing.tree.MavenProjectTreeImporter import org.jetbrains.idea.maven.importing.tree.ModuleData import org.jetbrains.idea.maven.project.* import org.jetbrains.idea.maven.utils.MavenProgressIndicator import org.jetbrains.idea.maven.utils.MavenUtil import java.util.* class MavenProjectTreeImporterToWorkspaceModel( private val mavenProjectsTree: MavenProjectsTree, private val projectsToImportWithChanges: Map<MavenProject, MavenProjectChanges>, private val mavenImportingSettings: MavenImportingSettings, ideModelsProvider: IdeModifiableModelsProvider, private val project: Project ) : MavenProjectImporterBase(mavenProjectsTree, mavenImportingSettings, projectsToImportWithChanges) { private val modelsProvider = MavenProjectTreeImporter.getModelProvider(ideModelsProvider, project) private val createdModulesList = ArrayList<Module>() private val virtualFileUrlManager = VirtualFileUrlManager.getInstance(project) private val contextProvider = MavenProjectImportContextProvider(project, mavenProjectsTree, projectsToImportWithChanges, mavenImportingSettings) override fun importProject(): List<MavenProjectsProcessorTask> { val activity = MavenImportStats.startApplyingModelsActivity(project) val startTime = System.currentTimeMillis() try { val postTasks = ArrayList<MavenProjectsProcessorTask>() val context = contextProvider.context if (context.hasChanges) { importModules(context, postTasks) scheduleRefreshResolvedArtifacts(postTasks) } return postTasks } finally { activity.finished() LOG.info("[maven import] applying models to workspace model took ${System.currentTimeMillis() - startTime}ms") } } private fun importModules(context: MavenModuleImportContext, postTasks: ArrayList<MavenProjectsProcessorTask>) { val builder = WorkspaceEntityStorageBuilder.create() val createdModuleIds = ArrayList<Pair<MavenModuleImportData, ModuleId>>() val mavenFolderHolderByMavenId = TreeMap<String, MavenImportFolderHolder>() for (importData in context.allModules) { val moduleEntity = WorkspaceModuleImporter( importData, virtualFileUrlManager, builder, mavenImportingSettings, mavenFolderHolderByMavenId, project ).importModule() createdModuleIds.add(importData to moduleEntity.persistentId()) } val moduleImportDataList = mutableListOf<ModuleImportData>() MavenUtil.invokeAndWaitWriteAction(project) { WorkspaceModel.getInstance(project).updateProjectModel { current -> current.replaceBySource( { (it as? JpsImportedEntitySource)?.externalSystemId == ExternalProjectSystemRegistry.MAVEN_EXTERNAL_SOURCE_ID }, builder) } val storage = WorkspaceModel.getInstance(project).entityStorage.current for ((importData, moduleId) in createdModuleIds) { val entity = storage.resolve(moduleId) if (entity == null) continue val module = storage.findModuleByEntity(entity) if (module != null) { createdModulesList.add(module) moduleImportDataList.add(ModuleImportData(module, importData)) } } } facetImport(moduleImportDataList, context, postTasks) MavenUtil.invokeAndWaitWriteAction(project) { modelsProvider.dispose() } configureMavenProjects(moduleImportDataList, project) } private fun facetImport(moduleImportDataList: MutableList<ModuleImportData>, context: MavenModuleImportContext, postTasks: List<MavenProjectsProcessorTask>) { val modifiableModelsProvider = ProjectDataManager.getInstance().createModifiableModelsProvider(project) try { for (importData in moduleImportDataList) { configFacet(importData, context, modifiableModelsProvider, postTasks) } } finally { MavenUtil.invokeAndWaitWriteAction(project) { ProjectRootManagerEx.getInstanceEx(project).mergeRootsChangesDuring { modifiableModelsProvider.commit() } } } } private fun configFacet(importData: ModuleImportData, context: MavenModuleImportContext, modifiableModelsProvider: IdeModifiableModelsProvider, postTasks: List<MavenProjectsProcessorTask>) { if (importData.mavenModuleImportData.moduleData.type == MavenModuleType.AGGREGATOR_MAIN_TEST) return val mavenProject = importData.mavenModuleImportData.mavenProject val mavenProjectChanges = projectsToImportWithChanges.get(mavenProject) if (mavenProjectChanges == null || !mavenProjectChanges.hasChanges()) return if (mavenProject.suitableImporters.isEmpty()) return val mavenModuleImporter = MavenModuleImporter( importData.module, mavenProjectsTree, mavenProject, mavenProjectChanges, context.moduleNameByProject, mavenImportingSettings, modelsProvider, importData.mavenModuleImportData.moduleData.type ) val rootModelAdapter = MavenRootModelAdapter(MavenRootModelAdapterLegacyImpl(mavenProject, importData.module, modelsProvider)) val mapToOldImportModel = mapToOldImportModel(importData) MavenProjectTreeImporter.configModule(mapToOldImportModel, mavenModuleImporter, rootModelAdapter) mavenModuleImporter.setModifiableModelsProvider(modifiableModelsProvider); mavenModuleImporter.preConfigFacets() mavenModuleImporter.configFacets(postTasks) mavenModuleImporter.postConfigFacets() } private fun mapToOldImportModel(importData: ModuleImportData): org.jetbrains.idea.maven.importing.tree.MavenModuleImportData { val mavenModuleImportData = importData.mavenModuleImportData return org.jetbrains.idea.maven.importing.tree.MavenModuleImportData( mavenModuleImportData.mavenProject, ModuleData(importData.module, mavenModuleImportData.moduleData.type, mavenModuleImportData.moduleData.javaVersionHolder, true), mavenModuleImportData.dependencies, mavenModuleImportData.changes ) } private fun configureMavenProjects(moduleImportDataList: List<ModuleImportData>, project: Project) { if (MavenUtil.isLinearImportEnabled()) return val configurers = MavenModuleConfigurer.getConfigurers() MavenUtil.runInBackground(project, MavenProjectBundle.message("command.name.configuring.projects"), false ) { indicator: MavenProgressIndicator -> var count = 0f val startTime = System.currentTimeMillis() val activity = MavenImportStats.startConfiguringProjectsActivity(project) try { val size = moduleImportDataList.size LOG.info("[maven import] applying " + configurers.size + " configurers to " + size + " Maven projects") for (moduleIMportData in moduleImportDataList) { indicator.setFraction((count++ / size).toDouble()) indicator.setText2(MavenProjectBundle.message("progress.details.configuring.module", moduleIMportData.module.name)) for (configurer in configurers) { configurer.configure(moduleIMportData.mavenModuleImportData.mavenProject, project, moduleIMportData.module) } } } finally { activity.finished() LOG.info("[maven import] configuring projects took " + (System.currentTimeMillis() - startTime) + "ms") } } } override val createdModules: List<Module> get() = createdModulesList companion object { private val LOG = logger<MavenProjectTreeImporterToWorkspaceModel>() } } class ModuleImportData( val module: Module, val mavenModuleImportData: MavenModuleImportData )
apache-2.0
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveExplicitTypeArgumentsIntention.kt
1
8582
// 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.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemHighlightType import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.descriptors.ValueDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyzeInContext import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.core.copied import org.jetbrains.kotlin.idea.inspections.IntentionBasedInspection import org.jetbrains.kotlin.idea.project.builtIns import org.jetbrains.kotlin.idea.util.getResolutionScope import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.findDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelector import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DelegatingBindingTrace import org.jetbrains.kotlin.resolve.bindingContextUtil.getDataFlowInfoBefore import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsStatement import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.TypeUtils import org.jetbrains.kotlin.types.checker.KotlinTypeChecker @Suppress("DEPRECATION") class RemoveExplicitTypeArgumentsInspection : IntentionBasedInspection<KtTypeArgumentList>(RemoveExplicitTypeArgumentsIntention::class) { override fun problemHighlightType(element: KtTypeArgumentList): ProblemHighlightType = ProblemHighlightType.LIKE_UNUSED_SYMBOL override fun additionalFixes(element: KtTypeArgumentList): List<LocalQuickFix>? { val declaration = element.getStrictParentOfType<KtCallableDeclaration>() ?: return null if (!RemoveExplicitTypeIntention.isApplicableTo(declaration)) return null return listOf(RemoveExplicitTypeFix(declaration.nameAsSafeName.asString())) } private class RemoveExplicitTypeFix(private val declarationName: String) : LocalQuickFix { override fun getName() = KotlinBundle.message("remove.explicit.type.specification.from.0", declarationName) override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val element = descriptor.psiElement as? KtTypeArgumentList ?: return val declaration = element.getStrictParentOfType<KtCallableDeclaration>() ?: return RemoveExplicitTypeIntention.removeExplicitType(declaration) } } } class RemoveExplicitTypeArgumentsIntention : SelfTargetingOffsetIndependentIntention<KtTypeArgumentList>( KtTypeArgumentList::class.java, KotlinBundle.lazyMessage("remove.explicit.type.arguments") ) { companion object { fun isApplicableTo(element: KtTypeArgumentList, approximateFlexible: Boolean): Boolean { val callExpression = element.parent as? KtCallExpression ?: return false val typeArguments = callExpression.typeArguments if (typeArguments.isEmpty() || typeArguments.any { it.typeReference?.annotationEntries?.isNotEmpty() == true }) return false val resolutionFacade = callExpression.getResolutionFacade() val bindingContext = resolutionFacade.analyze(callExpression, BodyResolveMode.PARTIAL_WITH_CFA) val originalCall = callExpression.getResolvedCall(bindingContext) ?: return false val (contextExpression, expectedType) = findContextToAnalyze(callExpression, bindingContext) val resolutionScope = contextExpression.getResolutionScope(bindingContext, resolutionFacade) val key = Key<Unit>("RemoveExplicitTypeArgumentsIntention") callExpression.putCopyableUserData(key, Unit) val expressionToAnalyze = contextExpression.copied() callExpression.putCopyableUserData(key, null) val newCallExpression = expressionToAnalyze.findDescendantOfType<KtCallExpression> { it.getCopyableUserData(key) != null }!! newCallExpression.typeArgumentList!!.delete() val newBindingContext = expressionToAnalyze.analyzeInContext( resolutionScope, contextExpression, trace = DelegatingBindingTrace(bindingContext, "Temporary trace"), dataFlowInfo = bindingContext.getDataFlowInfoBefore(contextExpression), expectedType = expectedType ?: TypeUtils.NO_EXPECTED_TYPE, isStatement = contextExpression.isUsedAsStatement(bindingContext) ) val newCall = newCallExpression.getResolvedCall(newBindingContext) ?: return false val args = originalCall.typeArguments val newArgs = newCall.typeArguments fun equalTypes(type1: KotlinType, type2: KotlinType): Boolean { return if (approximateFlexible) { KotlinTypeChecker.DEFAULT.equalTypes(type1, type2) } else { type1 == type2 } } return args.size == newArgs.size && args.values.zip(newArgs.values).all { (argType, newArgType) -> equalTypes(argType, newArgType) } } private fun findContextToAnalyze(expression: KtExpression, bindingContext: BindingContext): Pair<KtExpression, KotlinType?> { for (element in expression.parentsWithSelf) { if (element !is KtExpression) continue if (element.getQualifiedExpressionForSelector() != null) continue if (element is KtFunctionLiteral) continue if (!element.isUsedAsExpression(bindingContext)) return element to null when (val parent = element.parent) { is KtNamedFunction -> { val expectedType = if (element == parent.bodyExpression && !parent.hasBlockBody() && parent.hasDeclaredReturnType()) (bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, parent] as? FunctionDescriptor)?.returnType else null return element to expectedType } is KtVariableDeclaration -> { val expectedType = if (element == parent.initializer && parent.typeReference != null) (bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, parent] as? ValueDescriptor)?.type else null return element to expectedType } is KtParameter -> { val expectedType = if (element == parent.defaultValue) (bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, parent] as? ValueDescriptor)?.type else null return element to expectedType } is KtPropertyAccessor -> { val property = parent.parent as KtProperty val expectedType = when { element != parent.bodyExpression || parent.hasBlockBody() -> null parent.isSetter -> parent.builtIns.unitType property.typeReference == null -> null else -> (bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, parent] as? FunctionDescriptor)?.returnType } return element to expectedType } } } return expression to null } } override fun isApplicableTo(element: KtTypeArgumentList): Boolean = isApplicableTo(element, approximateFlexible = false) override fun applyTo(element: KtTypeArgumentList, editor: Editor?) = element.delete() }
apache-2.0
Homes-MinecraftServerMod/Homes
src/main/kotlin/com/masahirosaito/spigot/homes/datas/ConfigData.kt
1
1470
package com.masahirosaito.spigot.homes.datas import com.google.gson.annotations.SerializedName import com.masahirosaito.spigot.homes.Configs data class ConfigData( @SerializedName("Language folder name") var language: String = "en", @SerializedName("Allow showing debug messages") var onDebug: Boolean = false, @SerializedName("Allow using named home") var onNamedHome: Boolean = true, @SerializedName("Allow using player home") var onFriendHome: Boolean = true, @SerializedName("Allow respawning default home") var onDefaultHomeRespawn: Boolean = true, @SerializedName("Allow checking update") var onUpdateCheck: Boolean = true, @SerializedName("Allow setting home private") var onPrivate: Boolean = true, @SerializedName("Allow invitation") var onInvite: Boolean = true, @SerializedName("The limit number of named home") var homeLimit: Int = -1, @SerializedName("Allow home display") var onHomeDisplay: Boolean = true, @SerializedName("Teleport delay seconds") var teleportDelay: Int = 3, @SerializedName("Cancel teleport when moved") var onMoveCancel: Boolean = true, @SerializedName("Cancel teleport when damaged") var onDamageCancel: Boolean = true ) { init { require(homeLimit >= -1) require(teleportDelay >= 0) } }
apache-2.0
mstream/BoardGameEngine
src/main/kotlin/io.mstream.boardgameengine/Position.kt
1
846
package io.mstream.boardgameengine data class Position private constructor(val x: Int, val y: Int) { companion object { var positions = arrayOfNulls<Position>(100) fun fromCords(x: Int, y: Int): Position { if (x < 0 || y < 0) { throw IllegalArgumentException("cords can't be negative") } if (x > 9 || y > 9) { throw IllegalArgumentException("cords can't be bigger than 9") } val index = x * 10 + y val position = positions[index] when (position) { null -> { val newPosition = Position(x, y) positions[index] = newPosition return newPosition } else -> return position } } } }
mit
GunoH/intellij-community
plugins/kotlin/base/project-structure/src/org/jetbrains/kotlin/idea/base/projectStructure/KotlinResolveScopeEnlarger.kt
7
1701
// 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.base.projectStructure import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.module.Module import com.intellij.psi.PsiFile import com.intellij.psi.ResolveScopeEnlarger import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.SearchScope interface KotlinResolveScopeEnlarger { companion object { val EP_NAME: ExtensionPointName<KotlinResolveScopeEnlarger> = ExtensionPointName.create("org.jetbrains.kotlin.resolveScopeEnlarger") fun enlargeScope(scope: GlobalSearchScope, file: PsiFile): GlobalSearchScope { val virtualFile = file.originalFile.virtualFile ?: return scope var result = scope for (extension in ResolveScopeEnlarger.EP_NAME.extensions) { val project = scope.project ?: continue val additionalScope = extension.getAdditionalResolveScope(virtualFile, project) ?: continue result = result.union(additionalScope) } return result } fun enlargeScope(scope: GlobalSearchScope, module: Module, isTestScope: Boolean): GlobalSearchScope { var result = scope for (extension in EP_NAME.extensions) { val additionalScope = extension.getAdditionalResolveScope(module, isTestScope) ?: continue result = result.union(additionalScope) } return result } } fun getAdditionalResolveScope(module: Module, isTestScope: Boolean): SearchScope? }
apache-2.0
GunoH/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/merge/MergeConflictsTreeTable.kt
13
1769
// 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 com.intellij.openapi.vcs.merge import com.intellij.openapi.util.text.StringUtil import com.intellij.ui.treeStructure.treetable.ListTreeTableModelOnColumns import com.intellij.ui.treeStructure.treetable.TreeTable import com.intellij.util.ui.ColumnInfo import com.intellij.util.ui.JBUI class MergeConflictsTreeTable(private val tableModel: ListTreeTableModelOnColumns) : TreeTable(tableModel) { init { getTableHeader().reorderingAllowed = false tree.isRootVisible = false if (tableModel.columnCount > 1) setShowColumns(true) } override fun doLayout() { if (getTableHeader().resizingColumn == null) { updateColumnSizes() } super.doLayout() } private fun updateColumnSizes() { for ((index, columnInfo) in tableModel.columns.withIndex()) { val column = columnModel.getColumn(index) columnInfo.maxStringValue?.let { val width = calcColumnWidth(it, columnInfo) column.preferredWidth = width } } var size = width val fileColumn = 0 for (i in 0 until tableModel.columns.size) { if (i == fileColumn) continue size -= columnModel.getColumn(i).preferredWidth } columnModel.getColumn(fileColumn).preferredWidth = Math.max(size, JBUI.scale(200)) } private fun calcColumnWidth(maxStringValue: String, columnInfo: ColumnInfo<Any, Any>): Int { val columnName = StringUtil.shortenTextWithEllipsis(columnInfo.name, 15, 7, true) return Math.max(getFontMetrics(font).stringWidth(maxStringValue), getFontMetrics(tableHeader.font).stringWidth(columnName)) + columnInfo.additionalWidth } }
apache-2.0
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/quickfix/abstract/abstractPropertyInNonAbstractClass2.kt
13
84
// "Make 'i' not abstract" "true" class A() { <caret>abstract var i : Int = 0 }
apache-2.0
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/quickfix/surroundWithArrayOfForNamedArgumentsToVarargs/surroundWithSpreadForConstructorCall.fir.kt
8
109
// "Surround with arrayOf(...)" "true" class Foo<T>(vararg val p: T) fun test() { Foo(p = 123<caret>) }
apache-2.0
siosio/intellij-community
plugins/git4idea/src/git4idea/index/ui/GitStagePanel.kt
1
18179
// 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 git4idea.index.ui import com.intellij.dvcs.ui.RepositoryChangesBrowserNode import com.intellij.icons.AllIcons import com.intellij.ide.DataManager import com.intellij.ide.util.PropertiesComponent import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.ex.ActionUtil import com.intellij.openapi.actionSystem.ex.ActionUtil.performActionDumbAwareWithCallbacks import com.intellij.openapi.components.service import com.intellij.openapi.progress.util.ProgressWindow import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Splitter import com.intellij.openapi.util.Disposer import com.intellij.openapi.vcs.AbstractVcsHelper import com.intellij.openapi.vcs.VcsBundle import com.intellij.openapi.vcs.changes.* import com.intellij.openapi.vcs.changes.ChangesViewManager.createTextStatusFactory import com.intellij.openapi.vcs.changes.ui.* import com.intellij.openapi.vcs.changes.ui.ChangesGroupingSupport.Companion.REPOSITORY_GROUPING import com.intellij.openapi.vcs.checkin.CheckinHandler import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.wm.IdeFocusManager import com.intellij.ui.OnePixelSplitter import com.intellij.ui.PopupHandler import com.intellij.ui.ScrollPaneFactory.createScrollPane import com.intellij.ui.SideBorder import com.intellij.ui.components.panels.Wrapper import com.intellij.ui.switcher.QuickActionProvider import com.intellij.util.EditSourceOnDoubleClickHandler import com.intellij.util.EventDispatcher import com.intellij.util.OpenSourceUtil import com.intellij.util.Processor import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.util.ui.JBUI import com.intellij.util.ui.JBUI.Borders.empty import com.intellij.util.ui.JBUI.Panels.simplePanel import com.intellij.util.ui.ThreeStateCheckBox import com.intellij.util.ui.tree.TreeUtil import com.intellij.vcs.commit.CommitStatusPanel import com.intellij.vcs.commit.CommitWorkflowListener import com.intellij.vcs.commit.EditedCommitNode import com.intellij.vcs.log.runInEdt import com.intellij.vcs.log.runInEdtAsync import com.intellij.vcs.log.ui.frame.ProgressStripe import git4idea.GitVcs import git4idea.conflicts.GitConflictsUtil.canShowMergeWindow import git4idea.conflicts.GitConflictsUtil.showMergeWindow import git4idea.conflicts.GitMergeHandler import git4idea.i18n.GitBundle.message import git4idea.index.GitStageCommitWorkflow import git4idea.index.GitStageCommitWorkflowHandler import git4idea.index.GitStageTracker import git4idea.index.GitStageTrackerListener import git4idea.index.actions.GitAddOperation import git4idea.index.actions.GitResetOperation import git4idea.index.actions.StagingAreaOperation import git4idea.index.actions.performStageOperation import git4idea.merge.GitDefaultMergeDialogCustomizer import git4idea.repo.GitConflict import git4idea.repo.GitRepository import git4idea.repo.GitRepositoryManager import git4idea.status.GitRefreshListener import org.jetbrains.annotations.NonNls import java.awt.BorderLayout import java.beans.PropertyChangeListener import java.util.* import java.util.stream.Collectors import javax.swing.JPanel internal class GitStagePanel(private val tracker: GitStageTracker, isVertical: Boolean, isEditorDiffPreview: Boolean, disposableParent: Disposable, private val activate: () -> Unit) : JPanel(BorderLayout()), DataProvider, Disposable { private val project = tracker.project private val _tree: MyChangesTree val tree: ChangesTree get() = _tree private val treeMessageSplitter: Splitter private val commitPanel: GitStageCommitPanel private val commitWorkflowHandler: GitStageCommitWorkflowHandler private val progressStripe: ProgressStripe private val commitDiffSplitter: OnePixelSplitter private val toolbar: ActionToolbar private val changesStatusPanel: Wrapper private var diffPreviewProcessor: GitStageDiffPreview? = null private var editorTabPreview: EditorTabPreview? = null private val state: GitStageTracker.State get() = tracker.state private var hasPendingUpdates = false internal val commitMessage get() = commitPanel.commitMessage init { _tree = MyChangesTree(project) commitPanel = GitStageCommitPanel(project) commitPanel.commitActionsPanel.isCommitButtonDefault = { !commitPanel.commitProgressUi.isDumbMode && IdeFocusManager.getInstance(project).getFocusedDescendantFor(this) != null } commitPanel.commitActionsPanel.setupShortcuts(this, this) commitPanel.addEditedCommitListener(_tree::editedCommitChanged, this) commitPanel.setIncludedRoots(_tree.getIncludedRoots()) _tree.addIncludedRootsListener(object : IncludedRootsListener { override fun includedRootsChanged() { commitPanel.setIncludedRoots(_tree.getIncludedRoots()) } }, this) commitWorkflowHandler = GitStageCommitWorkflowHandler(GitStageCommitWorkflow(project), commitPanel) Disposer.register(this, commitPanel) val toolbarGroup = DefaultActionGroup() toolbarGroup.add(ActionManager.getInstance().getAction("Git.Stage.Toolbar")) toolbarGroup.addSeparator() toolbarGroup.add(ActionManager.getInstance().getAction(ChangesTree.GROUP_BY_ACTION_GROUP)) toolbarGroup.addSeparator() toolbarGroup.addAll(TreeActionsToolbarPanel.createTreeActions(tree)) toolbar = ActionManager.getInstance().createActionToolbar(GIT_STAGE_PANEL_PLACE, toolbarGroup, true) toolbar.setTargetComponent(tree) PopupHandler.installPopupMenu(tree, "Git.Stage.Tree.Menu", "Git.Stage.Tree.Menu") val statusPanel = CommitStatusPanel(commitPanel).apply { border = empty(0, 1, 0, 6) background = tree.background addToLeft(commitPanel.toolbar.component) } val treePanel = simplePanel(createScrollPane(tree, SideBorder.TOP)).addToBottom(statusPanel) progressStripe = ProgressStripe(treePanel, this, ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS) val treePanelWithToolbar = JPanel(BorderLayout()) treePanelWithToolbar.add(toolbar.component, BorderLayout.NORTH) treePanelWithToolbar.add(progressStripe, BorderLayout.CENTER) treeMessageSplitter = TwoKeySplitter(true, ProportionKey("git.stage.tree.message.splitter", 0.7f, "git.stage.tree.message.splitter.horizontal", 0.5f)) treeMessageSplitter.firstComponent = treePanelWithToolbar treeMessageSplitter.secondComponent = commitPanel changesStatusPanel = Wrapper() changesStatusPanel.minimumSize = JBUI.emptySize() commitDiffSplitter = OnePixelSplitter("git.stage.commit.diff.splitter", 0.5f) commitDiffSplitter.firstComponent = treeMessageSplitter add(commitDiffSplitter, BorderLayout.CENTER) add(changesStatusPanel, BorderLayout.SOUTH) updateLayout(isVertical, isEditorDiffPreview, forceDiffPreview = true) tracker.addListener(MyGitStageTrackerListener(), this) val busConnection = project.messageBus.connect(this) busConnection.subscribe(GitRefreshListener.TOPIC, MyGitChangeProviderListener()) busConnection.subscribe(ChangeListListener.TOPIC, MyChangeListListener()) commitWorkflowHandler.workflow.addListener(MyCommitWorkflowListener(), this) if (isRefreshInProgress()) { tree.setEmptyText(message("stage.loading.status")) progressStripe.startLoadingImmediately() } updateChangesStatusPanel() Disposer.register(disposableParent, this) runInEdtAsync(this) { update() } } private fun isRefreshInProgress(): Boolean { if (GitVcs.getInstance(project).changeProvider!!.isRefreshInProgress) return true return GitRepositoryManager.getInstance(project).repositories.any { it.untrackedFilesHolder.isInUpdateMode || it.ignoredFilesHolder.isInUpdateMode() } } private fun updateChangesStatusPanel() { val manager = ChangeListManagerImpl.getInstanceImpl(project) val factory = manager.updateException?.let { createTextStatusFactory(VcsBundle.message("error.updating.changes", it.message), true) } ?: manager.additionalUpdateInfo changesStatusPanel.setContent(factory?.create()) } @RequiresEdt fun update() { if (commitWorkflowHandler.workflow.isExecuting) { hasPendingUpdates = true return } tree.rebuildTree() commitPanel.setTrackerState(state) commitWorkflowHandler.state = state } override fun getData(dataId: String): Any? { if (QuickActionProvider.KEY.`is`(dataId)) return toolbar if (EditorTabDiffPreviewManager.EDITOR_TAB_DIFF_PREVIEW.`is`(dataId)) return editorTabPreview return null } fun updateLayout(isVertical: Boolean, canUseEditorDiffPreview: Boolean, forceDiffPreview: Boolean = false) { val isEditorDiffPreview = canUseEditorDiffPreview || isVertical val isMessageSplitterVertical = isVertical || !isEditorDiffPreview if (treeMessageSplitter.orientation != isMessageSplitterVertical) { treeMessageSplitter.orientation = isMessageSplitterVertical } setDiffPreviewInEditor(isEditorDiffPreview, forceDiffPreview) } private fun setDiffPreviewInEditor(isInEditor: Boolean, force: Boolean = false) { if (Disposer.isDisposed(this)) return if (!force && (isInEditor == (editorTabPreview != null))) return if (diffPreviewProcessor != null) Disposer.dispose(diffPreviewProcessor!!) diffPreviewProcessor = GitStageDiffPreview(project, _tree, tracker, isInEditor, this) diffPreviewProcessor!!.getToolbarWrapper().setVerticalSizeReferent(toolbar.component) if (isInEditor) { editorTabPreview = GitStageEditorDiffPreview(diffPreviewProcessor!!, tree, this, activate) commitDiffSplitter.secondComponent = null } else { editorTabPreview = null commitDiffSplitter.secondComponent = diffPreviewProcessor!!.component } } override fun dispose() { } private inner class MyChangesTree(project: Project) : GitStageTree(project, project.service<GitStageUiSettingsImpl>(), this@GitStagePanel) { override val state get() = [email protected] override val ignoredFilePaths get() = [email protected] override val operations: List<StagingAreaOperation> = listOf(GitAddOperation, GitResetOperation) private val includedRootsListeners = EventDispatcher.create(IncludedRootsListener::class.java) init { isShowCheckboxes = true setInclusionModel(GitStageRootInclusionModel(project, tracker, this@GitStagePanel)) groupingSupport.addPropertyChangeListener(PropertyChangeListener { includedRootsListeners.multicaster.includedRootsChanged() }) inclusionModel.addInclusionListener(object : InclusionListener { override fun inclusionChanged() { includedRootsListeners.multicaster.includedRootsChanged() } }) tracker.addListener(object : GitStageTrackerListener { override fun update() { includedRootsListeners.multicaster.includedRootsChanged() } }, this@GitStagePanel) doubleClickHandler = Processor { e -> if (EditSourceOnDoubleClickHandler.isToggleEvent(this, e)) return@Processor false val dataContext = DataManager.getInstance().getDataContext(this) val mergeAction = ActionManager.getInstance().getAction("Git.Stage.Merge") val event = AnActionEvent.createFromAnAction(mergeAction, e, ActionPlaces.UNKNOWN, dataContext) if (ActionUtil.lastUpdateAndCheckDumb(mergeAction, event, true)) { performActionDumbAwareWithCallbacks(mergeAction, event) } else { OpenSourceUtil.openSourcesFrom(dataContext, true) } true } } fun editedCommitChanged() { rebuildTree() commitPanel.editedCommit?.let { val node = TreeUtil.findNodeWithObject(root, it) node?.let { expandPath(TreeUtil.getPathFromRoot(node)) } } } override fun customizeTreeModel(builder: TreeModelBuilder) { super.customizeTreeModel(builder) commitPanel.editedCommit?.let { val commitNode = EditedCommitNode(it) builder.insertSubtreeRoot(commitNode) builder.insertChanges(it.commit.changes, commitNode) } } override fun performStageOperation(nodes: List<GitFileStatusNode>, operation: StagingAreaOperation) { performStageOperation(project, nodes, operation) } override fun getDndOperation(targetKind: NodeKind): StagingAreaOperation? { return when (targetKind) { NodeKind.STAGED -> GitAddOperation NodeKind.UNSTAGED -> GitResetOperation else -> null } } override fun showMergeDialog(conflictedFiles: List<VirtualFile>) { AbstractVcsHelper.getInstance(project).showMergeDialog(conflictedFiles) } override fun createHoverIcon(node: ChangesBrowserGitFileStatusNode): HoverIcon? { val conflict = node.conflict ?: return null val mergeHandler = createMergeHandler(project) if (!canShowMergeWindow(project, mergeHandler, conflict)) return null return GitStageMergeHoverIcon(mergeHandler, conflict) } fun getIncludedRoots(): Collection<VirtualFile> { if (!isInclusionEnabled()) return state.allRoots return inclusionModel.getInclusion().mapNotNull { (it as? GitRepository)?.root } } fun addIncludedRootsListener(listener: IncludedRootsListener, disposable: Disposable) { includedRootsListeners.addListener(listener, disposable) } private fun isInclusionEnabled(): Boolean { return state.rootStates.size > 1 && state.stagedRoots.size > 1 && groupingSupport.isAvailable(REPOSITORY_GROUPING) && groupingSupport[REPOSITORY_GROUPING] } override fun isInclusionEnabled(node: ChangesBrowserNode<*>): Boolean { return isInclusionEnabled() && node is RepositoryChangesBrowserNode && isUnderKind(node, NodeKind.STAGED) } override fun isInclusionVisible(node: ChangesBrowserNode<*>): Boolean = isInclusionEnabled(node) override fun getIncludableUserObjects(treeModelData: VcsTreeModelData): List<Any> { return treeModelData .rawNodesStream() .filter { node -> isIncludable(node) } .map { node -> node.userObject } .collect(Collectors.toList()) } override fun getNodeStatus(node: ChangesBrowserNode<*>): ThreeStateCheckBox.State { return inclusionModel.getInclusionState(node.userObject) } private fun isUnderKind(node: ChangesBrowserNode<*>, nodeKind: NodeKind): Boolean { val nodePath = node.path ?: return false return (nodePath.find { it is MyKindNode } as? MyKindNode)?.kind == nodeKind } override fun installGroupingSupport(): ChangesGroupingSupport { val result = ChangesGroupingSupport(project, this, false) if (PropertiesComponent.getInstance(project).getValues(GROUPING_PROPERTY_NAME) == null) { val oldGroupingKeys = (PropertiesComponent.getInstance(project).getValues(GROUPING_KEYS) ?: DEFAULT_GROUPING_KEYS).toMutableSet() oldGroupingKeys.add(REPOSITORY_GROUPING) PropertiesComponent.getInstance(project).setValues(GROUPING_PROPERTY_NAME, *oldGroupingKeys.toTypedArray()) } installGroupingSupport(this, result, GROUPING_PROPERTY_NAME, *DEFAULT_GROUPING_KEYS + REPOSITORY_GROUPING) return result } private inner class GitStageMergeHoverIcon(private val handler: GitMergeHandler, private val conflict: GitConflict) : HoverIcon(AllIcons.Vcs.Merge, message("changes.view.merge.action.text")) { override fun invokeAction(node: ChangesBrowserNode<*>) { showMergeWindow(project, handler, listOf(conflict)) } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as GitStageMergeHoverIcon if (conflict != other.conflict) return false return true } override fun hashCode(): Int { return conflict.hashCode() } } } interface IncludedRootsListener : EventListener { fun includedRootsChanged() } private inner class MyGitStageTrackerListener : GitStageTrackerListener { override fun update() { [email protected]() } } private inner class MyGitChangeProviderListener : GitRefreshListener { override fun progressStarted() { runInEdt(this@GitStagePanel) { updateProgressState() } } override fun progressStopped() { runInEdt(this@GitStagePanel) { updateProgressState() } } private fun updateProgressState() { if (isRefreshInProgress()) { tree.setEmptyText(message("stage.loading.status")) progressStripe.startLoading() } else { progressStripe.stopLoading() tree.setEmptyText("") } } } private inner class MyChangeListListener : ChangeListListener { override fun changeListUpdateDone() { runInEdt(this@GitStagePanel) { updateChangesStatusPanel() } } } private inner class MyCommitWorkflowListener: CommitWorkflowListener { override fun executionEnded() { if (hasPendingUpdates) { hasPendingUpdates = false update() } } override fun vcsesChanged() = Unit override fun executionStarted() = Unit override fun beforeCommitChecksStarted() = Unit override fun beforeCommitChecksEnded(isDefaultCommit: Boolean, result: CheckinHandler.ReturnResult) = Unit } companion object { @NonNls private const val GROUPING_PROPERTY_NAME = "GitStage.ChangesTree.GroupingKeys" private const val GIT_STAGE_PANEL_PLACE = "GitStagePanelPlace" } } internal fun createMergeHandler(project: Project) = GitMergeHandler(project, GitDefaultMergeDialogCustomizer(project))
apache-2.0
jwren/intellij-community
plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/declarations/KotlinUAnnotatedLocalVariable.kt
4
742
// 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.uast.kotlin import com.intellij.psi.PsiLocalVariable import org.jetbrains.annotations.ApiStatus import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.uast.UAnnotation import org.jetbrains.uast.UElement @ApiStatus.Internal open class KotlinUAnnotatedLocalVariable( psi: PsiLocalVariable, sourcePsi: KtElement, uastParent: UElement?, computeAnnotations: (parent: UElement) -> List<UAnnotation> ) : KotlinULocalVariable(psi, sourcePsi, uastParent) { override val uAnnotations: List<UAnnotation> by lz { computeAnnotations(this) } }
apache-2.0
jwren/intellij-community
plugins/kotlin/refIndex/tests/testData/compilerIndex/functions/hierarchy/kotlin/KKKK/KKK.kt
140
56
open class KKK : KK() { override fun test() = Unit }
apache-2.0
ninjahoahong/unstoppable
app/src/main/java/com/ninjahoahong/unstoppable/SplashActivity.kt
1
396
package com.ninjahoahong.unstoppable import android.os.Bundle import android.support.v7.app.AppCompatActivity import org.jetbrains.anko.intentFor class SplashActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val intent = intentFor<MainActivity>() startActivity(intent) finish() } }
mit
JetBrains/kotlin-native
shared/src/main/kotlin/org/jetbrains/kotlin/konan/target/KonanTargetExtenstions.kt
1
1715
package org.jetbrains.kotlin.konan.target // TODO: This all needs to go to konan.properties fun KonanTarget.supportsCodeCoverage(): Boolean = this == KonanTarget.MINGW_X64 || this == KonanTarget.LINUX_X64 || this == KonanTarget.MACOS_X64 || this == KonanTarget.IOS_X64 fun KonanTarget.supportsMimallocAllocator(): Boolean = when(this) { is KonanTarget.LINUX_X64 -> true is KonanTarget.MINGW_X86 -> true is KonanTarget.MINGW_X64 -> true is KonanTarget.MACOS_X64 -> true is KonanTarget.LINUX_ARM64 -> true is KonanTarget.LINUX_ARM32_HFP -> true is KonanTarget.ANDROID_X64 -> true is KonanTarget.ANDROID_ARM64 -> true is KonanTarget.IOS_ARM32 -> true is KonanTarget.IOS_ARM64 -> true is KonanTarget.IOS_X64 -> true else -> false // watchOS/tvOS/android_x86/android_arm32 aren't tested; linux_mips32/linux_mipsel32 need linking with libatomic. } fun KonanTarget.supportsThreads(): Boolean = when(this) { is KonanTarget.WASM32 -> false is KonanTarget.ZEPHYR -> false else -> true } fun KonanTarget.supportedSanitizers(): List<SanitizerKind> = when(this) { is KonanTarget.LINUX_X64 -> listOf(SanitizerKind.ADDRESS) is KonanTarget.MACOS_X64 -> listOf(SanitizerKind.THREAD) // TODO: Enable ASAN on macOS. Currently there's an incompatibility between clang frontend version and clang_rt.asan version. // TODO: Enable TSAN on linux. Currently there's a link error between clang_rt.tsan and libstdc++. // TODO: Consider supporting mingw. // TODO: Support macOS arm64 else -> listOf() }
apache-2.0
JetBrains/kotlin-native
backend.native/tests/codegen/function/defaultsWithInlineClasses.kt
4
382
/* * 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.function.defaultsWithInlineClasses import kotlin.test.* inline class Foo(val value: Int) fun foo(x: Foo = Foo(42)) = x.value @Test fun runTest() { assertEquals(foo(), 42) assertEquals(foo(Foo(17)), 17) }
apache-2.0
GunoH/intellij-community
platform/webSymbols/src/com/intellij/webSymbols/webTypes/WebTypesDocumentationCustomizer.kt
2
1045
// 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.webSymbols.webTypes import com.intellij.webSymbols.WebSymbol import com.intellij.webSymbols.documentation.WebSymbolDocumentation import com.intellij.webSymbols.documentation.WebSymbolDocumentationCustomizer import com.intellij.webSymbols.WebSymbolsBundle import com.intellij.webSymbols.patterns.impl.RegExpPattern import org.jetbrains.annotations.NonNls class WebTypesDocumentationCustomizer : WebSymbolDocumentationCustomizer { override fun customize(symbol: WebSymbol, documentation: WebSymbolDocumentation): WebSymbolDocumentation { val pattern = symbol.pattern as? RegExpPattern return if (pattern != null && symbol.properties[WebSymbol.PROP_DOC_HIDE_PATTERN] != true) { @NonNls val patternString: String = pattern.toString() documentation.withDescriptionSection(WebSymbolsBundle.message("mdn.documentation.section.pattern"), patternString) } else documentation } }
apache-2.0
GunoH/intellij-community
platform/lang-impl/src/com/intellij/ide/projectView/actions/LoadUnloadModulesAction.kt
6
1998
// Copyright 2000-2020 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.ide.projectView.actions import com.intellij.ide.actions.OpenModuleSettingsAction import com.intellij.ide.projectView.impl.ProjectRootsUtil import com.intellij.idea.ActionsBundle.actionText import com.intellij.openapi.actionSystem.* import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.roots.ui.configuration.ConfigureUnloadedModulesDialog private const val ACTION_ID = "LoadUnloadModules" class LoadUnloadModulesAction : DumbAwareAction(actionText(ACTION_ID)) { override fun update(e: AnActionEvent) { e.presentation.isEnabledAndVisible = isEnabled(e) } override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.BGT } private fun isEnabled(e: AnActionEvent): Boolean { val project = e.project ?: return false val moduleManager = ModuleManager.getInstance(project) if (moduleManager.modules.size <= 1 && moduleManager.unloadedModuleDescriptions.isEmpty()) return false val file = e.getData(LangDataKeys.VIRTUAL_FILE) return !ActionPlaces.isPopupPlace(e.place) || OpenModuleSettingsAction.isModuleInContext(e) || file != null && ProjectRootsUtil.findUnloadedModuleByContentRoot(file, project) != null } override fun actionPerformed(e: AnActionEvent) { val selectedModuleName = e.getData(LangDataKeys.MODULE_CONTEXT)?.name ?: getSelectedUnloadedModuleName(e) ?: e.getData(PlatformCoreDataKeys.MODULE)?.name ConfigureUnloadedModulesDialog(e.project!!, selectedModuleName).show() } private fun getSelectedUnloadedModuleName(e: AnActionEvent): String? { val project = e.project ?: return null val file = e.getData(LangDataKeys.VIRTUAL_FILE) ?: return null return ProjectRootsUtil.findUnloadedModuleByFile(file, project) } }
apache-2.0
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/shortenRefs/removeCompanionRefWithQualifiedReceiverInCalleeExpression.kt
13
401
class T { interface Factory { operator fun invoke(i: Int): IntPredicate companion object { inline operator fun invoke(crossinline f: (Int) -> IntPredicate) = object : Factory { override fun invoke(i: Int) = f(i) } } } } <selection>fun foo(): T.Factory = T.Factory.Companion { k -> IntPredicate { n -> n % k == 0 } }</selection>
apache-2.0
GunoH/intellij-community
platform/workspaceModel/storage/src/com/intellij/workspaceModel/deft/api/annotations/Default.kt
5
273
// 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.deft.api.annotations @Target(AnnotationTarget.PROPERTY, AnnotationTarget.PROPERTY_GETTER) annotation class Default
apache-2.0
LouisCAD/Splitties
test-helpers/src/androidMain/kotlin/splitties/internal/test/SuspendTest.kt
1
694
/* * Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license. */ package splitties.internal.test import android.os.Build import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.runBlocking import org.junit.Assume.assumeTrue actual fun runTest( alsoRunInNativeWorker: Boolean, skipIfRoboelectric: Boolean, block: suspend CoroutineScope.() -> Unit ) { if (skipIfRoboelectric) { val roboelectric = "robolectric" assumeTrue( "Running with Roboelectric, test skipped", Build.DEVICE != roboelectric && Build.PRODUCT != roboelectric ) } runBlocking { block() } }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/refIndex/tests/testData/compilerIndex/properties/hierarchy/kotlin/set/KKKK/k_.kt
300
28
fun k() { K().property }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/codeInsight/unwrapAndRemove/unwrapFunctionParameter/functionHasMultiParam.kt
8
128
// IS_APPLICABLE: false fun test() { val i = 1 foo(baz<caret>(i, 2)) } fun foo(i: Int) {} fun baz(i: Int, j: Int) = 1
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/joinLines/addSemicolon/WhileBlockAndACall2.kt
13
78
fun foo() { while (true) { println() <caret>} println() }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/refIndex/tests/testData/compilerIndex/functions/fromObject/fromCompanion/named/nestedObject/function/KotlinClass.kt
9
180
package one.two class KotlinClass { companion object Named { object NestedObject { fun func<caret>tion() { } } } } class Receiver
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/compiler-plugins/parcelize/tests/testData/checker/withoutParcelableSupertype.kt
13
648
package test import kotlinx.parcelize.Parcelize import android.os.Parcelable @Parcelize class <error descr="[NO_PARCELABLE_SUPERTYPE] No 'Parcelable' supertype">Without</error>(val firstName: String, val secondName: String, val age: Int) @Parcelize class With(val firstName: String, val secondName: String, val age: Int) : Parcelable interface MyParcelableIntf : Parcelable abstract class MyParcelableCl : Parcelable @Parcelize class WithIntfSubtype(val firstName: String, val secondName: String, val age: Int) : MyParcelableIntf @Parcelize class WithClSubtype(val firstName: String, val secondName: String, val age: Int) : MyParcelableCl()
apache-2.0
smmribeiro/intellij-community
platform/platform-impl/src/com/intellij/ide/util/TipAndTrickPromotionFactory.kt
2
588
// 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.ide.util import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.project.Project import javax.swing.JPanel interface TipAndTrickPromotionFactory { fun createPromotionPanel(project: Project, tip: TipAndTrickBean): JPanel? companion object { @JvmStatic val EP_NAME = ExtensionPointName<TipAndTrickPromotionFactory>("com.intellij.tipAndTrickPromotionFactory") } }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/j2k/old/tests/testData/fileOrElement/arrayType/newStringArray.kt
26
22
val a = arrayOf("abc")
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/intentions/replaceExplicitFunctionLiteralParamWithIt/applicable_inPropertyInitializer.kt
9
174
// AFTER-WARNING: Parameter 'i' is never used // AFTER-WARNING: Variable 'a' is never used fun foo() { val a: (Int) -> Unit = { <caret>a -> bar(a) } } fun bar(i: Int) {}
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/completion/tests/testData/basic/common/ExtensionFunReceiver.kt
7
214
fun testing() {} fun S<caret> // Should complete types for receiver after explicit basic completion call // INVOCATION_COUNT: 1 // EXIST: String // EXIST_JAVA_ONLY: StringBuffer // EXIST: Set // ABSENT: testing
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/refactoring/extractFunction/basic/malformedStatements.kt
13
150
fun foo(a: Int): Int { val b: Int = 1 val c: Int = 1 <selection>println(a) println(b) println</selection>(c) return a + b*c }
apache-2.0
smmribeiro/intellij-community
python/src/com/jetbrains/python/codeInsight/mlcompletion/PyClassCompletionFeatures.kt
13
1244
// 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 com.jetbrains.python.codeInsight.mlcompletion import com.intellij.codeInsight.completion.ml.CompletionEnvironment import com.intellij.psi.util.PsiTreeUtil import com.jetbrains.python.psi.PyClass import com.jetbrains.python.psi.PyUtil object PyClassCompletionFeatures { data class ClassFeatures(val diffLinesWithClassDef: Int, val classHaveConstructor: Boolean) fun getClassCompletionFeatures(environment: CompletionEnvironment): ClassFeatures? { val parentClass = PsiTreeUtil.getParentOfType(environment.parameters.position, PyClass::class.java) ?: return null val lookup = environment.lookup val editor = lookup.topLevelEditor val caretOffset = lookup.lookupStart val logicalPosition = editor.offsetToLogicalPosition(caretOffset) val lineno = logicalPosition.line val classLogicalPosition = editor.offsetToLogicalPosition(parentClass.textOffset) val classLineno = classLogicalPosition.line val classHaveConstructor = parentClass.methods.any { PyUtil.isInitOrNewMethod(it) } return ClassFeatures(lineno - classLineno, classHaveConstructor) } }
apache-2.0
ifabijanovic/swtor-holonet
android/app/src/test/java/com/ifabijanovic/holonet/helper/URLComponentsTests.kt
1
1394
package com.ifabijanovic.holonet.helper import org.junit.Assert.* import org.junit.Test /** * Created by feb on 19/03/2017. */ class URLComponentsTests { @Test fun queryValue_Success() { val url = "http://www.holonet.test?param=value" val value = URLComponents(url).queryValue("param") assertNotNull(value) assertEquals("value", value) } @Test fun queryValue_NoParameters() { val url = "http://www.holonet.test" val value = URLComponents(url).queryValue("param") assertNull(value) } @Test fun queryValue_MissingParameter() { val url = "http://www.holonet.test?param=value" val value = URLComponents(url).queryValue("otherParam") assertNull(value) } @Test fun queryValue_MultipleParameters() { val url = "http://www.holonet.test?param1=value1&param2=value2" val value1 = URLComponents(url).queryValue("param1") val value2 = URLComponents(url).queryValue("param2") assertNotNull(value1) assertEquals("value1", value1) assertNotNull(value2) assertEquals("value2", value2) } @Test fun queryValue_MalformedUrl() { val url = "somewhere/test?param=value" val value = URLComponents(url).queryValue("param") assertNotNull(value) assertEquals("value", value) } }
gpl-3.0
mewebstudio/Kotlin101
src/Objects/CopyDataClass.kt
1
375
package Kotlin101.Objects.CopyDataClass data class Person(val firstName: String, val lastName: String){ public fun print(){ println("$firstName $lastName") } } fun main(args : Array<String>) { val presidentOne = Person("Bill", "Clinton") presidentOne.print() val presidentTwo = presidentOne.copy(firstName = "Hillary") presidentTwo.print() }
bsd-3-clause
adriangl/Dev-QuickSettings
app/src/main/kotlin/com/adriangl/devquicktiles/tiles/finishactivities/FinishActivitiesTileService.kt
1
1907
/* * Copyright (C) 2017 Adrián García * * 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.adriangl.devquicktiles.tiles.finishactivities import android.graphics.drawable.Icon import android.provider.Settings import com.adriangl.devquicktiles.R import com.adriangl.devquicktiles.tiles.DevelopmentTileService import com.adriangl.devquicktiles.utils.SettingsUtils class FinishActivitiesTileService : DevelopmentTileService<Int>() { companion object { val SETTING = Settings.Global.ALWAYS_FINISH_ACTIVITIES } override fun isActive(value: Int): Boolean { return value != 0 } override fun queryValue(): Int { var value = SettingsUtils.getIntFromGlobalSettings(contentResolver, SETTING) if (value > 1) value = 1 return value } override fun saveValue(value: Int) : Boolean { return SettingsUtils.setIntToGlobalSettings(contentResolver, SETTING, value) } override fun getValueList(): List<Int> { return listOf(0, 1) } override fun getIcon(value: Int): Icon? { return Icon.createWithResource(applicationContext, if (value != 0) R.drawable.ic_qs_finish_activities_enabled else R.drawable.ic_qs_finish_activities_disabled) } override fun getLabel(value: Int): CharSequence? { return getString(R.string.qs_finish_activities) } }
apache-2.0
kenail2002/logAnalyzer
h2database/src/main/java/p/k/tools/h2db/dao/LogDaoService.kt
1
261
package p.k.tools.h2db.dao import p.k.tools.datasource.DataStoreService import javax.sql.DataSource interface LogDaoService : DataStoreService { /** * @param dataSource the jdbcTemplate to set */ fun setDataSource(dataSource: DataSource) }
apache-2.0
jbmlaird/DiscogsBrowser
app/src/test/java/bj/vinylbrowser/singlelist/SingleListEpxControllerTest.kt
1
3681
package bj.vinylbrowser.singlelist import android.content.Context import android.os.Build.VERSION_CODES.LOLLIPOP import bj.vinylbrowser.model.common.RecyclerViewModel import bj.vinylbrowser.utils.ImageViewAnimator import com.nhaarman.mockito_kotlin.mock import junit.framework.Assert.assertEquals import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.MockitoAnnotations import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config /** * Created by Josh Laird on 22/05/2017. */ @RunWith(RobolectricTestRunner::class) @Config(sdk = intArrayOf(LOLLIPOP), manifest = Config.NONE) class SingleListEpxControllerTest { lateinit var controller: SingleListEpxController val context: Context = mock() val view: SingleListContract.View = mock() val imageViewAnimator: ImageViewAnimator = mock() @Before fun setUp() { MockitoAnnotations.initMocks(this) controller = SingleListEpxController(context, view, imageViewAnimator) controller.requestModelBuild() } @Test fun initialState_Loading() { val copyOfModels = controller.adapter.copyOfModels assertEquals(copyOfModels[0].javaClass.simpleName, "SmallEmptySpaceModel_") assertEquals(copyOfModels[1].javaClass.simpleName, "LoadingModel_") assertEquals(copyOfModels[2].javaClass.simpleName, "SmallEmptySpaceModel_") assertEquals(copyOfModels.size, 3) } @Test fun setItemsEmptyList_displaysCenterTextModel() { controller.setItems(emptyList<RecyclerViewModel>()) val copyOfModels = controller.adapter.copyOfModels assertEquals(copyOfModels[0].javaClass.simpleName, "SmallEmptySpaceModel_") assertEquals(copyOfModels[1].javaClass.simpleName, "CenterTextModel_") assertEquals(copyOfModels[2].javaClass.simpleName, "SmallEmptySpaceModel_") assertEquals(copyOfModels.size, 3) } @Test fun setItems_setsItems() { val recyclerViewModels = WantFactory.getThreeWants() controller.setItems(recyclerViewModels) val copyOfModels = controller.adapter.copyOfModels assertEquals(copyOfModels[0].javaClass.simpleName, "SmallEmptySpaceModel_") assertEquals(copyOfModels[1].javaClass.simpleName, "CardListItemModel_") assertEquals(copyOfModels[2].javaClass.simpleName, "CardListItemModel_") assertEquals(copyOfModels[3].javaClass.simpleName, "CardListItemModel_") assertEquals(copyOfModels[4].javaClass.simpleName, "SmallEmptySpaceModel_") assertEquals(copyOfModels.size, 5) } @Test fun errorThenSetItems_displaysItems() { controller.setError("") var copyOfModels = controller.adapter.copyOfModels assertEquals(copyOfModels[0].javaClass.simpleName, "SmallEmptySpaceModel_") assertEquals(copyOfModels[1].javaClass.simpleName, "CenterTextModel_") assertEquals(copyOfModels[2].javaClass.simpleName, "SmallEmptySpaceModel_") assertEquals(copyOfModels.size, 3) val recyclerViewModels = WantFactory.getThreeWants() controller.setItems(recyclerViewModels) copyOfModels = controller.adapter.copyOfModels assertEquals(copyOfModels[0].javaClass.simpleName, "SmallEmptySpaceModel_") assertEquals(copyOfModels[1].javaClass.simpleName, "CardListItemModel_") assertEquals(copyOfModels[2].javaClass.simpleName, "CardListItemModel_") assertEquals(copyOfModels[3].javaClass.simpleName, "CardListItemModel_") assertEquals(copyOfModels[4].javaClass.simpleName, "SmallEmptySpaceModel_") assertEquals(copyOfModels.size, 5) } }
mit
hsz/idea-gitignore
src/main/kotlin/mobi/hsz/idea/gitignore/lexer/IgnoreLexerAdapter.kt
1
433
// 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 mobi.hsz.idea.gitignore.lexer import com.intellij.lexer.FlexAdapter import com.intellij.openapi.vfs.VirtualFile /** * Definition of [com.intellij.lexer.FlexAdapter]. */ class IgnoreLexerAdapter constructor(virtualFile: VirtualFile? = null) : FlexAdapter(IgnoreLexer(virtualFile))
mit
Waboodoo/HTTP-Shortcuts
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/utils/GsonUtil.kt
1
2307
package ch.rmy.android.http_shortcuts.utils import android.net.Uri import androidx.core.net.toUri import ch.rmy.android.http_shortcuts.data.models.BaseModel import com.google.gson.ExclusionStrategy import com.google.gson.FieldAttributes import com.google.gson.Gson import com.google.gson.GsonBuilder import com.google.gson.JsonDeserializationContext import com.google.gson.JsonDeserializer import com.google.gson.JsonElement import com.google.gson.JsonParseException import com.google.gson.JsonParser import com.google.gson.JsonPrimitive import com.google.gson.JsonSerializationContext import com.google.gson.JsonSerializer import com.google.gson.reflect.TypeToken import io.realm.RealmObject import java.lang.reflect.Type object GsonUtil { fun prettyPrint(jsonString: String): String = try { val json = JsonParser.parseString(jsonString) val gson = GsonBuilder().setPrettyPrinting().create() gson.toJson(json) } catch (e: JsonParseException) { jsonString } fun importData(data: JsonElement): BaseModel = gson.fromJson(data, BaseModel::class.java) fun <T> fromJsonObject(jsonObject: String?): Map<String, T> { if (jsonObject == null) { return emptyMap() } val type = object : TypeToken<Map<String, T>>() { }.type return gson.fromJson(jsonObject, type) } fun toJson(item: Map<String, Any>): String = gson.toJson(item) val gson: Gson by lazy { GsonBuilder() .addSerializationExclusionStrategy(RealmExclusionStrategy()) .registerTypeAdapter(Uri::class.java, UriSerializer) .create() } object UriSerializer : JsonSerializer<Uri>, JsonDeserializer<Uri> { override fun serialize(src: Uri, typeOfSrc: Type?, context: JsonSerializationContext?): JsonElement = JsonPrimitive(src.toString()) override fun deserialize(json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext?): Uri? = json?.asString?.toUri() } private class RealmExclusionStrategy : ExclusionStrategy { override fun shouldSkipField(f: FieldAttributes) = f.declaringClass == RealmObject::class.java override fun shouldSkipClass(clazz: Class<*>) = false } }
mit
Waboodoo/HTTP-Shortcuts
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/usecases/GetBuiltInIconPickerDialogUseCase.kt
1
2330
package ch.rmy.android.http_shortcuts.usecases import android.content.Context import androidx.recyclerview.widget.RecyclerView import ch.rmy.android.framework.viewmodel.viewstate.DialogState import ch.rmy.android.http_shortcuts.R import ch.rmy.android.http_shortcuts.extensions.createDialogState import ch.rmy.android.http_shortcuts.icons.BuiltInIconAdapter import ch.rmy.android.http_shortcuts.icons.Icons import ch.rmy.android.http_shortcuts.icons.ShortcutIcon import ch.rmy.android.http_shortcuts.utils.GridLayoutManager import javax.inject.Inject class GetBuiltInIconPickerDialogUseCase @Inject constructor() { operator fun invoke(onIconSelected: (ShortcutIcon.BuiltInIcon) -> Unit): DialogState = createDialogState(DIALOG_ID) { title(R.string.title_choose_icon) .view(R.layout.dialog_icon_selector) .build() .show { val grid = findViewById<RecyclerView>(R.id.icon_selector_grid) grid.setHasFixedSize(true) val layoutManager = GridLayoutManager(context, R.dimen.grid_layout_builtin_icon_width) grid.layoutManager = layoutManager view.addOnLayoutChangeListener { view, _, _, _, _, _, _, _, _ -> layoutManager.setTotalWidth(view.width) } val adapter = BuiltInIconAdapter(getIcons(context)) { icon -> dismiss() onIconSelected(icon) } grid.adapter = adapter } } private fun getIcons(context: Context): List<ShortcutIcon.BuiltInIcon> = getColoredIcons(context).plus(getTintableIcons(context)) private fun getColoredIcons(context: Context): List<ShortcutIcon.BuiltInIcon> = Icons.getColoredIcons() .map { ShortcutIcon.BuiltInIcon.fromDrawableResource(context, it) } private fun getTintableIcons(context: Context): List<ShortcutIcon.BuiltInIcon> = Icons.getTintableIcons().map { iconResource -> ShortcutIcon.BuiltInIcon.fromDrawableResource(context, iconResource, Icons.TintColors.BLACK) } companion object { private const val DIALOG_ID = "built-in-icon-picker" } }
mit
dam5s/kspec
libraries/aspen/src/main/kotlin/io/damo/aspen/TestTreeRunner.kt
1
4834
package io.damo.aspen import org.junit.runner.Description import org.junit.runner.Description.createSuiteDescription import org.junit.runner.Description.createTestDescription import org.junit.runner.notification.Failure import org.junit.runner.notification.RunNotifier import org.junit.runners.ParentRunner import org.junit.runners.model.MultipleFailureException import org.junit.runners.model.Statement import java.util.* open class TestTreeRunner<T : TestTree>(val testTreeClass: Class<T>) : ParentRunner<TestTreeNodeRunner>(testTreeClass) { val testTree by lazy { testTreeClass.newInstance() } private val _children by lazy { buildChildren() } override fun getChildren() = _children override fun runChild(child: TestTreeNodeRunner, notifier: RunNotifier) { junitAction(describeChild(child), notifier) { child.run(notifier) } } override fun describeChild(child: TestTreeNodeRunner) = child.getDescription() open fun buildChildren(): MutableList<TestTreeNodeRunner> { testTree.readTestBody() val root = testTree.getRoot() val runFocusedOnly = root.isFocused() val rootBranchRunner = TestBranchRunner(testTreeClass, root, runFocusedOnly) return arrayListOf(rootBranchRunner) } } interface TestTreeNodeRunner { fun getDescription(): Description fun run(notifier: RunNotifier) } class TestBranchRunner<T : TestTree>(val testTreeClass: Class<T>, val testTreeNode: TestTreeNode, val runFocusedOnly: Boolean) : TestTreeNodeRunner, ParentRunner<TestTreeNodeRunner>(testTreeClass) { private val children = buildChildren() private val description = buildDescription() override fun getName(): String { if (testTreeNode.isRoot()) return super.getName() return testTreeNode.name } override fun getChildren() = children override fun getDescription() = description override fun describeChild(child: TestTreeNodeRunner) = child.getDescription() override fun runChild(child: TestTreeNodeRunner, notifier: RunNotifier) { junitAction(describeChild(child), notifier) { child.run(notifier) } } private fun buildChildren(): MutableList<TestTreeNodeRunner> { return getFilteredNodeChildren().map { when (it) { is TestBranch -> TestBranchRunner(testTreeClass, it, runFocusedOnly) is TestLeaf -> TestLeafRunner(it) else -> throw RuntimeException("Encountered unexpected TestTreeNode type $it") } }.toMutableList() } private fun getFilteredNodeChildren(): Collection<TestTreeNode> { var nodeChildren: Collection<TestTreeNode> = testTreeNode.children if (runFocusedOnly) { nodeChildren = nodeChildren.filter { it.isFocused() } } return nodeChildren } private fun buildDescription(): Description { if (testTreeNode.isRoot()) return super.getDescription() val desc = createSuiteDescription(name, testTreeNode.id)!! children.forEach { desc.addChild(describeChild(it)) } return desc } } class TestLeafRunner(val testLeaf: TestLeaf) : TestTreeNodeRunner { override fun getDescription(): Description { return createTestDescription(testLeaf.rootName(), testLeaf.testName, testLeaf.id)!! } override fun run(notifier: RunNotifier) { val description = getDescription() var statement = buildStatement() for (rule in testLeaf.allRules()) { statement = rule.apply(statement, description) } statement.evaluate() } private fun buildStatement(): Statement { val (befores, afters) = testLeaf.collectBeforesAndAfters() val errors = ArrayList<Throwable>() return object : Statement() { override fun evaluate() { try { befores.forEach { it.invoke() } testLeaf.block.invoke() } finally { afters.forEach { try { it.invoke() } catch(e: Throwable) { errors.add(e) } } MultipleFailureException.assertEmpty(errors) } } } } } fun junitAction(description: Description, notifier: RunNotifier, action: () -> Unit) { if (description.isTest) notifier.fireTestStarted(description) try { action() } catch(e: Throwable) { notifier.fireTestFailure(Failure(description, e)) } finally { if (description.isTest) notifier.fireTestFinished(description) } }
mit
marktony/ZhiHuDaily
app/src/main/java/com/marktony/zhihudaily/data/source/repository/GuokrHandpickNewsRepository.kt
1
4300
/* * Copyright 2016 lizhaotailang * * 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.marktony.zhihudaily.data.source.repository import com.marktony.zhihudaily.data.GuokrHandpickNewsResult import com.marktony.zhihudaily.data.source.Result import com.marktony.zhihudaily.data.source.datasource.GuokrHandpickDataSource import com.marktony.zhihudaily.util.formatGuokrHandpickTimeStringToLong import java.util.* /** * Created by lizhaotailang on 2017/5/24. * * Concrete implementation to load [GuokrHandpickNewsResult] from the data sources into a cache. * * Use the remote data source firstly, which is obtained from the server. * If the remote data was not available, then use the local data source, * which was from the locally persisted in database. */ class GuokrHandpickNewsRepository private constructor( private val mRemoteDataSource: GuokrHandpickDataSource, private val mLocalDataSource: GuokrHandpickDataSource ) : GuokrHandpickDataSource { private var mCachedItems: MutableMap<Int, GuokrHandpickNewsResult> = LinkedHashMap() companion object { private var INSTANCE: GuokrHandpickNewsRepository? = null fun getInstance(remoteDataSource: GuokrHandpickDataSource, localDataSource: GuokrHandpickDataSource): GuokrHandpickNewsRepository { if (INSTANCE == null) { INSTANCE = GuokrHandpickNewsRepository(remoteDataSource, localDataSource) } return INSTANCE!! } fun destroyInstance() { INSTANCE = null } } override suspend fun getGuokrHandpickNews(forceUpdate: Boolean, clearCache: Boolean, offset: Int, limit: Int): Result<List<GuokrHandpickNewsResult>> { if (!forceUpdate) { return Result.Success(mCachedItems.values.toList()) } val remoteResult = mRemoteDataSource.getGuokrHandpickNews(false, clearCache, offset, limit) return if (remoteResult is Result.Success) { refreshCache(clearCache, remoteResult.data) saveAll(remoteResult.data) remoteResult } else { mLocalDataSource.getGuokrHandpickNews(false, clearCache, offset, limit).also { if (it is Result.Success) { refreshCache(clearCache, it.data) } } } } override suspend fun getFavorites(): Result<List<GuokrHandpickNewsResult>> = mLocalDataSource.getFavorites() override suspend fun getItem(itemId: Int): Result<GuokrHandpickNewsResult> { val item = getItemWithId(itemId) if (item != null) { return Result.Success(item) } return mLocalDataSource.getItem(itemId).apply { if (this is Result.Success) { mCachedItems[this.data.id] = this.data } } } override suspend fun favoriteItem(itemId: Int, favorite: Boolean) { mLocalDataSource.favoriteItem(itemId, favorite) val cachedItem = getItemWithId(itemId) if (cachedItem != null) { cachedItem.isFavorite = favorite } } override suspend fun saveAll(list: List<GuokrHandpickNewsResult>) { for (item in list) { item.timestamp = formatGuokrHandpickTimeStringToLong(item.datePublished) mCachedItems[item.id] = item } mLocalDataSource.saveAll(list) } private fun refreshCache(clearCache: Boolean, list: List<GuokrHandpickNewsResult>) { if (clearCache) { mCachedItems.clear() } for (item in list) { mCachedItems[item.id] = item } } private fun getItemWithId(itemId: Int): GuokrHandpickNewsResult? = if (mCachedItems.isEmpty()) null else mCachedItems[itemId] }
apache-2.0
chiken88/passnotes
app/src/main/kotlin/com/ivanovsky/passnotes/presentation/core/widget/SquareLayout.kt
1
567
package com.ivanovsky.passnotes.presentation.core.widget import android.content.Context import android.util.AttributeSet import android.widget.RelativeLayout class SquareLayout(context: Context?, attrs: AttributeSet?) : RelativeLayout(context, attrs) { override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val size = MeasureSpec.getSize(widthMeasureSpec) super.onMeasure( MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY) ) } }
gpl-2.0
MaTriXy/gradle-play-publisher-1
play/android-publisher/src/main/kotlin/com/github/triplet/gradle/androidpublisher/EditManager.kt
1
4229
package com.github.triplet.gradle.androidpublisher import java.io.File import java.util.ServiceLoader /** * Orchestrates all edit based operations. * * For more information on edits, see [here](https://developers.google.com/android-publisher/edits). */ interface EditManager { /** Retrieves the current app details. */ fun getAppDetails(): GppAppDetails /** Retrieves the current app listings for all languages. */ fun getListings(): List<GppListing> /** Retrieves the app's graphics for the given [locale] and [type]. */ fun getImages(locale: String, type: String): List<GppImage> /** Retrieves the highest version code available for this app. */ fun findMaxAppVersionCode(): Long /** Retrieves the track with the highest version code available for this app. */ fun findLeastStableTrackName(): String? /** Retrieves the release notes across all tracks for this app. */ fun getReleaseNotes(): List<ReleaseNote> /** Publish app details, overwriting any existing values. */ fun publishAppDetails( defaultLocale: String?, contactEmail: String?, contactPhone: String?, contactWebsite: String? ) /** * Publish an app listing for the given [locale], overwriting any existing values. * * Note: valid locales may be found * [here](https://support.google.com/googleplay/android-developer/table/4419860?hl=en). */ fun publishListing( locale: String, title: String?, shortDescription: String?, fullDescription: String?, video: String? ) /** Publish images for a given [locale] and [type], overwriting any existing values. */ fun publishImages(locale: String, type: String, images: List<File>) /** * Promote a release from [fromTrackName] to [promoteTrackName] with the specified update * params. */ fun promoteRelease( promoteTrackName: String, fromTrackName: String, releaseStatus: ReleaseStatus?, releaseName: String?, releaseNotes: Map</* locale= */String, /* text= */String?>?, userFraction: Double?, updatePriority: Int?, retainableArtifacts: List<Long>? ) /** Uploads and publishes the given [bundleFile]. */ fun uploadBundle( bundleFile: File, mappingFile: File?, strategy: ResolutionStrategy, didPreviousBuildSkipCommit: Boolean, trackName: String, releaseStatus: ReleaseStatus?, releaseName: String?, releaseNotes: Map</* locale= */String, /* text= */String?>?, userFraction: Double?, updatePriority: Int?, retainableArtifacts: List<Long>? ) /** * Uploads the given [apkFile]. * * Note: since APKs have splits, APK management is a two step process. The APKs must first be * uploaded and then published using [publishApk]. */ fun uploadApk( apkFile: File, mappingFile: File?, strategy: ResolutionStrategy, mainObbRetainable: Int?, patchObbRetainable: Int? ): Long? /** Publishes a set of APKs uploaded with [uploadApk]. */ fun publishApk( versionCodes: List<Long>, didPreviousBuildSkipCommit: Boolean, trackName: String, releaseStatus: ReleaseStatus?, releaseName: String?, releaseNotes: Map</* locale= */String, /* text= */String?>?, userFraction: Double?, updatePriority: Int?, retainableArtifacts: List<Long>? ) /** Basic factory to create [EditManager] instances. */ interface Factory { /** Creates a new [EditManager]. */ fun create(publisher: PlayPublisher, editId: String): EditManager } companion object { /** Creates a new [EditManager]. */ operator fun invoke( publisher: PlayPublisher, editId: String ): EditManager = ServiceLoader.load(Factory::class.java).last() .create(publisher, editId) } }
mit
intrigus/jtransc
jtransc-utils/src/com/jtransc/lang/nullable.kt
2
113
package com.jtransc.lang fun <T, T2> T?.nullMap(notNull:T2, isNull:T2) = if (this != null) notNull else isNull
apache-2.0
quran/quran_android
common/data/src/main/java/com/quran/data/source/PageProvider.kt
2
930
package com.quran.data.source import androidx.annotation.StringRes import com.quran.data.model.audio.Qari interface PageProvider { fun getDataSource(): QuranDataSource fun getPageSizeCalculator(displaySize: DisplaySize): PageSizeCalculator fun getImageVersion(): Int fun getImagesBaseUrl(): String fun getImagesZipBaseUrl(): String fun getPatchBaseUrl(): String fun getAyahInfoBaseUrl(): String fun getDatabasesBaseUrl(): String fun getAudioDatabasesBaseUrl(): String fun getAudioDirectoryName(): String fun getDatabaseDirectoryName(): String fun getAyahInfoDirectoryName(): String fun getImagesDirectoryName(): String fun ayahInfoDbHasGlyphData(): Boolean = false @StringRes fun getPreviewTitle(): Int @StringRes fun getPreviewDescription(): Int fun getPageContentType(): PageContentType = PageContentType.IMAGE fun getFallbackPageType(): String? = null fun getQaris(): List<Qari> }
gpl-3.0
justin-hayes/kotlin-boot-react
backend/src/main/kotlin/me/justinhayes/bookclub/service/BookService.kt
1
1094
package me.justinhayes.bookclub.service import me.justinhayes.bookclub.client.BookClient import me.justinhayes.bookclub.domain.Book import me.justinhayes.bookclub.repository.BookRepository import me.justinhayes.bookclub.util.toIsbn13 import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Service interface BookService { fun getAllBooks(): List<Book> fun getBookByIsbn(isbn: String): Book } @Service class BookServiceImpl @Autowired constructor(val repository: BookRepository, val client: BookClient) : BookService { override fun getAllBooks(): List<Book> = repository.findAll().toList() override fun getBookByIsbn(isbn: String): Book { val isbn13 = isbn.toIsbn13() return repository.findOne(isbn13) ?: repository.save(addCoverToBook(client.getBookByIsbn(isbn13))) } private fun addCoverToBook(book: Book): Book { val coverUrl = client.findCoverForBook(book.isbn); return if (coverUrl != null) book.copy(coverUrl = coverUrl) else book } }
mit
AVnetWS/Hentoid
app/src/test/java/me/devsaki/hentoid/viewmodels/SearchViewModelTest.kt
1
8475
package me.devsaki.hentoid.viewmodels import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.lifecycle.LiveData import androidx.lifecycle.Observer import io.kotlintest.matchers.numerics.shouldBeGreaterThanOrEqual import io.kotlintest.matchers.types.shouldNotBeNull import io.kotlintest.shouldBe import me.devsaki.hentoid.database.CollectionDAO import me.devsaki.hentoid.database.ObjectBoxDAO import me.devsaki.hentoid.database.domains.Attribute import me.devsaki.hentoid.database.domains.Content import me.devsaki.hentoid.enums.AttributeType import me.devsaki.hentoid.enums.Site import me.devsaki.hentoid.enums.StatusContent import me.devsaki.hentoid.mocks.AbstractObjectBoxTest import net.lachlanmckee.timberjunit.TimberTestRule import org.junit.BeforeClass import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import java.util.concurrent.TimeoutException @RunWith(RobolectricTestRunner::class) class SearchViewModelTest : AbstractObjectBoxTest() { @get:Rule val logAllAlwaysRule: TimberTestRule? = TimberTestRule.logAllAlways() @get:Rule val instantTaskExecutorRule = InstantTaskExecutorRule() companion object { lateinit var mockObjectBoxDAO: CollectionDAO @BeforeClass @JvmStatic fun prepareDB() { println(">> Preparing DB...") val attrs1 = ArrayList<Attribute>() attrs1.add(Attribute(AttributeType.ARTIST, "artist1")) attrs1.add(Attribute(AttributeType.LANGUAGE, "english")) val attrs2 = ArrayList<Attribute>() attrs2.add(Attribute(AttributeType.ARTIST, "artist2")) attrs2.add(Attribute(AttributeType.LANGUAGE, "english")) val attrs3 = ArrayList<Attribute>() attrs3.add(Attribute(AttributeType.ARTIST, "artist3")) attrs3.add(Attribute(AttributeType.LANGUAGE, "english")) mockObjectBoxDAO = ObjectBoxDAO(store) mockObjectBoxDAO.insertContent(Content().setTitle("").setStatus(StatusContent.DOWNLOADED).setSite(Site.ASMHENTAI).addAttributes(attrs1)) mockObjectBoxDAO.insertContent(Content().setTitle("").setStatus(StatusContent.DOWNLOADED).setSite(Site.HITOMI).addAttributes(attrs1)) mockObjectBoxDAO.insertContent(Content().setTitle("").setStatus(StatusContent.DOWNLOADED).setSite(Site.ASMHENTAI).addAttributes(attrs2)) mockObjectBoxDAO.insertContent(Content().setTitle("").setStatus(StatusContent.ONLINE).setSite(Site.HITOMI).addAttributes(attrs3)) println(">> DB prepared") } } fun lookForAttr(type: AttributeType, name: String): Attribute? { val result = mockObjectBoxDAO.selectAttributeMasterDataPaged(listOf(type), name, null, false, false, false, 1, 40, 0).blockingGet() return result.attributes[0] } fun <T> LiveData<T>.observeForTesting(block: () -> Unit) { val observer = Observer<T> { } try { observeForever(observer) block() } finally { removeObserver(observer) } } /** * Gets the value of a [LiveData] or waits for it to have one, with a timeout. * * Use this extension from host-side (JVM) tests. It's recommended to use it alongside * `InstantTaskExecutorRule` or a similar mechanism to execute tasks synchronously. */ fun <T> LiveData<T>.getOrAwaitValue( time: Long = 2, timeUnit: TimeUnit = TimeUnit.SECONDS, afterObserve: () -> Unit = {} ): T { var data: T? = null val latch = CountDownLatch(1) val observer = object : Observer<T> { override fun onChanged(o: T?) { data = o latch.countDown() [email protected](this) } } this.observeForever(observer) afterObserve.invoke() // Don't wait indefinitely if the LiveData is not set. if (!latch.await(time, timeUnit)) { this.removeObserver(observer) throw TimeoutException("LiveData value was never set.") } @Suppress("UNCHECKED_CAST") return data as T } @Test fun `verify initial state`() { println(">> verify initial state START") val viewModel = SearchViewModel(mockObjectBoxDAO, 1) viewModel.selectedAttributesData.shouldNotBeNull() println(">> verify initial state END") } @Test fun `count category attributes unfiltered`() { println(">> count category attributes unfiltered START") val viewModel = SearchViewModel(mockObjectBoxDAO, 1) viewModel.update() val attrs = viewModel.attributesCountData.value attrs.shouldNotBeNull() // General attributes attrs.size().shouldBe(3) attrs.indexOfKey(AttributeType.ARTIST.code).shouldBeGreaterThanOrEqual(0) attrs.indexOfKey(AttributeType.LANGUAGE.code).shouldBeGreaterThanOrEqual(0) attrs.indexOfKey(AttributeType.SOURCE.code).shouldBeGreaterThanOrEqual(0) // Details attrs[AttributeType.ARTIST.code].shouldBe(2) attrs[AttributeType.LANGUAGE.code].shouldBe(1) attrs[AttributeType.SOURCE.code].shouldBe(2) println(">> count category attributes unfiltered END") } @Test fun `list category attributes unfiltered`() { println(">> list category attributes unfiltered START") val viewModel = SearchViewModel(mockObjectBoxDAO, 1) viewModel.update() val typeList = ArrayList<AttributeType>() typeList.add(AttributeType.ARTIST) viewModel.setAttributeTypes(typeList) viewModel.setAttributeQuery("", 1, 40) val attrs = viewModel.availableAttributesData.value attrs.shouldNotBeNull() attrs.attributes.shouldNotBeNull() attrs.totalSelectedAttributes.shouldBe(2) attrs.attributes.size.shouldBe(2) attrs.attributes[0].name.shouldBe("artist1") attrs.attributes[0].count.shouldBe(2) attrs.attributes[1].name.shouldBe("artist2") attrs.attributes[1].count.shouldBe(1) println(">> list category attributes unfiltered END") } @Test fun `count category attributes filtered`() { println(">> count category attributes filtered START") val viewModel = SearchViewModel(mockObjectBoxDAO, 1) val searchAttr = lookForAttr(AttributeType.ARTIST, "artist1") searchAttr.shouldNotBeNull() viewModel.addSelectedAttribute(searchAttr) val attrs = viewModel.attributesCountData.value attrs.shouldNotBeNull() // General attributes attrs.size().shouldBe(3) attrs.indexOfKey(AttributeType.ARTIST.code).shouldBeGreaterThanOrEqual(0) attrs.indexOfKey(AttributeType.LANGUAGE.code).shouldBeGreaterThanOrEqual(0) attrs.indexOfKey(AttributeType.SOURCE.code).shouldBeGreaterThanOrEqual(0) // Details attrs[AttributeType.ARTIST.code].shouldBe(0) // Once we select one artist, any other artist is unavailable attrs[AttributeType.LANGUAGE.code].shouldBe(1) attrs[AttributeType.SOURCE.code].shouldBe(2) println(">> count category attributes filtered END") } @Test fun `count books unfiltered`() { println(">> count books unfiltered START") val viewModel = SearchViewModel(mockObjectBoxDAO, 1) viewModel.update() val typeList = ArrayList<AttributeType>() typeList.add(AttributeType.ARTIST) viewModel.setAttributeTypes(typeList) viewModel.setAttributeQuery("", 1, 40) val books = viewModel.selectedContentCount.getOrAwaitValue {} books.shouldBe(3) // One of the books is not in the DOWNLOADED state println(">> count books unfiltered END") } @Test fun `count books filtered`() { println(">> count books filtered START") val viewModel = SearchViewModel(mockObjectBoxDAO, 1) val searchAttr = lookForAttr(AttributeType.ARTIST, "artist1") searchAttr.shouldNotBeNull() viewModel.addSelectedAttribute(searchAttr) val books = viewModel.selectedContentCount.getOrAwaitValue {} books.shouldBe(2) println(">> count books filtered END") } }
apache-2.0
seventhroot/elysium
bukkit/rpk-auction-lib-bukkit/src/main/kotlin/com/rpkit/auctions/bukkit/event/auction/RPKAuctionBiddingOpenEvent.kt
1
102
package com.rpkit.auctions.bukkit.event.auction interface RPKAuctionBiddingOpenEvent: RPKAuctionEvent
apache-2.0
rjhdby/motocitizen
Motocitizen/src/motocitizen/ui/menus/ContextMenuItem.kt
1
304
package motocitizen.ui.menus import android.content.Context import android.support.v7.widget.AppCompatButton class ContextMenuItem(context: Context, val name: String, val callback: () -> Unit) : AppCompatButton(context) { init { text = name setOnClickListener { callback() } } }
mit
seventhroot/elysium
bukkit/rpk-stores-bukkit/src/main/kotlin/com/rpkit/store/bukkit/database/table/RPKPurchaseTable.kt
1
5085
/* * Copyright 2018 Ross Binden * * 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.rpkit.store.bukkit.database.table import com.rpkit.core.database.Database import com.rpkit.core.database.Table import com.rpkit.players.bukkit.profile.RPKProfile import com.rpkit.store.bukkit.RPKStoresBukkit import com.rpkit.store.bukkit.purchase.RPKPurchase import com.rpkit.stores.bukkit.database.jooq.rpkit.Tables.RPKIT_PURCHASE import org.ehcache.config.builders.CacheConfigurationBuilder import org.ehcache.config.builders.ResourcePoolsBuilder import org.jooq.impl.DSL.constraint import org.jooq.impl.SQLDataType import java.sql.Timestamp class RPKPurchaseTable(database: Database, private val plugin: RPKStoresBukkit): Table<RPKPurchase>(database, RPKPurchase::class) { private val cache = if (plugin.config.getBoolean("caching.rpkit_purchase.id.enabled")) { database.cacheManager.createCache("rpkit-stores-bukkit.rpkit_purchase.id", CacheConfigurationBuilder.newCacheConfigurationBuilder(Int::class.javaObjectType, RPKPurchase::class.java, ResourcePoolsBuilder.heap(plugin.config.getLong("caching.rpkit_consumable_purchase.id.size"))).build()) } else { null } override fun create() { database.create .createTableIfNotExists(RPKIT_PURCHASE) .column(RPKIT_PURCHASE.ID, SQLDataType.INTEGER.identity(true)) .column(RPKIT_PURCHASE.STORE_ITEM_ID, SQLDataType.INTEGER) .column(RPKIT_PURCHASE.PROFILE_ID, SQLDataType.INTEGER) .column(RPKIT_PURCHASE.PURCHASE_DATE, SQLDataType.TIMESTAMP) .constraints( constraint("pk_rpkit_purchase").primaryKey(RPKIT_PURCHASE.ID) ) .execute() } override fun applyMigrations() { if (database.getTableVersion(this) == null) { database.setTableVersion(this, "1.6.0") } } override fun insert(entity: RPKPurchase): Int { database.create .insertInto( RPKIT_PURCHASE, RPKIT_PURCHASE.STORE_ITEM_ID, RPKIT_PURCHASE.PROFILE_ID, RPKIT_PURCHASE.PURCHASE_DATE ) .values( entity.storeItem.id, entity.profile.id, Timestamp.valueOf(entity.purchaseDate) ) .execute() val id = database.create.lastID().toInt() entity.id = id cache?.put(id, entity) return id } override fun update(entity: RPKPurchase) { database.create .update(RPKIT_PURCHASE) .set(RPKIT_PURCHASE.STORE_ITEM_ID, entity.storeItem.id) .set(RPKIT_PURCHASE.PROFILE_ID, entity.profile.id) .set(RPKIT_PURCHASE.PURCHASE_DATE, Timestamp.valueOf(entity.purchaseDate)) .where(RPKIT_PURCHASE.ID.eq(entity.id)) .execute() cache?.put(entity.id, entity) } override fun get(id: Int): RPKPurchase? { if (cache?.containsKey(id) == true) return cache[id] var purchase: RPKPurchase? = database.getTable(RPKConsumablePurchaseTable::class)[id] if (purchase != null) { cache?.put(id, purchase) return purchase } else { cache?.remove(id) } purchase = database.getTable(RPKPermanentPurchaseTable::class)[id] if (purchase != null) { cache?.put(id, purchase) return purchase } else { cache?.remove(id) } purchase = database.getTable(RPKTimedPurchaseTable::class)[id] if (purchase != null) { cache?.put(id, purchase) return purchase } else { cache?.remove(id) } return null } fun get(profile: RPKProfile): List<RPKPurchase> { return listOf( *database.getTable(RPKConsumablePurchaseTable::class).get(profile).toTypedArray(), *database.getTable(RPKPermanentPurchaseTable::class).get(profile).toTypedArray(), *database.getTable(RPKTimedPurchaseTable::class).get(profile).toTypedArray() ) } override fun delete(entity: RPKPurchase) { database.create .deleteFrom(RPKIT_PURCHASE) .where(RPKIT_PURCHASE.ID.eq(entity.id)) .execute() cache?.remove(entity.id) } }
apache-2.0
EMResearch/EvoMaster
core/src/main/kotlin/org/evomaster/core/problem/external/service/httpws/HarvestActualHttpWsResponseHandler.kt
1
17042
package org.evomaster.core.problem.external.service.httpws import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.databind.ObjectMapper import com.google.inject.Inject import org.evomaster.client.java.instrumentation.shared.PreDefinedSSLInfo import org.evomaster.core.EMConfig import org.evomaster.core.Lazy import org.evomaster.core.logging.LoggingUtil import org.evomaster.core.problem.external.service.ApiExternalServiceAction import org.evomaster.core.problem.external.service.httpws.param.HttpWsResponseParam import org.evomaster.core.problem.external.service.param.ResponseParam import org.evomaster.core.problem.util.ParamUtil import org.evomaster.core.problem.util.ParserDtoUtil import org.evomaster.core.problem.util.ParserDtoUtil.getJsonNodeFromText import org.evomaster.core.problem.util.ParserDtoUtil.parseJsonNodeAsGene import org.evomaster.core.problem.util.ParserDtoUtil.setGeneBasedOnString import org.evomaster.core.problem.util.ParserDtoUtil.wrapWithOptionalGene import org.evomaster.core.remote.TcpUtils import org.evomaster.core.remote.service.RemoteController import org.evomaster.core.search.gene.Gene import org.evomaster.core.search.gene.collection.EnumGene import org.evomaster.core.search.gene.optional.OptionalGene import org.evomaster.core.search.gene.string.StringGene import org.evomaster.core.search.service.Randomness import org.glassfish.jersey.client.ClientConfig import org.glassfish.jersey.client.ClientProperties import org.glassfish.jersey.client.HttpUrlConnectorProvider import org.slf4j.Logger import org.slf4j.LoggerFactory import java.util.concurrent.ConcurrentLinkedQueue import javax.annotation.PostConstruct import javax.annotation.PreDestroy import javax.ws.rs.ProcessingException import javax.ws.rs.client.Client import javax.ws.rs.client.ClientBuilder import javax.ws.rs.client.Entity import javax.ws.rs.client.Invocation import javax.ws.rs.core.MediaType import javax.ws.rs.core.Response import kotlin.math.max /** * based on collected requests to external services from WireMock * harvest actual responses by making the requests to real external services * * harvested actual responses could be applied as seeded in optimizing * test generation with search */ class HarvestActualHttpWsResponseHandler { // note rc should never be used in the thread of sending requests to external services @Inject(optional = true) private lateinit var rc: RemoteController @Inject private lateinit var config: EMConfig @Inject private lateinit var randomness: Randomness private lateinit var httpWsClient : Client /** * TODO * to further improve the efficiency of collecting actual responses, * might have a pool of threads to send requests */ private lateinit var threadToHandleRequest: Thread companion object { private val log: Logger = LoggerFactory.getLogger(HarvestActualHttpWsResponseHandler::class.java) private const val ACTUAL_RESPONSE_GENE_NAME = "ActualResponse" init{ /** * this default setting in jersey-client is false * to allow collected requests which might have restricted headers, then * set the property */ System.setProperty("sun.net.http.allowRestrictedHeaders", "true") } } /** * save the harvested actual responses * * key is actual request based on [HttpExternalServiceRequest.getDescription] * ie, "method:absoluteURL[headers]{body payload}", * value is an actual response info */ private val actualResponses = mutableMapOf<String, ActualResponseInfo>() /** * cache collected requests * * key is description of request with [HttpExternalServiceRequest.getDescription] * ie, "method:absoluteURL[headers]{body payload}", * value is an example of HttpExternalServiceRequest */ private val cachedRequests = mutableMapOf<String, HttpExternalServiceRequest>() /** * track a list of actual responses which have been seeded in the search based on * its corresponding request using its description, ie, ie, "method:absoluteURL[headers]{body payload}", */ private val seededResponses = mutableSetOf<String>() /** * need it for wait and notify in kotlin */ private val lock = Object() /** * an queue for handling urls for */ private val queue = ConcurrentLinkedQueue<String>() /** * key is dto class name * value is parsed gene based on schema */ private val extractedObjectDto = mutableMapOf<String, Gene>() /* skip headers if they depend on the client shall we skip Connection? */ private val skipHeaders = listOf("user-agent","host","accept-encoding") @PostConstruct fun initialize() { if (config.doHarvestActualResponse()){ val clientConfiguration = ClientConfig() .property(ClientProperties.CONNECT_TIMEOUT, 10_000) .property(ClientProperties.READ_TIMEOUT, config.tcpTimeoutMs) //workaround bug in Jersey client .property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true) .property(ClientProperties.FOLLOW_REDIRECTS, false) httpWsClient = ClientBuilder.newBuilder() .sslContext(PreDefinedSSLInfo.getSSLContext()) // configure ssl certificate .hostnameVerifier(PreDefinedSSLInfo.allowAllHostNames()) // configure all hostnames .withConfig(clientConfiguration).build() threadToHandleRequest = object :Thread() { override fun run() { while (!this.isInterrupted) { sendRequestToRealExternalService() } } } threadToHandleRequest.start() } } @PreDestroy private fun preDestroy() { if (config.doHarvestActualResponse()){ shutdown() } } fun shutdown(){ Lazy.assert { config.doHarvestActualResponse() } synchronized(lock){ if (threadToHandleRequest.isAlive) threadToHandleRequest.interrupt() httpWsClient.close() } } @Synchronized private fun sendRequestToRealExternalService() { synchronized(lock){ while (queue.size == 0) { lock.wait() } val first = queue.remove() val info = handleActualResponse(createInvocationToRealExternalService(cachedRequests[first]?:throw IllegalStateException("Fail to get Http request with description $first"))) if (info != null){ info.param.responseBody.markAllAsInitialized() actualResponses[first] = info }else LoggingUtil.uniqueWarn(log, "Fail to harvest actual responses from GET $first") } } /** * @return a copy of gene of actual responses based on the given [gene] and probability * * note that this method is used in mutation phase to mutate the given [gene] based on actual response if it exists * and based on the given [probability] * * the given [gene] should be the response body gene of ResponseParam */ fun getACopyOfItsActualResponseIfExist(gene: Gene, probability : Double) : ResponseParam?{ if (probability == 0.0) return null val exAction = gene.getFirstParent { it is ApiExternalServiceAction }?:return null // only support HttpExternalServiceAction, TODO for others if (exAction is HttpExternalServiceAction ){ Lazy.assert { gene.parent == exAction.response} if (exAction.response.responseBody == gene){ val p = if (!seededResponses.contains(exAction.request.getDescription()) && actualResponses.containsKey(exAction.request.getDescription())){ // if the actual response is never seeded, give a higher probably to employ it max(config.probOfHarvestingResponsesFromActualExternalServices, probability) } else probability if (randomness.nextBoolean(p)) return getACopyOfActualResponse(exAction.request) } } return null } /** * @return a copy of actual responses based on the given [httpRequest] and probability */ fun getACopyOfActualResponse(httpRequest: HttpExternalServiceRequest, probability: Double?=null) : ResponseParam?{ val harvest = probability == null || (randomness.nextBoolean(probability)) if (!harvest) return null synchronized(actualResponses){ val found= (actualResponses[httpRequest.getDescription()]?.param?.copy() as? ResponseParam) if (found!=null) seededResponses.add(httpRequest.getDescription()) return found } } /** * add http request to queue for sending them to real external services */ fun addHttpRequests(requests: List<HttpExternalServiceRequest>){ if (requests.isEmpty()) return if (!config.doHarvestActualResponse()) return // only harvest responses with GET method //val filter = requests.filter { it.method.equals("GET", ignoreCase = true) } synchronized(cachedRequests){ requests.forEach { cachedRequests.putIfAbsent(it.getDescription(), it) } } addRequests(requests.map { it.getDescription() }) } private fun addRequests(requests : List<String>) { if (requests.isEmpty()) return val notInCollected = requests.filterNot { actualResponses.containsKey(it) }.distinct() if (notInCollected.isEmpty()) return synchronized(lock){ val newRequests = notInCollected.filterNot { queue.contains(it) } if (newRequests.isEmpty()) return updateExtractedObjectDto() lock.notify() queue.addAll(newRequests) } } private fun buildInvocation(httpRequest : HttpExternalServiceRequest) : Invocation{ val build = httpWsClient.target(httpRequest.actualAbsoluteURL).request("*/*").apply { val handledHeaders = httpRequest.headers.filterNot { skipHeaders.contains(it.key.lowercase()) } if (handledHeaders.isNotEmpty()) handledHeaders.forEach { (t, u) -> this.header(t, u) } } val bodyEntity = if (httpRequest.body != null) { val contentType = httpRequest.getContentType() if (contentType !=null ) Entity.entity(httpRequest.body, contentType) else Entity.entity(httpRequest.body, MediaType.APPLICATION_FORM_URLENCODED_TYPE) } else { null } return when{ httpRequest.method.equals("GET", ignoreCase = true) -> build.buildGet() httpRequest.method.equals("POST", ignoreCase = true) -> build.buildPost(bodyEntity) httpRequest.method.equals("PUT", ignoreCase = true) -> build.buildPut(bodyEntity) httpRequest.method.equals("DELETE", ignoreCase = true) -> build.buildDelete() httpRequest.method.equals("PATCH", ignoreCase = true) -> build.build("PATCH", bodyEntity) httpRequest.method.equals("OPTIONS", ignoreCase = true) -> build.build("OPTIONS") httpRequest.method.equals("HEAD", ignoreCase = true) -> build.build("HEAD") httpRequest.method.equals("TRACE", ignoreCase = true) -> build.build("TRACE") else -> { throw IllegalStateException("NOT SUPPORT to create invocation for method ${httpRequest.method}") } } } private fun createInvocationToRealExternalService(httpRequest : HttpExternalServiceRequest) : Response?{ return try { buildInvocation(httpRequest).invoke() } catch (e: ProcessingException) { log.debug("There has been an issue in accessing external service with url (${httpRequest.getDescription()}): {}", e) when { TcpUtils.isTooManyRedirections(e) -> { return null } TcpUtils.isTimeout(e) -> { return null } TcpUtils.isOutOfEphemeralPorts(e) -> { httpWsClient.close() //make sure to release any resource httpWsClient = ClientBuilder.newClient() TcpUtils.handleEphemeralPortIssue() createInvocationToRealExternalService(httpRequest) } TcpUtils.isStreamClosed(e) || TcpUtils.isEndOfFile(e) -> { log.warn("TCP connection to Real External Service: ${e.cause!!.message}") return null } TcpUtils.isRefusedConnection(e) -> { log.warn("Failed to connect Real External Service with TCP with url ($httpRequest).") return null } else -> throw e } } } private fun handleActualResponse(response: Response?) : ActualResponseInfo? { response?:return null val status = response.status var statusGene = HttpWsResponseParam.getDefaultStatusEnumGene() if (!statusGene.values.contains(status)) statusGene = EnumGene(name = statusGene.name, statusGene.values.plus(status)) val body = response.readEntity(String::class.java) val node = getJsonNodeFromText(body) val responseParam = if(node != null){ getHttpResponse(node, statusGene).apply { setGeneBasedOnString(responseBody, body) } }else{ HttpWsResponseParam(status = statusGene, responseBody = OptionalGene(ACTUAL_RESPONSE_GENE_NAME, StringGene(ACTUAL_RESPONSE_GENE_NAME, value = body))) } (responseParam as HttpWsResponseParam).setStatus(status) return ActualResponseInfo(body, responseParam) } private fun getHttpResponse(node: JsonNode, statusGene: EnumGene<Int>) : ResponseParam{ synchronized(extractedObjectDto){ val found = if (extractedObjectDto.isEmpty()) null else parseJsonNodeAsGene(ACTUAL_RESPONSE_GENE_NAME, node, extractedObjectDto) return if (found != null) HttpWsResponseParam(status= statusGene, responseBody = OptionalGene(ACTUAL_RESPONSE_GENE_NAME, found)) else { val parsed = parseJsonNodeAsGene(ACTUAL_RESPONSE_GENE_NAME, node) HttpWsResponseParam(status= statusGene, responseBody = wrapWithOptionalGene(parsed, true) as OptionalGene) } } } private fun updateExtractedObjectDto(){ synchronized(extractedObjectDto){ val infoDto = rc.getSutInfo()!! val map = ParserDtoUtil.getOrParseDtoWithSutInfo(infoDto) if (map.isNotEmpty()){ map.forEach { (t, u) -> extractedObjectDto.putIfAbsent(t, u) } } } } /** * harvest the existing action [externalServiceAction] with collected actual responses only if the actual response for the action exists, and it is never seeded */ fun harvestExistingExternalActionIfNeverSeeded(externalServiceAction: HttpExternalServiceAction, probability: Double) : Boolean{ if (!seededResponses.contains(externalServiceAction.request.getDescription()) && actualResponses.containsKey(externalServiceAction.request.getDescription())){ return harvestExistingGeneBasedOn(externalServiceAction.response.responseBody, probability) } return false } /** * harvest the existing mocked response with collected actual responses */ fun harvestExistingGeneBasedOn(geneToMutate: Gene, probability: Double) : Boolean{ try { val template = getACopyOfItsActualResponseIfExist(geneToMutate, probability)?.responseBody?:return false val v = ParamUtil.getValueGene(geneToMutate) val t = ParamUtil.getValueGene(template) if (v::class.java == t::class.java){ v.copyValueFrom(t) return true }else if (v is StringGene){ // add template as part of specialization v.addChild(t) v.selectedSpecialization = v.specializationGenes.indexOf(t) return true } LoggingUtil.uniqueWarn(log, "Fail to mutate gene (${geneToMutate::class.java.name}) based on a given gene (${template::class.java.name})") return false }catch (e: Exception){ LoggingUtil.uniqueWarn(log, "Fail to mutate gene based on a given gene and an exception (${e.message}) is thrown") return false } } }
lgpl-3.0
DR-YangLong/spring-boot-kotlin-demo
src/main/kotlin/site/yanglong/promotion/model/Resources.kt
1
1146
package site.yanglong.promotion.model import java.io.Serializable import com.baomidou.mybatisplus.enums.IdType import com.baomidou.mybatisplus.annotations.TableId import com.baomidou.mybatisplus.activerecord.Model import com.baomidou.mybatisplus.annotations.TableField import com.baomidou.mybatisplus.annotations.TableLogic /** * * * * * * @author Dr.YangLong * @since 2017-11-01 */ class Resources : Model<Resources>() { /** * 资源id */ @TableId(value = "id", type = IdType.AUTO) var id: Long? = null /** * 资源标识 */ var uri: String? = null /** * 资源名称 */ var name: String? = null /** * 是否启用 */ @TableField @TableLogic var enable: String? = null override fun pkVal(): Serializable? { return this.id } override fun toString(): String { return "Resources{" + ", id=" + id + ", uri=" + uri + ", name=" + name + ", enable=" + enable + "}" } companion object { private val serialVersionUID = 1L } }
apache-2.0
kangsLee/sh8email-kotlin
app/src/main/kotlin/org/triplepy/sh8email/sh8/utils/LogAppEventUtil.kt
1
653
package org.triplepy.sh8email.sh8.utils import com.crashlytics.android.answers.Answers import com.crashlytics.android.answers.LoginEvent /** * The sh8email-android Project. * ============================== * org.triplepy.sh8email.sh8.utils * ============================== * Created by igangsan on 2016. 9. 1.. */ object LogAppEventUtil { fun eventLogin(method: String, isLoginSucceeded: Boolean, responseCode: Int = 200) { Answers.getInstance().logLogin(LoginEvent() .putMethod(method) .putSuccess(isLoginSucceeded) .putCustomAttribute("responseCode", responseCode) ) } }
apache-2.0
matthieucoisne/LeagueChampions
features/champions/src/androidTest/java/com/leaguechampions/features/champions/presentation/championdetails/ChampionDetailsRobot.kt
1
579
package com.leaguechampions.features.champions.presentation.championdetails import androidx.test.espresso.Espresso.onView import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.espresso.matcher.ViewMatchers.withText import com.leaguechampions.features.champions.R class ChampionDetailsRobot { fun verifyChampionIsDisplayed(championId: String): ChampionDetailsRobot { onView(withId(R.id.tvName)) .check(matches(withText(championId))) return this } }
apache-2.0
ilya-g/kotlinx.collections.immutable
core/commonMain/src/ImmutableMap.kt
1
5417
/* * Copyright 2016-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.txt file. */ package kotlinx.collections.immutable /** * A generic immutable collection that holds pairs of objects (keys and values) and supports efficiently retrieving * the value corresponding to each key. Map keys are unique; the map holds only one value for each key. * Methods in this interface support only read-only access to the immutable map. * * Modification operations are supported through the [PersistentMap] interface. * * Implementors of this interface take responsibility to be immutable. * Once constructed they must contain the same elements in the same order. * * @param K the type of map keys. The map is invariant on its key type, as it * can accept key as a parameter (of [containsKey] for example) and return it in [keys] set. * @param V the type of map values. The map is covariant on its value type. */ public interface ImmutableMap<K, out V>: Map<K, V> { override val keys: ImmutableSet<K> override val values: ImmutableCollection<V> override val entries: ImmutableSet<Map.Entry<K, V>> } /** * A generic persistent collection that holds pairs of objects (keys and values) and supports efficiently retrieving * the value corresponding to each key. Map keys are unique; the map holds only one value for each key. * * Modification operations return new instances of the persistent map with the modification applied. * * @param K the type of map keys. The map is invariant on its key type. * @param V the type of map values. The persistent map is covariant on its value type. */ public interface PersistentMap<K, out V> : ImmutableMap<K, V> { /** * Returns the result of associating the specified [value] with the specified [key] in this map. * * If this map already contains a mapping for the key, the old value is replaced by the specified value. * * @return a new persistent map with the specified [value] associated with the specified [key]; * or this instance if no modifications were made in the result of this operation. */ fun put(key: K, value: @UnsafeVariance V): PersistentMap<K, V> /** * Returns the result of removing the specified [key] and its corresponding value from this map. * * @return a new persistent map with the specified [key] and its corresponding value removed; * or this instance if it contains no mapping for the key. */ fun remove(key: K): PersistentMap<K, V> /** * Returns the result of removing the entry that maps the specified [key] to the specified [value]. * * @return a new persistent map with the entry for the specified [key] and [value] removed; * or this instance if it contains no entry with the specified key and value. */ fun remove(key: K, value: @UnsafeVariance V): PersistentMap<K, V> /** * Returns the result of merging the specified [m] map with this map. * * The effect of this call is equivalent to that of calling `put(k, v)` once for each * mapping from key `k` to value `v` in the specified map. * * @return a new persistent map with keys and values from the specified map [m] associated; * or this instance if no modifications were made in the result of this operation. */ fun putAll(m: Map<out K, @UnsafeVariance V>): PersistentMap<K, V> // m: Iterable<Map.Entry<K, V>> or Map<out K,V> or Iterable<Pair<K, V>> /** * Returns an empty persistent map. */ fun clear(): PersistentMap<K, V> /** * A generic builder of the persistent map. Builder exposes its modification operations through the [MutableMap] interface. * * Builders are reusable, that is [build] method can be called multiple times with modifications between these calls. * However, modifications applied do not affect previously built persistent map instances. * * Builder is backed by the same underlying data structure as the persistent map it was created from. * Thus, [builder] and [build] methods take constant time passing the backing storage to the * new builder and persistent map instances, respectively. * * The builder tracks which nodes in the structure are shared with the persistent map, * and which are owned by it exclusively. It owns the nodes it copied during modification * operations and avoids copying them on subsequent modifications. * * When [build] is called the builder forgets about all owned nodes it had created. */ interface Builder<K, V>: MutableMap<K, V> { /** * Returns a persistent map with the same contents as this builder. * * This method can be called multiple times. * * If operations applied on this builder have caused no modifications: * - on the first call it returns the same persistent map instance this builder was obtained from. * - on subsequent calls it returns the same previously returned persistent map instance. */ fun build(): PersistentMap<K, V> } /** * Returns a new builder with the same contents as this map. * * The builder can be used to efficiently perform multiple modification operations. */ fun builder(): Builder<K, @UnsafeVariance V> }
apache-2.0
matthieucoisne/LeagueChampions
features/champions/src/main/java/com/leaguechampions/features/champions/presentation/championdetails/ChampionDetailsFragment.kt
1
2535
package com.leaguechampions.features.champions.presentation.championdetails import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import com.leaguechampions.features.champions.databinding.FragmentChampionDetailsBinding import com.leaguechampions.libraries.core.data.local.Const import com.leaguechampions.libraries.core.injection.ViewModelFactory import com.leaguechampions.libraries.core.utils.loadChampionImage import dagger.android.support.DaggerFragment import javax.inject.Inject class ChampionDetailsFragment : DaggerFragment() { private lateinit var binding: FragmentChampionDetailsBinding private lateinit var viewModel: ChampionDetailsViewModel @Inject lateinit var viewModelFactory: ViewModelFactory override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding = FragmentChampionDetailsBinding.inflate(inflater, container, false) viewModel = ViewModelProvider(this, viewModelFactory).get(ChampionDetailsViewModel::class.java) viewModel.viewState.observe(viewLifecycleOwner, Observer { render(it) }) val championId = requireArguments().getString(Const.KEY_CHAMPION_ID) viewModel.setChampionId(championId) return binding.root } private fun render(viewState: ChampionDetailsViewModel.ViewState) { when (viewState) { is ChampionDetailsViewModel.ViewState.ShowLoading -> { showToast("Loading") viewState.championDetails?.let { showChampionDetails(it) } } is ChampionDetailsViewModel.ViewState.ShowChampionDetails -> showChampionDetails(viewState.championDetails) is ChampionDetailsViewModel.ViewState.ShowError -> showError(getString(viewState.errorStringId)) } } private fun showChampionDetails(championDetails: ChampionDetailsUiModel) { binding.tvName.text = championDetails.name binding.tvLore.text = championDetails.lore loadChampionImage(binding.ivChampion, championDetails.id, championDetails.version) } private fun showError(message: String) { showToast(message, Toast.LENGTH_LONG) } private fun showToast(message: String, length: Int = Toast.LENGTH_SHORT) { Toast.makeText(requireActivity(), message, length).show() } }
apache-2.0
tangying91/profit
src/main/java/org/profit/server/impl/AbstractNettyServer.kt
1
1773
package org.profit.server.impl import io.netty.channel.Channel import io.netty.channel.ChannelInitializer import io.netty.channel.EventLoopGroup import org.profit.server.NettyConfig import org.profit.server.NettyServer import org.slf4j.LoggerFactory import java.net.InetSocketAddress /** * @author Kyia */ abstract class AbstractNettyServer(override val nettyConfig: NettyConfig, override var channelInitializer: ChannelInitializer<out Channel?>?) : NettyServer { @Throws(Exception::class) override fun startServer(port: Int) { nettyConfig.portNumber = port nettyConfig.socketAddress = InetSocketAddress(port) startServer() } @Throws(Exception::class) override fun startServer(socketAddress: InetSocketAddress?) { nettyConfig.socketAddress = socketAddress startServer() } @Throws(Exception::class) override fun stopServer() { LOG.debug("In stopServer method of class: {}", this.javaClass.name) // TODO move this part to spring. nettyConfig.bossGroup?.shutdownGracefully() nettyConfig.workerGroup?.shutdownGracefully() } protected val bossGroup: EventLoopGroup? protected get() = nettyConfig.bossGroup protected val workerGroup: EventLoopGroup? protected get() = nettyConfig.workerGroup override val socketAddress: InetSocketAddress? get() = nettyConfig.socketAddress override fun toString(): String { return ("NettyServer [socketAddress=" + nettyConfig.socketAddress + ", portNumber=" + nettyConfig.portNumber + "]") } companion object { private val LOG = LoggerFactory.getLogger(AbstractNettyServer::class.java) } }
apache-2.0
KotlinPorts/pooled-client
db-async-common/src/main/kotlin/com/github/mauricio/async/db/pool/PoolConfiguration.kt
2
1485
/* * 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.pool /** * * Defines specific pieces of a pool's behavior. * * @param maxObjects how many objects this pool will hold * @param maxIdle number of milliseconds for which the objects are going to be kept as idle (not in use by clients of the pool) * @param maxQueueSize when there are no more objects, the pool can queue up requests to serve later then there * are objects available, this is the maximum number of enqueued requests * @param validationInterval pools will use this value as the timer period to validate idle objects. */ data class PoolConfiguration( val maxObjects: Int, val maxIdle: Long, val maxQueueSize: Int, val validationInterval: Long = 5000 ) { companion object { val Default = PoolConfiguration(10, 4, 10) } }
apache-2.0
shymmq/librus-client-kotlin
app/src/androidTest/kotlin/com/wabadaba/dziennik/BaseInstrumentedTest.kt
1
1313
package com.wabadaba.dziennik import android.arch.lifecycle.ViewModel import android.support.test.InstrumentationRegistry import com.nhaarman.mockito_kotlin.KStubbing import com.nhaarman.mockito_kotlin.any import com.nhaarman.mockito_kotlin.doReturn import com.nhaarman.mockito_kotlin.mock import com.wabadaba.dziennik.di.ViewModelFactory import com.wabadaba.dziennik.ui.GPServicesChecker import org.junit.Before import org.junit.Rule import org.mockito.Mock import org.mockito.Mockito.`when` abstract class BaseInstrumentedTest { @Suppress("unused") @get:Rule val rule = EspressoDaggerMockRule() @Mock lateinit var viewModelFactory: ViewModelFactory @Mock lateinit var servicesChecker: GPServicesChecker @Before fun setup() { `when`(servicesChecker.check(any())) .doReturn(true) } inline fun <reified T : ViewModel> mockViewModel(stubbing: KStubbing<T>.(T) -> Unit): T { val viewModelMock = mock<T>(stubbing = stubbing) `when`(viewModelFactory.create(T::class.java)).thenReturn(viewModelMock) return viewModelMock } companion object { fun getApp(): MainApplication = InstrumentationRegistry.getInstrumentation() .targetContext .applicationContext as MainApplication } }
gpl-3.0
romasch/yaml-configuration-generator
src/main/kotlin/ch/romasch/gradle/yaml/config/analysis/ScalarKeyChecker.kt
1
732
package ch.romasch.gradle.yaml.config.analysis import org.yaml.snakeyaml.nodes.* class ScalarKeyChecker: YamlCheckVisitor() { override fun visitNodeTuple(tuple: NodeTuple) { checkValidKey(tuple.keyNode) super.visitNodeTuple(tuple) } private fun checkValidKey(node: Node) { if (node is ScalarNode) { val value = node.value if (!value.isNullOrEmpty()) { if (value == "<<") { return } if (value[0].isJavaIdentifierStart() && value.all(Char::isJavaIdentifierPart)) { return } } } throw IllegalStateException("Invalid node" + node) } }
mit
BenjaminSutter/genera
src/main/kotlin/net/bms/genera/init/GeneraTileEntities.kt
1
132
package net.bms.genera.init /** * Created by ben on 4/3/17. */ object GeneraTileEntities { fun initTileEntities() { } }
mit
AsynkronIT/protoactor-kotlin
examples/src/main/kotlin/actor/proto/examples/remotebenchmark/Node2.kt
1
1444
package actor.proto.examples.remotebenchmark import actor.proto.Actor import actor.proto.Context import actor.proto.PID import actor.proto.Started import actor.proto.examples.remotebenchmark.Messages.Pong import actor.proto.examples.remotebenchmark.Messages.Start import actor.proto.examples.remotebenchmark.Messages.getDescriptor import actor.proto.fromProducer import actor.proto.remote.Remote import actor.proto.remote.Serialization.registerFileDescriptor import actor.proto.spawnNamed private val start: Start = Start.newBuilder().build() private val pong: Pong = Pong.newBuilder().build() fun main(args: Array<String>) { registerFileDescriptor(getDescriptor()) Remote.start("127.0.0.1", 12000) spawnNamed(fromProducer { EchoActor() }, "remote") readLine() } class EchoActor : Actor { private var _sender: PID? = null override suspend fun Context.receive(msg: Any) { when (msg) { is Started -> println("Started") is Messages.StartRemote -> { println("Start remote") this@EchoActor._sender = msg.sender respond(start) } is Messages.Ping -> { this@EchoActor._sender?.let { send(it, pong) } ?: println("StartRemote must be received before Ping!") } else -> { println("Unknown $msg") } } } }
apache-2.0
manami-project/manami
manami-gui/src/main/kotlin/io/github/manamiproject/manami/gui/relatedanime/RelatedAnimeView.kt
1
3184
package io.github.manamiproject.manami.gui.relatedanime import io.github.manamiproject.manami.app.lists.Link import io.github.manamiproject.manami.gui.* import io.github.manamiproject.manami.gui.components.animeTable import io.github.manamiproject.manami.gui.components.simpleServiceStart import io.github.manamiproject.manami.gui.events.* import javafx.beans.property.ObjectProperty import javafx.beans.property.SimpleBooleanProperty import javafx.beans.property.SimpleIntegerProperty import javafx.beans.property.SimpleObjectProperty import javafx.collections.FXCollections import javafx.collections.ObservableList import javafx.scene.layout.Priority.ALWAYS import tornadofx.* class RelatedAnimeView : View() { private val manamiAccess: ManamiAccess by inject() private val finishedTasks: SimpleIntegerProperty = SimpleIntegerProperty(0) private val tasks: SimpleIntegerProperty = SimpleIntegerProperty(0) private val isRelatedAnimeProgressIndicatorVisible = SimpleBooleanProperty(false) private val entries: ObjectProperty<ObservableList<BigPicturedAnimeEntry>> = SimpleObjectProperty( FXCollections.observableArrayList() ) init { subscribe<AnimeListRelatedAnimeFoundGuiEvent> { event -> entries.value.add(BigPicturedAnimeEntry(event.anime)) } subscribe<AnimeListRelatedAnimeStatusGuiEvent> { event -> finishedTasks.set(event.finishedChecking) tasks.set(event.toBeChecked) if (event.finishedChecking == 1) { entries.get().clear() } } subscribe<AnimeListRelatedAnimeFinishedGuiEvent> { isRelatedAnimeProgressIndicatorVisible.set(false) } subscribe<AddAnimeListEntryGuiEvent> { event -> val uris = event.entries.map { it.link }.filterIsInstance<Link>().map { it.uri }.toSet() entries.get().removeIf { uris.contains(it.link.uri) } } subscribe<AddWatchListEntryGuiEvent> { event -> val uris = event.entries.map { it.link }.map { it.uri }.toSet() entries.get().removeIf { uris.contains(it.link.uri) } } subscribe<AddIgnoreListEntryGuiEvent> { event -> val uris = event.entries.map { it.link }.map { it.uri }.toSet() entries.get().removeIf { uris.contains(it.link.uri) } } subscribe<FileOpenedGuiEvent> { entries.get().clear() } } override val root = pane { vbox { vgrow = ALWAYS hgrow = ALWAYS fitToParentSize() simpleServiceStart { finishedTasksProperty.bindBidirectional(finishedTasks) numberOfTasksProperty.bindBidirectional(tasks) progressIndicatorVisibleProperty.bindBidirectional(isRelatedAnimeProgressIndicatorVisible) onStart = { entries.get().clear() manamiAccess.findRelatedAnimeForAnimeList() } } animeTable<BigPicturedAnimeEntry> { manamiApp = manamiAccess items = entries } } } }
agpl-3.0
ajalt/clikt
clikt/src/commonTest/kotlin/com/github/ajalt/clikt/sources/ChainedValueSourceTest.kt
1
1087
package com.github.ajalt.clikt.sources import com.github.ajalt.clikt.core.context import com.github.ajalt.clikt.parameters.options.option import com.github.ajalt.clikt.testing.TestCommand import com.github.ajalt.clikt.testing.TestSource import com.github.ajalt.clikt.testing.parse import io.kotest.matchers.shouldBe import kotlin.js.JsName import kotlin.test.Test class ChainedValueSourceTest { @Test @JsName("reads_from_the_first_available_value") fun `reads from the first available value`() { val sources = arrayOf( TestSource(), TestSource("foo" to "bar"), TestSource("foo" to "baz") ) class C : TestCommand() { init { context { valueSources(*sources) } } val foo by option() override fun run_() { foo shouldBe "bar" } } C().parse("") sources[0].assert(read = true) sources[1].assert(read = true) sources[2].assert(read = false) } }
apache-2.0
box/box-android-share-sdk
box-share-sdk/src/test/java/com/box/androidsdk/share/vm/SelectRoleVMTest.kt
1
3284
package com.box.androidsdk.share.vm import androidx.arch.core.executor.testing.InstantTaskExecutorRule import com.box.androidsdk.content.models.BoxCollaboration import com.nhaarman.mockitokotlin2.mock import junit.framework.Assert.assertEquals import junit.framework.Assert.assertNull import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.rules.TestRule class SelectRoleVMTest { @get:Rule var rule: TestRule = InstantTaskExecutorRule() private lateinit var selectRoleShareVM: SelectRoleShareVM private val mockRolesList: List<BoxCollaboration.Role> = mock() private val mockAllowOwnerRole = true private val mockRole = BoxCollaboration.Role.EDITOR private val mockAllowRemove = true private val mockCollaboration: BoxCollaboration = mock() @Before fun setup() { selectRoleShareVM = SelectRoleShareVM() } @Test fun `test set selectedRole update the live data correctly`() { assertNull(selectRoleShareVM.selectedRole.value) selectRoleShareVM.setSelectedRole(mockRole) assertEquals(mockRole, selectRoleShareVM.selectedRole.value) } @Test fun `test set allow owner role update the variable correctly`() { assertEquals(false, selectRoleShareVM.isOwnerRoleAllowed) selectRoleShareVM.setAllowOwnerRole(mockAllowOwnerRole) assertEquals(mockAllowOwnerRole, selectRoleShareVM.isOwnerRoleAllowed) } @Test fun `test set allow remove update the variable correctly`() { assertEquals(false, selectRoleShareVM.isRemoveAllowed) selectRoleShareVM.setAllowRemove(mockAllowRemove) assertEquals(mockAllowRemove, selectRoleShareVM.isRemoveAllowed) } @Test fun `test set roles update the variable correctly`() { assertEquals(0, selectRoleShareVM.roles.size) selectRoleShareVM.roles = mockRolesList assertEquals(mockRolesList, selectRoleShareVM.roles) } @Test fun `test set collaboration update the variable correctly`() { assertNull(selectRoleShareVM.collaboration) selectRoleShareVM.collaboration = mockCollaboration assertEquals(mockCollaboration, selectRoleShareVM.collaboration) } @Test fun `test set send invitation enabled update the variable correctly`() { assertEquals(false, selectRoleShareVM.isSendInvitationEnabled.value) selectRoleShareVM.setSendInvitationEnabled(true) assertEquals(true, selectRoleShareVM.isSendInvitationEnabled.value) } @Test fun `test set show send update the variable correctly`() { assertEquals(true, selectRoleShareVM.isShowSend.value) selectRoleShareVM.setShowSend(false) assertEquals(false, selectRoleShareVM.isShowSend.value) } @Test fun `test set remove selected update the variable correctly`() { assertEquals(false, selectRoleShareVM.isRemoveSelected) selectRoleShareVM.isRemoveSelected = true assertEquals(true, selectRoleShareVM.isRemoveSelected) } @Test fun `test set name update the variable correctly`() { assertEquals("", selectRoleShareVM.name) selectRoleShareVM.name = "user" assertEquals("user", selectRoleShareVM.name) } }
apache-2.0
pardom/navigator
navigator/src/main/kotlin/navigator/route/AbsRoute.kt
1
508
package navigator.route import kotlinx.coroutines.experimental.CompletableDeferred import navigator.Navigator import navigator.Overlay import navigator.Route abstract class AbsRoute<T> : Route<T> { override var navigator: Navigator? = null override val overlayEntries: MutableList<Overlay.Entry> = mutableListOf() override val popped: CompletableDeferred<Any?> = CompletableDeferred() override val currentResult: T? = null override val willHandlePopInternally: Boolean = false }
apache-2.0
weisterjie/FamilyLedger
app/src/main/java/ycj/com/familyledger/ui/KHomeActivity.kt
1
9225
package ycj.com.familyledger.ui import android.content.Intent import android.os.SystemClock import android.support.design.widget.FloatingActionButton import android.support.v7.widget.DefaultItemAnimator import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.Gravity import android.view.View import android.widget.TextView import org.jetbrains.anko.* import org.jetbrains.anko.design.floatingActionButton import org.jetbrains.anko.recyclerview.v7.recyclerView import ycj.com.familyledger.Consts import ycj.com.familyledger.R import ycj.com.familyledger.adapter.KHomeAdapter import ycj.com.familyledger.bean.BaseResponse import ycj.com.familyledger.bean.LedgerBean import ycj.com.familyledger.bean.PageResult import ycj.com.familyledger.http.HttpUtils import ycj.com.familyledger.impl.BaseCallBack import ycj.com.familyledger.impl.IGetLedgerList import ycj.com.familyledger.utils.RecyclerViewItemDiv import ycj.com.familyledger.utils.SPUtils import ycj.com.familyledger.view.EdxDialog import java.util.* class KHomeActivity : KBaseActivity(), KHomeAdapter.ItemClickListener, EdxDialog.DataCallBack, View.OnClickListener, IGetLedgerList { private var trigleCancel: Long = 0 private var selfData: Boolean = true private var lView: RecyclerView? = null private var data: ArrayList<LedgerBean> = ArrayList() private var fBtn: FloatingActionButton? = null private var mAdapter: KHomeAdapter? = null override fun initialize() { showLoading() HttpUtils.getInstance().getLedgerList(0, 1, 1000, this) } override fun initListener() { leftLayout?.setOnClickListener(this) splitLayout?.setOnClickListener(this) mAdapter?.setOnItemClickListener(this) fBtn?.setOnClickListener(this) lView?.setOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) if (lView?.scrollState == RecyclerView.SCROLL_STATE_DRAGGING) { if (dy > 0) { fBtn?.hide() } else { fBtn?.show() } } } override fun onScrollStateChanged(recyclerView: RecyclerView?, newState: Int) { super.onScrollStateChanged(recyclerView, newState) android.util.Log.i("ycj ScrollChanged", "" + newState) //==1,显示 if (newState == RecyclerView.SCROLL_STATE_IDLE) { fBtn?.show() } } }) } //输入框返回 override fun callBack(dates: String, cashs: String) { val userId = SPUtils.getInstance().getLong(Consts.SP_USER_ID) HttpUtils.getInstance().addLedger(userId, dates, cashs, object : BaseCallBack<String> { override fun onSuccess(data: BaseResponse<String>) { hideLoading() if (data.result == 1) { toast(data.data) initialize() } else { toast(data.error.message) } } override fun onFail(msg: String) { toast(msg) } }) } override fun onItemClickListener(position: Int) { go2Detail(position) } override fun onItemLongClickListener(position: Int) { showTips(getString(R.string.sure_delete), object : OnTipsCallBack { override fun positiveClick() { HttpUtils.getInstance().deleteLedger(data[position].id!!, object : BaseCallBack<String> { override fun onSuccess(data: BaseResponse<String>) { if (data.result == 1) { toast(getString(R.string.success_delete)) [email protected](position) mAdapter?.notifyDataSetChanged() } else { toast(data.error.message) } } override fun onFail(msg: String) { toast(getString(R.string.fail_delete)) } }) } }) } override fun onClick(v: android.view.View?) { when (v?.id) { R.id.layout_left_title_home -> { go2Calculate() } R.id.layout_split -> { showLoading() val userId = SPUtils.getInstance().getLong(Consts.SP_USER_ID) HttpUtils.getInstance().getLedgerList(if (selfData) userId else 0, 1, 1000, this) selfData = !selfData } R.id.btn_home_add -> EdxDialog.Companion.create() .showEdxDialog("请输入信息", this@KHomeActivity, this@KHomeActivity) } } override fun onSuccess(pages: PageResult<LedgerBean>) { hideLoading() mAdapter?.setDatas(pages.list) } override fun onFail(msg: String) { hideLoading() mAdapter?.clearData() toast("获取失败") } private fun go2Detail(position: Int) { val intent = android.content.Intent(KHomeActivity@ this, KLedgerDetailActivity::class.java) intent.putExtra(Consts.DATA_ID, position) intent.putExtra(Consts.DATA_BEAN, data[position]) startActivityForResult(intent, 100) } private fun go2Calculate() { val intent = android.content.Intent(KHomeActivity@ this, KCalculateActivity::class.java) intent.putExtra(Consts.LIST_DATA, data) startActivity(intent) } private var splitLayout: TextView? = null private var leftLayout: TextView? = null override fun initView() { relativeLayout { lparams(height = matchParent, width = matchParent) relativeLayout { id = R.id.layout_title backgroundResource = R.color.color_title_bar textView("Ledger") { textSize = resources.getDimension(R.dimen.title_size) textColor = resources.getColor(R.color.white) }.lparams(height = wrapContent, width = wrapContent) { centerInParent() } splitLayout = textView("筛选") { id = R.id.layout_split gravity = Gravity.CENTER textColor = resources.getColor(R.color.white) backgroundResource = R.drawable.bg_btn }.lparams(width = dip(48), height = matchParent) { centerInParent() alignParentRight() } leftLayout = textView("结账") { id = R.id.layout_left_title_home gravity = Gravity.CENTER textColor = resources.getColor(R.color.white) backgroundResource = R.drawable.bg_btn }.lparams(width = dip(48), height = matchParent) }.lparams(height = dip(48), width = matchParent) lView = recyclerView { id = R.id.list_view_home }.lparams(width = matchParent, height = matchParent) { below(R.id.layout_title) } fBtn = floatingActionButton { id = R.id.btn_home_add imageResource = android.R.drawable.ic_menu_add }.lparams(width = wrapContent, height = wrapContent) { alignParentRight() alignParentBottom() bottomMargin = dip(20) rightMargin = dip(20) } } mAdapter = KHomeAdapter(data, this) //分割线 lView?.addItemDecoration(RecyclerViewItemDiv(this@KHomeActivity, LinearLayoutManager.VERTICAL)) lView?.adapter = mAdapter lView?.layoutManager = LinearLayoutManager(this@KHomeActivity) //滑动监听 lView?.overScrollMode = android.view.View.OVER_SCROLL_NEVER lView?.itemAnimator = DefaultItemAnimator() as RecyclerView.ItemAnimator?//设置Item增加、移除动画 // val callBack = RItemTouchHelper(mAdapter!!) // val helpers = ItemTouchHelper(callBack) // helpers.attachToRecyclerView(lView) } //按后退键时 override fun onBackPressed() { toastExtrance() // “提示再按一次可退出..” } //双击退出提醒 fun toastExtrance() { val uptimeMillis = SystemClock.uptimeMillis() if (uptimeMillis - trigleCancel > 2000) { trigleCancel = uptimeMillis toast(getString(R.string.note_exit)) } else { finish() } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (resultCode == Consts.ACTIVITY_RESULT_REFRESH) { initialize() } } }
apache-2.0
MichaelRocks/lightsaber
processor/src/main/java/io/michaelrocks/lightsaber/processor/generation/PackageInvadersGenerator.kt
1
1415
/* * Copyright 2019 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.generation import io.michaelrocks.grip.ClassRegistry import io.michaelrocks.lightsaber.processor.generation.model.GenerationContext import io.michaelrocks.lightsaber.processor.logging.getLogger class PackageInvadersGenerator( private val classProducer: ClassProducer, private val classRegistry: ClassRegistry ) { private val logger = getLogger() fun generate(generationContext: GenerationContext) { generationContext.packageInvaders.forEach { packageInvader -> logger.debug("Generating package invader {}", packageInvader.type) val generator = PackageInvaderClassGenerator(classRegistry, packageInvader) val classData = generator.generate() classProducer.produceClass(packageInvader.type.internalName, classData) } } }
apache-2.0
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/dao/servers/moduleconfigs/ReactionOption.kt
1
704
package net.perfectdreams.loritta.morenitta.dao.servers.moduleconfigs import net.perfectdreams.loritta.morenitta.tables.servers.moduleconfigs.ReactionOptions import org.jetbrains.exposed.dao.LongEntity import org.jetbrains.exposed.dao.LongEntityClass import org.jetbrains.exposed.dao.id.EntityID class ReactionOption(id: EntityID<Long>) : LongEntity(id) { companion object : LongEntityClass<ReactionOption>(ReactionOptions) var guildId by ReactionOptions.guildId var textChannelId by ReactionOptions.textChannelId var messageId by ReactionOptions.messageId var reaction by ReactionOptions.reaction var roleIds by ReactionOptions.roleIds var locks by ReactionOptions.locks }
agpl-3.0
owntracks/android
project/app/src/main/java/org/owntracks/android/ui/preferences/load/LoadActivityModule.kt
1
365
package org.owntracks.android.ui.preferences.load import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.android.components.ActivityComponent @InstallIn(ActivityComponent::class) @Module abstract class LoadActivityModule { @Binds abstract fun bindViewModel(viewModel: LoadViewModel): LoadMvvm.ViewModel<LoadMvvm.View>? }
epl-1.0
rectangle-dbmi/Realtime-Port-Authority
app/src/main/java/rectangledbmi/com/pittsburghrealtimetracker/patterns/PatternSelection.kt
1
2490
package rectangledbmi.com.pittsburghrealtimetracker.patterns import com.google.android.gms.maps.model.LatLng import com.rectanglel.patstatic.patterns.polylines.PolylineView import com.rectanglel.patstatic.patterns.response.Ptr /** * * Data Transfer Object that transfers meta info for [com.google.android.gms.maps.model.Polyline] * creation from the [PatternViewModel] * to the [PolylineView]. * * * The contract of this class should be that if [.isSelected] is `false`, [.getPatterns] * should be `null. Otherwise, it will always not be null. * * * Created by epicstar on 7/30/16. * @since 78 * @author Jeremy Jao */ data class PatternSelection /** * * It is recommended to use this constructor when you want to show the polyline of a route number. * Otherwise, it breaks the contract of this data-transfer object. * * * Creates a data-transfer object for [com.google.android.gms.maps.model.Polyline] creation. * * @param patterns a list of patterns for polyline metadata * @param isSelected whether or not the route is selected * @param routeNumber the route number of the polyline * @param routeColor the route color of the polyline */ ( /** * * The List of patterns. Each pattern should represent some metadata * [com.google.android.gms.maps.model.Polyline]s for a selected route. * * * This should always be null if [.isSelected] is `false`. Otherwise, it should almost * always not be `null`. * @return a list of Patterns for [com.google.android.gms.maps.model.Polyline] creation */ val patterns: List<Ptr?>?, /** * * Tells the [PolylineView] whether or not to show the * [com.google.android.gms.maps.model.Polyline]s for a route. * * * If this is `false`, [.getPatterns] should always be null. * @return whether or not to show the [com.google.android.gms.maps.model.Polyline]. */ val isSelected: Boolean, /** * * @return the route number as part of polyline metadata. */ val routeNumber: String, /** * * @return the route's color */ val routeColor: Int) { /** * [com.google.android.gms.maps.model.Polyline] creation needs a list of latlngs to create. * A route has a list of patterns per outbound and inbound route. */ var latLngs: List<List<LatLng>>? = null }
gpl-3.0
cketti/okhttp
okhttp/src/test/java/okhttp3/internal/ws/MessageDeflaterInflaterTest.kt
1
4716
/* * Copyright (C) 2020 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 * * 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 okhttp3.internal.ws import java.io.EOFException import okhttp3.TestUtil.fragmentBuffer import okio.Buffer import okio.ByteString import okio.ByteString.Companion.decodeHex import okio.ByteString.Companion.encodeUtf8 import org.assertj.core.api.Assertions.assertThat import org.junit.Assert.fail import org.junit.Test internal class MessageDeflaterInflaterTest { @Test fun `inflate golden value`() { val inflater = MessageInflater(false) val message = "f248cdc9c957c8cc4bcb492cc9cccf530400".decodeHex() assertThat(inflater.inflate(message)).isEqualTo("Hello inflation!".encodeUtf8()) } @Test fun `deflate golden value`() { val deflater = MessageDeflater(false) val deflated = deflater.deflate("Hello deflate!".encodeUtf8()) assertThat(deflated.hex()).isEqualTo("f248cdc9c95748494dcb492c49550400") } @Test fun `inflate deflate`() { val deflater = MessageDeflater(false) val inflater = MessageInflater(false) val goldenValue = "Hello deflate!".repeat(100).encodeUtf8() val deflated = deflater.deflate(goldenValue) assertThat(deflated.size).isLessThan(goldenValue.size) val inflated = inflater.inflate(deflated) assertThat(inflated).isEqualTo(goldenValue) } @Test fun `inflate deflate empty message`() { val deflater = MessageDeflater(false) val inflater = MessageInflater(false) val goldenValue = "".encodeUtf8() val deflated = deflater.deflate(goldenValue) assertThat(deflated).isEqualTo("00".decodeHex()) val inflated = inflater.inflate(deflated) assertThat(inflated).isEqualTo(goldenValue) } @Test fun `inflate deflate with context takeover`() { val deflater = MessageDeflater(false) val inflater = MessageInflater(false) val goldenValue1 = "Hello deflate!".repeat(100).encodeUtf8() val deflatedValue1 = deflater.deflate(goldenValue1) assertThat(inflater.inflate(deflatedValue1)).isEqualTo(goldenValue1) val goldenValue2 = "Hello deflate?".repeat(100).encodeUtf8() val deflatedValue2 = deflater.deflate(goldenValue2) assertThat(inflater.inflate(deflatedValue2)).isEqualTo(goldenValue2) assertThat(deflatedValue2.size).isLessThan(deflatedValue1.size) } @Test fun `inflate deflate with no context takeover`() { val deflater = MessageDeflater(true) val inflater = MessageInflater(true) val goldenValue1 = "Hello deflate!".repeat(100).encodeUtf8() val deflatedValue1 = deflater.deflate(goldenValue1) assertThat(inflater.inflate(deflatedValue1)).isEqualTo(goldenValue1) val goldenValue2 = "Hello deflate!".repeat(100).encodeUtf8() val deflatedValue2 = deflater.deflate(goldenValue2) assertThat(inflater.inflate(deflatedValue2)).isEqualTo(goldenValue2) assertThat(deflatedValue2).isEqualTo(deflatedValue1) } @Test fun `deflate after close`() { val deflater = MessageDeflater(true) deflater.close() try { deflater.deflate("Hello deflate!".encodeUtf8()) fail() } catch (expected: Exception) { } } @Test fun `inflate after close`() { val inflater = MessageInflater(false) inflater.close() try { inflater.inflate("f240e30300".decodeHex()) fail() } catch (expected: Exception) { } } /** * Test for an [EOFException] caused by mishandling of fragmented buffers in web socket * compression. https://github.com/square/okhttp/issues/5965 */ @Test fun `inflate golden value in buffer that has been fragmented`() { val inflater = MessageInflater(false) val buffer = fragmentBuffer(Buffer().write("f248cdc9c957c8cc4bcb492cc9cccf530400".decodeHex())) inflater.inflate(buffer) assertThat(buffer.readUtf8()).isEqualTo("Hello inflation!") } private fun MessageDeflater.deflate(byteString: ByteString): ByteString { val buffer = Buffer() buffer.write(byteString) deflate(buffer) return buffer.readByteString() } private fun MessageInflater.inflate(byteString: ByteString): ByteString { val buffer = Buffer() buffer.write(byteString) inflate(buffer) return buffer.readByteString() } }
apache-2.0
bassph/bassph-app-android
app/src/main/java/org/projectbass/bass/inject/StoreModule.kt
1
1017
package org.projectbass.bass.inject import org.projectbass.bass.flux.Dispatcher import org.projectbass.bass.flux.store.DataCollectionStore import org.projectbass.bass.flux.store.LocationPointsStore import dagger.Module import dagger.Provides import java.util.* /** * Dagger module to provide flux components. This class will contain the Dispatcher, * ActionCreators, and Stores. * @author Gian Darren Aquino */ @Module internal class StoreModule { @PerApplication @Provides fun providesDispatcher(dataCollectionStore: DataCollectionStore, locationPointsStore: LocationPointsStore): Dispatcher { return Dispatcher(Arrays.asList( dataCollectionStore, locationPointsStore)) } @PerApplication @Provides fun providesDataCollectionStore(): DataCollectionStore { return DataCollectionStore() } @PerApplication @Provides fun providesLocationPointsStore(): LocationPointsStore { return LocationPointsStore() } }
agpl-3.0
STUDIO-apps/GeoShare_Android
mobile/src/main/java/uk/co/appsbystudio/geoshare/authentication/forgotpassword/ForgotPasswordInteractorImpl.kt
1
759
package uk.co.appsbystudio.geoshare.authentication.forgotpassword import android.text.TextUtils import com.google.android.gms.tasks.Task import com.google.firebase.auth.FirebaseAuth class ForgotPasswordInteractorImpl: ForgotPasswordInteractor { override fun recover(email: String, listener: ForgotPasswordInteractor.OnRecoverFinishedListener) { if (TextUtils.isEmpty(email)) { listener.onEmailError() return } FirebaseAuth.getInstance().sendPasswordResetEmail(email).addOnCompleteListener { it: Task<Void> -> if (it.isSuccessful) { listener.onSuccess() } else { listener.onFailure(it.exception?.message.toString()) } } } }
apache-2.0
kotlintest/kotlintest
kotest-extensions/src/jvmTest/kotlin/com/sksamuel/kt/extensions/system/SystemEnvironmentExtensionTest.kt
1
2875
package com.sksamuel.kt.extensions.system import io.kotest.core.listeners.TestListener import io.kotest.core.test.TestCase import io.kotest.core.test.TestResult import io.kotest.core.spec.Spec import io.kotest.core.spec.style.FreeSpec import io.kotest.core.spec.style.FreeSpecScope import io.kotest.core.spec.style.WordSpec import io.kotest.extensions.system.OverrideMode import io.kotest.extensions.system.SystemEnvironmentTestListener import io.kotest.extensions.system.withEnvironment import io.kotest.inspectors.forAll import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe import io.mockk.every import io.mockk.mockk import kotlin.reflect.KClass class SystemEnvironmentExtensionTest : FreeSpec() { private val key = "SystemEnvironmentExtensionTestFoo" private val value = "SystemEnvironmentExtensionTestBar" private val mode: OverrideMode = mockk { every { override(any(), any()) } answers { firstArg<Map<String, String>>().plus(secondArg<Map<String, String>>()).toMutableMap() } } init { "Should set environment to specific map" - { executeOnAllEnvironmentOverloads { System.getenv(key) shouldBe value } } "Should return original environment to its place after execution" - { val before = System.getenv().toMap() executeOnAllEnvironmentOverloads { System.getenv() shouldNotBe before } System.getenv() shouldBe before } "Should return the computed value" - { val results = executeOnAllEnvironmentOverloads { "RETURNED" } results.forAll { it shouldBe "RETURNED" } } } private suspend fun <T> FreeSpecScope.executeOnAllEnvironmentOverloads(block: suspend () -> T): List<T> { val results = mutableListOf<T>() "String String overload" { results += withEnvironment(key, value, mode) { block() } } "Pair overload" { results += withEnvironment(key to value, mode) { block() } } "Map overload" { results += withEnvironment(mapOf(key to value), mode) { block() } } return results } } class SystemEnvironmentTestListenerTest : WordSpec() { override fun listeners() = listOf(SystemEnvironmentTestListener("mop", "dop", mode = OverrideMode.SetOrOverride), listener) private val listener = object : TestListener { override suspend fun prepareSpec(kclass: KClass<out Spec>) { System.getenv("mop") shouldBe null } override suspend fun finalizeSpec(kclass: KClass<out Spec>, results: Map<TestCase, TestResult>) { System.getenv("mop") shouldBe null } } init { "sys environment extension" should { "set environment variable" { System.getenv("mop") shouldBe "dop" } } } }
apache-2.0
kotlintest/kotlintest
kotest-core/src/jvmMain/kotlin/io/kotest/core/spec/tempfile.kt
1
283
package io.kotest.core.spec import java.io.File import java.nio.file.Files fun TestConfiguration.tempfile(prefix: String? = null, suffix: String? = ".tmp"): File { val file = Files.createTempFile(prefix, suffix).toFile() afterSpec { file.delete() } return file }
apache-2.0
cliffano/swaggy-jenkins
clients/kotlin-spring/generated/src/main/kotlin/org/openapitools/model/BranchImplpermissions.kt
1
1272
package org.openapitools.model import java.util.Objects import com.fasterxml.jackson.annotation.JsonProperty import javax.validation.constraints.DecimalMax import javax.validation.constraints.DecimalMin import javax.validation.constraints.Email import javax.validation.constraints.Max import javax.validation.constraints.Min import javax.validation.constraints.NotNull import javax.validation.constraints.Pattern import javax.validation.constraints.Size import javax.validation.Valid import io.swagger.v3.oas.annotations.media.Schema /** * * @param create * @param read * @param start * @param stop * @param propertyClass */ data class BranchImplpermissions( @Schema(example = "null", description = "") @field:JsonProperty("create") val create: kotlin.Boolean? = null, @Schema(example = "null", description = "") @field:JsonProperty("read") val read: kotlin.Boolean? = null, @Schema(example = "null", description = "") @field:JsonProperty("start") val start: kotlin.Boolean? = null, @Schema(example = "null", description = "") @field:JsonProperty("stop") val stop: kotlin.Boolean? = null, @Schema(example = "null", description = "") @field:JsonProperty("_class") val propertyClass: kotlin.String? = null ) { }
mit
Bombe/Sone
src/main/kotlin/net/pterodactylus/sone/text/SoneTextParser.kt
1
7803
package net.pterodactylus.sone.text import freenet.keys.* import net.pterodactylus.sone.data.* import net.pterodactylus.sone.data.impl.* import net.pterodactylus.sone.database.* import net.pterodactylus.sone.text.LinkType.* import net.pterodactylus.sone.text.LinkType.USK import net.pterodactylus.sone.utils.* import org.bitpedia.util.* import java.net.* import javax.inject.* /** * [Parser] implementation that can recognize Freenet URIs. */ class SoneTextParser @Inject constructor(private val soneProvider: SoneProvider?, private val postProvider: PostProvider?) { fun parse(source: String, context: SoneTextParserContext?) = source.split("\n") .dropWhile { it.trim() == "" } .dropLastWhile { it.trim() == "" } .mergeMultipleEmptyLines() .flatMap { splitLineIntoParts(it, context) } .removeEmptyPlainTextParts() .mergeAdjacentPlainTextParts() private fun splitLineIntoParts(line: String, context: SoneTextParserContext?) = generateSequence(PlainTextPart("") as Part to line) { remainder -> if (remainder.second == "") null else LinkType.values() .mapNotNull { it.findNext(remainder.second) } .minBy { it.position } .let { when { it == null -> PlainTextPart(remainder.second) to "" it.position == 0 -> it.toPart(context) to it.remainder else -> PlainTextPart(remainder.second.substring(0, it.position)) to (it.link + it.remainder) } } }.map { it.first }.toList() private val NextLink.linkWithoutBacklink: String get() { val backlink = link.indexOf("/../") val query = link.indexOf("?") return if ((backlink > -1) && ((query == -1) || (query > -1) && (backlink < query))) link.substring(0, backlink) else link } private fun NextLink.toPart(context: SoneTextParserContext?) = when (linkType) { KSK, CHK -> try { FreenetURI(linkWithoutBacklink).let { freenetUri -> FreenetLinkPart( linkWithoutBacklink, freenetUri.allMetaStrings?.lastOrNull { it != "" } ?: freenetUri.docName ?: linkWithoutBacklink.substring(0, 9), linkWithoutBacklink.split('?').first() ) } } catch (e: MalformedURLException) { PlainTextPart(linkWithoutBacklink) } SSK, USK -> try { FreenetURI(linkWithoutBacklink).let { uri -> uri.allMetaStrings ?.takeIf { (it.size > 1) || ((it.size == 1) && (it.single() != "")) } ?.lastOrNull() ?: uri.docName ?: "${uri.keyType}@${uri.routingKey.asFreenetBase64}" }.let { FreenetLinkPart(linkWithoutBacklink.removeSuffix("/"), it, trusted = context?.routingKey?.contentEquals(FreenetURI(linkWithoutBacklink).routingKey) == true) } } catch (e: MalformedURLException) { PlainTextPart(linkWithoutBacklink) } SONE -> link.substring(7).let { SonePart(soneProvider?.getSone(it) ?: IdOnlySone(it)) } POST -> postProvider?.getPost(link.substring(7))?.let { PostPart(it) } ?: PlainTextPart(link) FREEMAIL -> link.indexOf('@').let { atSign -> link.substring(atSign + 1, link.length - 9).let { freemailId -> FreemailPart(link.substring(0, atSign), freemailId, freemailId.decodedId) } } HTTP, HTTPS -> LinkPart(link, link .withoutProtocol .withoutWwwPrefix .withoutUrlParameters .withoutMiddlePathComponents .withoutTrailingSlash) } } private fun List<String>.mergeMultipleEmptyLines() = fold(emptyList<String>()) { previous, current -> if (previous.isEmpty()) { previous + current } else { if ((previous.last() == "\n") && (current == "")) { previous } else { previous + ("\n" + current) } } } private fun List<Part>.mergeAdjacentPlainTextParts() = fold(emptyList<Part>()) { parts, part -> if ((parts.lastOrNull() is PlainTextPart) && (part is PlainTextPart)) { parts.dropLast(1) + PlainTextPart(parts.last().text + part.text) } else { parts + part } } private fun List<Part>.removeEmptyPlainTextParts() = filterNot { it == PlainTextPart("") } private val String.decodedId: String get() = Base32.decode(this).asFreenetBase64 private val String.withoutProtocol get() = substring(indexOf("//") + 2) private val String.withoutUrlParameters get() = split('?').first() private val String.withoutWwwPrefix get() = split("/") .replaceFirst { it.split(".").dropWhile { it == "www" }.joinToString(".") } .joinToString("/") private fun <T> List<T>.replaceFirst(replacement: (T) -> T) = mapIndexed { index, element -> if (index == 0) replacement(element) else element } private val String.withoutMiddlePathComponents get() = split("/").let { if (it.size > 2) { "${it.first()}/…/${it.last()}" } else { it.joinToString("/") } } private val String.withoutTrailingSlash get() = if (endsWith("/")) substring(0, length - 1) else this private val SoneTextParserContext.routingKey: ByteArray? get() = postingSone?.routingKey private val Sone.routingKey: ByteArray get() = id.fromFreenetBase64 private enum class LinkType(private val scheme: String, private val freenetLink: Boolean) { KSK("KSK@", true), CHK("CHK@", true), SSK("SSK@", true), USK("USK@", true), HTTP("http://", false), HTTPS("https://", false), SONE("sone://", false) { override fun validateLinkLength(length: Int) = length.takeIf { it == 50 } }, POST("post://", false), FREEMAIL("", true) { override fun findNext(line: String): NextLink? { val nextFreemailSuffix = line.indexOf(".freemail").takeIf { it >= 54 } ?: return null if (line[nextFreemailSuffix - 53] != '@') return null if (!line.substring(nextFreemailSuffix - 52, nextFreemailSuffix).matches(Regex("^[a-z2-7]*\$"))) return null val firstCharacterIndex = generateSequence(nextFreemailSuffix - 53) { it.minus(1).takeIf { (it >= 0) && line[it].validLocalPart } }.lastOrNull() ?: return null return NextLink(firstCharacterIndex, this, line.substring(firstCharacterIndex, nextFreemailSuffix + 9), line.substring(nextFreemailSuffix + 9)) } private val Char.validLocalPart get() = (this in ('A'..'Z')) || (this in ('a'..'z')) || (this in ('0'..'9')) || (this == '-') || (this == '_') || (this == '.') }; open fun findNext(line: String): NextLink? { val nextLinkPosition = line.indexOf(scheme).takeIf { it != -1 } ?: return null val endOfLink = line.substring(nextLinkPosition).findEndOfLink().validate() ?: return null val link = line.substring(nextLinkPosition, nextLinkPosition + endOfLink) val realNextLinkPosition = if (freenetLink && line.substring(0, nextLinkPosition).endsWith("freenet:")) nextLinkPosition - 8 else nextLinkPosition return NextLink(realNextLinkPosition, this, link, line.substring(nextLinkPosition + endOfLink)) } private fun String.findEndOfLink() = substring(0, whitespace.find(this)?.range?.start ?: length) .dropLastWhile(::isPunctuation) .upToFirstUnmatchedParen() private fun Int.validate() = validateLinkLength(this) protected open fun validateLinkLength(length: Int) = length.takeIf { it > scheme.length } private fun String.upToFirstUnmatchedParen() = foldIndexed(Pair<Int, Int?>(0, null)) { index, (openParens, firstUnmatchedParen), currentChar -> when (currentChar) { '(' -> (openParens + 1) to firstUnmatchedParen ')' -> ((openParens - 1) to (if (openParens == 0) (firstUnmatchedParen ?: index) else firstUnmatchedParen)) else -> openParens to firstUnmatchedParen } }.second ?: length } private val punctuationChars = listOf('.', ',', '?', '!') private fun isPunctuation(char: Char) = char in punctuationChars private val whitespace = Regex("[\\u000a\u0020\u00a0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u200c\u200d\u202f\u205f\u2060\u2800\u3000]") private data class NextLink(val position: Int, val linkType: LinkType, val link: String, val remainder: String)
gpl-3.0
Bombe/Sone
src/test/kotlin/net/pterodactylus/sone/web/ajax/CreatePostAjaxPageTest.kt
1
3323
package net.pterodactylus.sone.web.ajax import net.pterodactylus.sone.data.Post import net.pterodactylus.sone.data.Sone import net.pterodactylus.sone.test.getInstance import net.pterodactylus.sone.test.mock import net.pterodactylus.sone.test.whenever import net.pterodactylus.sone.utils.asOptional import net.pterodactylus.sone.web.baseInjector import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.equalTo import org.hamcrest.Matchers.notNullValue import org.hamcrest.Matchers.nullValue import org.junit.Test /** * Unit test for [CreatePostAjaxPage]. */ class CreatePostAjaxPageTest : JsonPageTest("createPost.ajax", pageSupplier = ::CreatePostAjaxPage) { @Test fun `missing text parameter returns error`() { assertThatJsonFailed("text-required") } @Test fun `empty text returns error`() { addRequestParameter("text", "") assertThatJsonFailed("text-required") } @Test fun `whitespace-only text returns error`() { addRequestParameter("text", " ") assertThatJsonFailed("text-required") } @Test fun `request with valid data creates post`() { addRequestParameter("text", "test") val post = createPost() whenever(core.createPost(currentSone, null, "test")).thenReturn(post) assertThatJsonIsSuccessful() assertThat(json["postId"]?.asText(), equalTo("id")) assertThat(json["sone"]?.asText(), equalTo(currentSone.id)) assertThat(json["recipient"], nullValue()) } @Test fun `request with invalid recipient creates post without recipient`() { addRequestParameter("text", "test") addRequestParameter("recipient", "invalid") val post = createPost() whenever(core.createPost(currentSone, null, "test")).thenReturn(post) assertThatJsonIsSuccessful() assertThat(json["postId"]?.asText(), equalTo("id")) assertThat(json["sone"]?.asText(), equalTo(currentSone.id)) assertThat(json["recipient"], nullValue()) } @Test fun `request with valid data and recipient creates correct post`() { addRequestParameter("text", "test") addRequestParameter("recipient", "valid") val recipient = mock<Sone>().apply { whenever(id).thenReturn("valid") } addSone(recipient) val post = createPost("valid") whenever(core.createPost(currentSone, recipient, "test")).thenReturn(post) assertThatJsonIsSuccessful() assertThat(json["postId"]?.asText(), equalTo("id")) assertThat(json["sone"]?.asText(), equalTo(currentSone.id)) assertThat(json["recipient"]?.asText(), equalTo("valid")) } @Test fun `text is filtered correctly`() { addRequestParameter("text", "Link http://freenet.test:8888/KSK@foo is filtered") addRequestHeader("Host", "freenet.test:8888") val post = createPost() whenever(core.createPost(currentSone, null, "Link KSK@foo is filtered")).thenReturn(post) assertThatJsonIsSuccessful() assertThat(json["postId"]?.asText(), equalTo("id")) assertThat(json["sone"]?.asText(), equalTo(currentSone.id)) assertThat(json["recipient"], nullValue()) } private fun createPost(recipientId: String? = null) = mock<Post>().apply { whenever(id).thenReturn("id") whenever(sone).thenReturn(currentSone) whenever(this.recipientId).thenReturn(recipientId.asOptional()) } @Test fun `page can be created by dependency injection`() { assertThat(baseInjector.getInstance<CreatePostAjaxPage>(), notNullValue()) } }
gpl-3.0
Bombe/Sone
src/test/kotlin/net/pterodactylus/sone/web/ajax/GetLikesAjaxPageTest.kt
1
3278
package net.pterodactylus.sone.web.ajax import net.pterodactylus.sone.data.Post import net.pterodactylus.sone.data.PostReply import net.pterodactylus.sone.data.Profile import net.pterodactylus.sone.data.Sone import net.pterodactylus.sone.test.getInstance import net.pterodactylus.sone.test.mock import net.pterodactylus.sone.test.whenever import net.pterodactylus.sone.web.baseInjector import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.contains import org.hamcrest.Matchers.equalTo import org.hamcrest.Matchers.notNullValue import org.junit.Test /** * Unit test for [GetLikesAjaxPage]. */ class GetLikesAjaxPageTest : JsonPageTest("getLikes.ajax", needsFormPassword = false, pageSupplier = ::GetLikesAjaxPage) { @Test fun `request without parameters results in failing request`() { assertThat(json.isSuccess, equalTo(false)) } @Test fun `request with invalid post id results in invalid-post-id`() { addRequestParameter("type", "post") addRequestParameter("post", "invalid") assertThatJsonFailed("invalid-post-id") } @Test fun `request with missing post id results in invalid-post-id`() { addRequestParameter("type", "post") assertThatJsonFailed("invalid-post-id") } @Test fun `request with valid post id results in likes for post`() { val post = mock<Post>().apply { whenever(id).thenReturn("post-id") } addPost(post) addLikes(post, createSone(2), createSone(1), createSone(3)) addRequestParameter("type", "post") addRequestParameter("post", "post-id") assertThatJsonIsSuccessful() assertThat(json["likes"]?.asInt(), equalTo(3)) assertThat(json["sones"]!!.toList().map { it["id"].asText() to it["name"].asText() }, contains( "S1" to "F1 M1 L1", "S2" to "F2 M2 L2", "S3" to "F3 M3 L3" )) } @Test fun `request with invalid reply id results in invalid-reply-id`() { addRequestParameter("type", "reply") addRequestParameter("reply", "invalid") assertThatJsonFailed("invalid-reply-id") } @Test fun `request with missing reply id results in invalid-reply-id`() { addRequestParameter("type", "reply") assertThatJsonFailed("invalid-reply-id") } @Test fun `request with valid reply id results in likes for reply`() { val reply = mock<PostReply>().apply { whenever(id).thenReturn("reply-id") } addReply(reply) addLikes(reply, createSone(2), createSone(1), createSone(3)) addRequestParameter("type", "reply") addRequestParameter("reply", "reply-id") assertThatJsonIsSuccessful() assertThat(json["likes"]?.asInt(), equalTo(3)) assertThat(json["sones"]!!.toList().map { it["id"].asText() to it["name"].asText() }, contains( "S1" to "F1 M1 L1", "S2" to "F2 M2 L2", "S3" to "F3 M3 L3" )) } @Test fun `request with invalid type results in invalid-type`() { addRequestParameter("type", "invalid") addRequestParameter("invalid", "foo") assertThatJsonFailed("invalid-type") } @Test fun `page can be created by dependency injection`() { assertThat(baseInjector.getInstance<GetLikesAjaxPage>(), notNullValue()) } } private fun createSone(index: Int) = mock<Sone>().apply { whenever(id).thenReturn("S$index") whenever(profile).thenReturn(Profile(this).apply { firstName = "F$index" middleName = "M$index" lastName = "L$index" }) }
gpl-3.0
ruuvi/Android_RuuvitagScanner
app/src/main/java/com/ruuvi/station/tagdetails/ui/TagFragment.kt
1
8662
package com.ruuvi.station.tagdetails.ui import android.app.Dialog import android.content.DialogInterface import android.os.Bundle import android.text.SpannableString import android.text.style.SuperscriptSpan import android.view.View import androidx.appcompat.app.AlertDialog import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import com.ruuvi.station.R import com.ruuvi.station.graph.GraphView import com.ruuvi.station.network.ui.SignInActivity import com.ruuvi.station.tag.domain.RuuviTag import com.ruuvi.station.tagdetails.domain.TagViewModelArgs import com.ruuvi.station.util.extensions.describingTimeSince import com.ruuvi.station.util.extensions.sharedViewModel import com.ruuvi.station.util.extensions.viewModel import kotlinx.android.synthetic.main.view_graphs.* import kotlinx.android.synthetic.main.view_tag_detail.* import org.kodein.di.Kodein import org.kodein.di.KodeinAware import org.kodein.di.android.support.closestKodein import org.kodein.di.generic.instance import timber.log.Timber import java.util.* import kotlin.concurrent.scheduleAtFixedRate class TagFragment : Fragment(R.layout.view_tag_detail), KodeinAware { override val kodein: Kodein by closestKodein() private var timer: Timer? = null private val viewModel: TagViewModel by viewModel { arguments?.let { TagViewModelArgs(it.getString(TAG_ID, "")) } } private val activityViewModel: TagDetailsViewModel by sharedViewModel() private val graphView: GraphView by instance() init { Timber.d("new TagFragment") } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) observeShowGraph() observeTagEntry() observeTagReadings() observeSelectedTag() observeSync() gattSyncButton.setOnClickListener { viewModel.syncGatt() } clearDataButton.setOnClickListener { confirm(getString(R.string.clear_confirm), DialogInterface.OnClickListener { _, _ -> viewModel.removeTagData() }) } gattSyncCancel.setOnClickListener { viewModel.disconnectGatt() } } override fun onResume() { super.onResume() timer = Timer("TagFragmentTimer", true) timer?.scheduleAtFixedRate(0, 1000) { viewModel.getTagInfo() } } override fun onPause() { super.onPause() timer?.cancel() } private fun observeSelectedTag() { activityViewModel.selectedTagObserve.observe(viewLifecycleOwner, Observer { viewModel.tagSelected(it) }) } private fun confirm(message: String, positiveButtonClick: DialogInterface.OnClickListener) { val builder = AlertDialog.Builder(requireContext()) with(builder) { setMessage(message) setPositiveButton(getString(R.string.yes), positiveButtonClick) setNegativeButton(getString(R.string.no), DialogInterface.OnClickListener { dialogInterface, i -> dialogInterface.dismiss() }) show() } } private fun gattAlertDialog(message: String) { val alertDialog = AlertDialog.Builder(requireContext(), R.style.CustomAlertDialog).create() alertDialog.setMessage(message) alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, getString(R.string.ok) ) { dialog, _ -> dialog.dismiss() } alertDialog.setOnDismissListener { gattSyncViewButtons.visibility = View.VISIBLE gattSyncViewProgress.visibility = View.GONE } alertDialog.show() } private fun observeShowGraph() { activityViewModel.isShowGraphObserve.observe(viewLifecycleOwner, Observer { isShowGraph -> view?.let { setupViewVisibility(it, isShowGraph) viewModel.isShowGraph(isShowGraph) } }) } private fun observeTagEntry() { viewModel.tagEntryObserve.observe(viewLifecycleOwner, Observer { it?.let { updateTagData(it) } }) } private fun observeSync() { viewModel.syncStatusObserve.observe(viewLifecycleOwner, Observer { when (it.syncProgress) { TagViewModel.SyncProgress.STILL -> { // nothing is happening } TagViewModel.SyncProgress.CONNECTING -> { gattSyncStatusTextView.text = "${context?.getString(R.string.connecting)}" gattSyncViewButtons.visibility = View.GONE gattSyncViewProgress.visibility = View.VISIBLE gattSyncCancel.visibility = View.GONE } TagViewModel.SyncProgress.CONNECTED -> { gattSyncStatusTextView.text = "${context?.getString(R.string.connected_reading_info)}" } TagViewModel.SyncProgress.DISCONNECTED -> { gattAlertDialog(requireContext().getString(R.string.disconnected)) } TagViewModel.SyncProgress.READING_INFO -> { gattSyncStatusTextView.text = "${context?.getString(R.string.connected_reading_info)}" } TagViewModel.SyncProgress.NOT_SUPPORTED -> { gattAlertDialog("${it.deviceInfoModel}, ${it.deviceInfoFw}\n${context?.getString(R.string.reading_history_not_supported)}") } TagViewModel.SyncProgress.READING_DATA -> { gattSyncStatusTextView.text = "${context?.getString(R.string.reading_history)}"+"..." gattSyncCancel.visibility = View.VISIBLE } TagViewModel.SyncProgress.SAVING_DATA -> { gattSyncStatusTextView.text = if (it.readDataSize > 0) { "${context?.getString(R.string.data_points_read, it.readDataSize)}" } else { "${context?.getString(R.string.no_new_data_points)}" } } TagViewModel.SyncProgress.NOT_FOUND -> { gattAlertDialog(requireContext().getString(R.string.tag_not_in_range)) } TagViewModel.SyncProgress.ERROR -> { gattAlertDialog(requireContext().getString(R.string.something_went_wrong)) } TagViewModel.SyncProgress.DONE -> { //gattAlertDialog(requireContext().getString(R.string.sync_complete)) gattSyncViewButtons.visibility = View.VISIBLE gattSyncViewProgress.visibility = View.GONE } } }) } private fun observeTagReadings() { viewModel.tagReadingsObserve.observe(viewLifecycleOwner, Observer { readings -> readings?.let { view?.let { view -> graphView.drawChart(readings, view) } } }) } private fun updateTagData(tag: RuuviTag) { Timber.d("updateTagData for ${tag.id}") tagTemperatureTextView.text = viewModel.getTemperatureStringWithoutUnit(tag) tagHumidityTextView.text = viewModel.getHumidityString(tag) tagPressureTextView.text = viewModel.getPressureString(tag) tagSignalTextView.text = viewModel.getSignalString(tag) tagUpdatedTextView.text = getString(R.string.updated, tag.updatedAt?.describingTimeSince(requireContext())) val unit = viewModel.getTemperatureUnitString() val unitSpan = SpannableString(unit) unitSpan.setSpan(SuperscriptSpan(), 0, unit.length, 0) tagTempUnitTextView.text = unitSpan tag.connectable?.let { if (it) { gattSyncView.visibility = View.VISIBLE } else { gattSyncView.visibility = View.GONE } } } private fun setupViewVisibility(view: View, showGraph: Boolean) { val graph = view.findViewById<View>(R.id.tag_graphs) graph.isVisible = showGraph tagContainer.isVisible = !showGraph } companion object { private const val TAG_ID = "TAG_ID" fun newInstance(tagEntity: RuuviTag): TagFragment { val tagFragment = TagFragment() val arguments = Bundle() arguments.putString(TAG_ID, tagEntity.id) tagFragment.arguments = arguments return tagFragment } } }
mit
lttng/lttng-scope
jabberwocky-lttng/src/main/kotlin/com/efficios/jabberwocky/lttng/kernel/analysis/os/Attributes.kt
2
3322
/* * Copyright (C) 2018 EfficiOS Inc., Alexandre Montplaisir <[email protected]> * Copyright (C) 2012-2015 Ericsson * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Eclipse Public License v1.0 which * accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package com.efficios.jabberwocky.lttng.kernel.analysis.os /** * This file defines all the attribute names used in the handler. Both the * construction and query steps should use them. * * These should not be externalized! The values here are used as-is in the * history file on disk, so they should be kept the same to keep the file format * compatible. If a view shows attribute names directly, the localization should * be done on the viewer side. */ object Attributes { /* First-level attributes */ const val CPUS = "CPUs" const val THREADS = "Threads" /* Sub-attributes of the CPU nodes */ const val CURRENT_THREAD = "Current_thread" const val SOFT_IRQS = "Soft_IRQs" const val IRQS = "IRQs" /* Sub-attributes of the Thread nodes */ const val CURRENT_CPU_RQ = "Current_cpu_rq" const val PPID = "PPID" const val EXEC_NAME = "Exec_name" const val PRIO = "Prio" const val SYSTEM_CALL = "System_call" /* Misc stuff */ const val UNKNOWN = "Unknown" const val THREAD_0_PREFIX = "0_" const val THREAD_0_SEPARATOR = "_" /** * Build the thread attribute name. * * For all threads except "0" this is the string representation of the * threadId. For thread "0" which is the idle thread and can be running * concurrently on multiple CPUs, append "_cpuId". * * @param threadId * the thread id * @param cpuId * the cpu id * @return the thread attribute name null if the threadId is zero and the * cpuId is null */ @JvmStatic fun buildThreadAttributeName(threadId: Int, cpuId: Int?): String? { if (threadId == 0) { cpuId ?: return null return "${Attributes.THREAD_0_PREFIX}$cpuId" } return threadId.toString() } /** * Parse the thread id and CPU id from the thread attribute name string * * For thread "0" the attribute name is in the form "threadId_cpuId", * extract both values from the string. * * For all other threads, the attribute name is the string representation of * the threadId and there is no cpuId. * * @param threadAttributeName * the thread attribute name * @return the thread id and cpu id */ @JvmStatic fun parseThreadAttributeName(threadAttributeName: String): Pair<Int, Int> { var threadId = -1 var cpuId = -1 try { if (threadAttributeName.startsWith(Attributes.THREAD_0_PREFIX)) { threadId = 0 val tokens = threadAttributeName.split(Attributes.THREAD_0_SEPARATOR) cpuId = Integer.parseInt(tokens[1]) } else { threadId = Integer.parseInt(threadAttributeName) } } catch (e: NumberFormatException) { // ignore } return (threadId to cpuId) } }
epl-1.0
Shynixn/PetBlocks
petblocks-bukkit-plugin/petblocks-bukkit-nms-117R1/src/main/java/com/github/shynixn/petblocks/bukkit/logic/business/listener/EntityCleanUp117R1Listener.kt
1
616
package com.github.shynixn.petblocks.bukkit.logic.business.listener import com.github.shynixn.petblocks.api.business.service.EntityService import com.google.inject.Inject import org.bukkit.event.EventHandler import org.bukkit.event.Listener import org.bukkit.event.world.EntitiesLoadEvent class EntityCleanUp117R1Listener @Inject constructor(private val entityService: EntityService) : Listener { /** * Gets called when entities are requested to load. */ @EventHandler fun onEntityLoad(event: EntitiesLoadEvent) { entityService.cleanUpInvalidEntities(event.entities.toList()) } }
apache-2.0
JetBrains/resharper-unity
rider/src/main/kotlin/com/jetbrains/rider/plugins/unity/UnityBundle.kt
1
617
package com.jetbrains.rider.plugins.unity import com.intellij.DynamicBundle import org.jetbrains.annotations.Nls import org.jetbrains.annotations.NonNls import org.jetbrains.annotations.PropertyKey class UnityBundle: DynamicBundle(BUNDLE) { companion object { @NonNls private const val BUNDLE = "messages.UnityBundle" private val INSTANCE: UnityBundle = UnityBundle() @Nls fun message( @PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any ): String { return INSTANCE.getMessage(key, *params) } } }
apache-2.0
JuliaResh/Capitolio
src/main/kotlin/org/jetbrains/capitolio/ServerModeEnum.kt
1
160
package org.jetbrains.capitolio /** * Created by Julia.Reshetnikova on 15-Jul-16. */ enum class ServerModeEnum { MAIN_SERVER, RUNNING_BUILDS_NODE }
apache-2.0
wireapp/wire-android
storage/src/main/kotlin/com/waz/zclient/storage/db/users/migration/UserDatabase137To138Migration.kt
1
557
@file:Suppress("MagicNumber") package com.waz.zclient.storage.db.users.migration import androidx.room.migration.Migration import androidx.sqlite.db.SupportSQLiteDatabase import com.waz.zclient.storage.db.MigrationUtils val USER_DATABASE_MIGRATION_137_TO_138 = object : Migration(137, 138) { override fun migrate(database: SupportSQLiteDatabase) { MigrationUtils.deleteTable(database,"FCMNotifications") MigrationUtils.deleteTable(database,"NotificationData") MigrationUtils.deleteTable(database,"FCMNotificationStats") } }
gpl-3.0
facebook/litho
sample/src/main/java/com/facebook/samples/litho/kotlin/bordereffects/VaryingRadiiBorder.kt
1
2024
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * 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.facebook.samples.litho.kotlin.bordereffects import android.graphics.Color import com.facebook.litho.Component import com.facebook.litho.ComponentScope import com.facebook.litho.KComponent import com.facebook.litho.Row import com.facebook.litho.Style import com.facebook.litho.dp import com.facebook.litho.flexbox.border import com.facebook.litho.kotlin.widget.Border import com.facebook.litho.kotlin.widget.BorderEdge import com.facebook.litho.kotlin.widget.BorderRadius import com.facebook.litho.kotlin.widget.Text class VaryingRadiiBorder : KComponent() { override fun ComponentScope.render(): Component { return Row( style = Style.border( Border( edgeAll = BorderEdge(width = 3f.dp), edgeTop = BorderEdge(color = NiceColor.GREEN), edgeBottom = BorderEdge(color = NiceColor.BLUE), edgeLeft = BorderEdge(color = Color.BLACK), edgeRight = BorderEdge(NiceColor.RED), radius = BorderRadius( topLeft = 10f.dp, topRight = 5f.dp, bottomLeft = 30f.dp, bottomRight = 20f.dp), ))) { child(Text("This component has varying corner radii", textSize = 20f.dp)) } } }
apache-2.0
toastkidjp/Jitte
app/src/main/java/jp/toastkid/yobidashi/browser/webview/factory/WebChromeClientFactory.kt
1
3011
/* * Copyright (c) 2020 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.browser.webview.factory import android.graphics.Bitmap import android.os.Message import android.view.View import android.webkit.WebChromeClient import android.webkit.WebView import androidx.core.net.toUri import androidx.fragment.app.FragmentActivity import androidx.lifecycle.ViewModelProvider import jp.toastkid.lib.BrowserViewModel import jp.toastkid.lib.image.BitmapCompressor import jp.toastkid.yobidashi.browser.BrowserHeaderViewModel import jp.toastkid.yobidashi.browser.FaviconApplier import jp.toastkid.yobidashi.browser.webview.CustomViewSwitcher class WebChromeClientFactory( private val browserHeaderViewModel: BrowserHeaderViewModel? = null, private val faviconApplier: FaviconApplier? = null, private val customViewSwitcher: CustomViewSwitcher? = null ) { operator fun invoke(): WebChromeClient = object : WebChromeClient() { private val bitmapCompressor = BitmapCompressor() override fun onProgressChanged(view: WebView, newProgress: Int) { super.onProgressChanged(view, newProgress) browserHeaderViewModel?.updateProgress(newProgress) browserHeaderViewModel?.stopProgress(newProgress < 65) } override fun onReceivedIcon(view: WebView?, favicon: Bitmap?) { super.onReceivedIcon(view, favicon) val urlStr = view?.url if (urlStr != null && favicon != null) { val file = faviconApplier?.assignFile(urlStr) ?: return bitmapCompressor(favicon, file) } } override fun onShowCustomView(view: View?, callback: CustomViewCallback?) { super.onShowCustomView(view, callback) customViewSwitcher?.onShowCustomView(view, callback) } override fun onHideCustomView() { super.onHideCustomView() customViewSwitcher?.onHideCustomView() } override fun onCreateWindow( view: WebView?, isDialog: Boolean, isUserGesture: Boolean, resultMsg: Message? ): Boolean { val href = view?.handler?.obtainMessage() view?.requestFocusNodeHref(href) val url = href?.data?.getString("url")?.toUri() ?: return super.onCreateWindow(view, isDialog, isUserGesture, resultMsg) view.stopLoading() (view.context as? FragmentActivity)?.also { fragmentActivity -> ViewModelProvider(fragmentActivity) .get(BrowserViewModel::class.java) .open(url) } return true } } }
epl-1.0
tmarsteel/compiler-fiddle
test/matchers.kt
1
966
/* * Copyright 2018 Tobias Marstaller * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package matchers var isNotNull = com.natpryce.hamkrest.Matcher("isNotNull", { it: Any? -> it != null }) var isNull = com.natpryce.hamkrest.Matcher("isNull", { it: Any? -> it == null })
lgpl-3.0
JavaEden/OrchidCore
OrchidCore/src/main/kotlin/com/eden/orchid/impl/themes/functions/HomepageUrlFunction.kt
1
637
package com.eden.orchid.impl.themes.functions import com.eden.orchid.api.OrchidContext import com.eden.orchid.api.compilers.TemplateFunction import com.eden.orchid.api.options.annotations.Description import javax.inject.Inject @Description(value = "Returns the URL to your site's homepage.", name = "Homepage URL") class HomepageUrlFunction @Inject constructor(val context: OrchidContext) : TemplateFunction("homepageUrl", true) { override fun parameters(): Array<String> { return emptyArray() } override fun apply(): Any { return context.findPage("home", "home", "home")?.link ?: context.baseUrl } }
mit
xfournet/intellij-community
platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/configurationStore/ExternalSystemStorageTest.kt
8
4015
// Copyright 2000-2017 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.openapi.externalSystem.configurationStore import com.intellij.configurationStore.ESCAPED_MODULE_DIR import com.intellij.configurationStore.useAndDispose import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.externalSystem.ExternalSystemModulePropertyManager import com.intellij.openapi.externalSystem.service.project.manage.ExternalProjectsDataStorage import com.intellij.openapi.externalSystem.service.project.manage.ExternalProjectsManagerImpl import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.module.ModuleTypeId import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.roots.ModuleRootModificationUtil import com.intellij.openapi.roots.impl.ModuleRootManagerImpl import com.intellij.project.stateStore import com.intellij.testFramework.* import com.intellij.testFramework.assertions.Assertions.assertThat import com.intellij.util.io.delete import com.intellij.util.io.parentSystemIndependentPath import com.intellij.util.io.systemIndependentPath import org.junit.ClassRule import org.junit.Rule import org.junit.Test import java.nio.file.Paths @RunsInEdt @RunsInActiveStoreMode class ExternalSystemStorageTest { companion object { @JvmField @ClassRule val projectRule = ProjectRule() } private val tempDirManager = TemporaryDirectory() @Suppress("unused") @JvmField @Rule val ruleChain = RuleChain(tempDirManager, EdtRule()) @Test fun `must be empty if external system storage`() { createProjectAndUseInLoadComponentStateMode(tempDirManager, directoryBased = true) { project -> ExternalProjectsManagerImpl.getInstance(project).setStoreExternally(true) val dotIdeaDir = Paths.get(project.stateStore.directoryStorePath) val cacheDir = ExternalProjectsDataStorage.getProjectConfigurationDir(project).resolve("modules") cacheDir.delete() // we must not use VFS here, file must not be created val moduleFile = dotIdeaDir.parent.resolve("test.iml") runWriteAction { ModuleManager.getInstance(project).newModule(moduleFile.systemIndependentPath, ModuleTypeId.JAVA_MODULE) }.useAndDispose { assertThat(cacheDir).doesNotExist() ModuleRootModificationUtil.addContentRoot(this, moduleFile.parentSystemIndependentPath) saveStore() assertThat(cacheDir).doesNotExist() assertThat(moduleFile).isEqualTo(""" <?xml version="1.0" encoding="UTF-8"?> <module type="JAVA_MODULE" version="4"> <component name="NewModuleRootManager" inherit-compiler-output="true"> <exclude-output /> <content url="file://$ESCAPED_MODULE_DIR" /> <orderEntry type="sourceFolder" forTests="false" /> </component> </module>""") ExternalSystemModulePropertyManager.getInstance(this).setMavenized(true) // force re-save: this call not in the setMavenized because ExternalSystemModulePropertyManager in the API (since in production we have the only usage, it is ok for now) (ModuleRootManager.getInstance(this) as ModuleRootManagerImpl).stateChanged() assertThat(cacheDir).doesNotExist() saveStore() assertThat(cacheDir).isDirectory assertThat(moduleFile).isEqualTo(""" <?xml version="1.0" encoding="UTF-8"?> <module type="JAVA_MODULE" version="4" />""") assertThat(cacheDir.resolve("test.xml")).isEqualTo(""" <module> <component name="ExternalSystem" externalSystem="Maven" /> <component name="NewModuleRootManager" inherit-compiler-output="true"> <exclude-output /> <content url="file://$ESCAPED_MODULE_DIR" /> <orderEntry type="sourceFolder" forTests="false" /> </component> </module>""") assertThat(dotIdeaDir.resolve("modules.xml")).doesNotExist() } } } }
apache-2.0
AerisG222/maw_photos_android
MaWPhotos/src/main/java/us/mikeandwan/photos/utils/Constants.kt
1
176
package us.mikeandwan.photos.utils const val NOTIFICATION_CHANNEL_ID_NEW_CATEGORIES = "notify_new_categories" const val NOTIFICATION_CHANNEL_ID_UPLOAD_FILES = "files_uploaded"
mit
ricardoAntolin/AndroidBluetoothDeviceListExample
app/src/main/java/com/ilaps/androidtest/dagger/scope/PerActivity.kt
1
185
package com.ilaps.androidtest.dagger.scope import javax.inject.Scope /** * Created by ricar on 4/7/17. */ @Scope @Retention(AnnotationRetention.RUNTIME) annotation class PerActivity
apache-2.0
lskycity/AndroidTools
app/src/main/java/com/lskycity/androidtools/DeviceFragment.kt
1
7211
package com.lskycity.androidtools import android.Manifest import android.annotation.SuppressLint import android.app.ActivityManager import android.content.Context import android.os.Build import android.os.Bundle import android.text.TextUtils import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AlertDialog import androidx.fragment.app.Fragment import androidx.loader.app.LoaderManager import androidx.loader.content.Loader import com.lskycity.androidtools.utils.ClassUtils import com.lskycity.androidtools.utils.PermissionUtils import com.lskycity.support.utils.DeviceUtils import java.util.* /** * Created by zhaofliu on 10/1/16. * */ class DeviceFragment : Fragment(), LoaderManager.LoaderCallbacks<ArrayList<String>> { private lateinit var deviceName: TextView private lateinit var androidVersion: TextView private lateinit var imei: TextView private lateinit var support32: TextView private lateinit var support64: TextView private lateinit var cpuFeature: TextView private lateinit var backend: TextView private lateinit var front: TextView private lateinit var grantCameraPermission: Button private lateinit var more: TextView private lateinit var glVersion: TextView private val systemInfo: CharSequence get() { val sb = StringBuilder() sb.append("-------build info -------\n\n") ClassUtils.fetchClassInfo(sb, Build::class.java) sb.append('\n') sb.append("Radio version is ") sb.append(Build.getRadioVersion()) sb.append('\n') sb.append('\n') sb.append("-------version info -------\n\n") ClassUtils.fetchClassInfo(sb, Build.VERSION::class.java) return sb } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_devices, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) deviceName = view.findViewById(R.id.device_name) as TextView androidVersion = view.findViewById(R.id.android_version) as TextView imei = view.findViewById(R.id.imei) as TextView support32 = view.findViewById(R.id.support_32) as TextView support64 = view.findViewById(R.id.support_64) as TextView cpuFeature = view.findViewById(R.id.cpu_feature) as TextView backend = view.findViewById(R.id.backend) as TextView front = view.findViewById(R.id.front) as TextView grantCameraPermission = view.findViewById(R.id.grant_camera_permission) as Button grantCameraPermission.setOnClickListener { requestPermissions(arrayOf(Manifest.permission.CAMERA), permissionId)} more = view.findViewById(R.id.more) as TextView more.setOnClickListener { clickMore() } glVersion = view.findViewById(R.id.gl_version) as TextView updateInfo() } @SuppressLint("SetTextI18n") private fun updateInfo() { deviceName.text = Build.BRAND + " " + Build.MODEL androidVersion.text = getString(R.string.android_version) + ": " + Build.VERSION.RELEASE + " / " + Build.VERSION.SDK_INT if (PermissionUtils.checkPermission(activity!!, Manifest.permission.READ_PHONE_STATE)) { imei.text = "IMEI: " + DeviceUtils.getIMEI(activity!!) } else { imei.text = getString(R.string.serial) + ": " + Build.SERIAL } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { support32.text = "64 ABI: " + Arrays.toString(Build.SUPPORTED_64_BIT_ABIS) } else { support32.text = "ABI: " + Build.CPU_ABI } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { support64.text = "32 ABI: " + Arrays.toString(Build.SUPPORTED_32_BIT_ABIS) } else { //noinspection deprecated if (!TextUtils.isEmpty(Build.CPU_ABI2)) { support64.text = "ABI2: " + Build.CPU_ABI2 } else { support64.visibility = View.GONE } } cpuFeature.text = getCpuFeature() glVersion.text = getGlVersion() try { updateCameraInfo() } catch (e: Exception) { backend.text = "No Camera found." front.visibility = View.GONE grantCameraPermission.visibility = View.GONE } } private fun getGlVersion(): String { val am = context!!.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager val info = am.deviceConfigurationInfo val glversion = info.reqGlEsVersion return (glversion shr 16).toString() + "." + (glversion and 0xffff).toString() } fun clickMore() { val builder = AlertDialog.Builder(activity!!) builder.setMessage(systemInfo) builder.setNegativeButton(android.R.string.cancel, null) builder.show() } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (PermissionUtils.verifyPermissions(grantResults)) { updateInfo() } else { Toast.makeText(activity, "No grant Permission", Toast.LENGTH_LONG).show() } } private fun updateCameraInfo() { if (PermissionUtils.checkPermission(activity!!, Manifest.permission.CAMERA)) { loaderManager.initLoader(0, null, this) grantCameraPermission.visibility = View.GONE backend.setText(R.string.loading) front.setText(R.string.loading) } else { backend.setText(R.string.grant_camera_permission_msg) front.visibility = View.GONE grantCameraPermission.visibility = View.VISIBLE } } override fun onCreateLoader(id: Int, args: Bundle?): Loader<ArrayList<String>> { return CameraParameterLoader(context!!) } override fun onLoadFinished(loader: Loader<ArrayList<String>>, data: ArrayList<String>) { if (data.size > 0) { backend.text = data[0] if (data.size > 1) { front.text = data[1] front.visibility = View.VISIBLE } else { front.visibility = View.GONE } } else { backend.setText(R.string.no_camera_found) front.visibility = View.GONE } } override fun onLoaderReset(loader: Loader<ArrayList<String>>) { } /** * A native method that is implemented by the 'native-lib' native library, * which is packaged with this application. */ private external fun getCpuFeature(): String companion object { private val permissionId = 11 init { System.loadLibrary("native-lib") } } }
apache-2.0
sepatel/tekniq
tekniq-jdbc/src/main/kotlin/io/tekniq/jdbc/TqResultSetExt.kt
1
1181
package io.tekniq.jdbc import java.sql.ResultSet fun ResultSet.getBooleanNull(x: Int) = returnNullable(getBoolean(x)) fun ResultSet.getBooleanNull(x: String) = returnNullable(getBoolean(x)) fun ResultSet.getByteNull(x: Int) = returnNullable(getByte(x)) fun ResultSet.getByteNull(x: String) = returnNullable(getByte(x)) fun ResultSet.getShortNull(x: Int) = returnNullable(getShort(x)) fun ResultSet.getShortNull(x: String) = returnNullable(getShort(x)) fun ResultSet.getIntNull(x: Int) = returnNullable(getInt(x)) fun ResultSet.getIntNull(x: String) = returnNullable(getInt(x)) fun ResultSet.getLongNull(x: Int) = returnNullable(getLong(x)) fun ResultSet.getLongNull(x: String) = returnNullable(getLong(x)) fun ResultSet.getFloatNull(x: Int) = returnNullable(getFloat(x)) fun ResultSet.getFloatNull(x: String) = returnNullable(getFloat(x)) fun ResultSet.getDoubleNull(x: Int) = returnNullable(getDouble(x)) fun ResultSet.getDoubleNull(x: String) = returnNullable(getDouble(x)) private fun <T> ResultSet.returnNullable(x: T): T? = when (wasNull()) { true -> null false -> x } inline fun ResultSet.forEach(action: ResultSet.() -> Unit) { while (next()) action(this) }
mit
JimSeker/ui
ListViews/ListviewFragmentDemo_kt/app/src/main/java/edu/cs4730/listviewfragmentdemo_kt/MainActivity.kt
1
2181
package edu.cs4730.listviewfragmentdemo_kt import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatActivity /** * This is an example using the listview in a fragment. There is very little code here that is not default * except the callbacks for the fragment named titlefrag. There is a layout and layout-land for this * so the code also decides if it needs to display a fragment or if it is already showing. * * see the two fragments textFrag and titlefrag for the bulk of the code. */ class MainActivity : AppCompatActivity(), titlefrag.OnFragmentInteractionListener { var TwoPane = false lateinit var myTextFrag: textFrag override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) if (findViewById<View?>(R.id.container) == null) { //landscape or large mode. both fragments will be displayed on the screen. // nothing to do, since it already showing. TwoPane = true myTextFrag = supportFragmentManager.findFragmentById(R.id.frag_text) as textFrag } else { //portrait or small screen. the container exists. TwoPane = false //add the title fragment. supportFragmentManager.beginTransaction() .add(R.id.container, titlefrag()) .commit() } } override fun onItemSelected(id: Int) { if (TwoPane) { //already showing, so just update it. myTextFrag.setText(id) } else { //get an new instance of the fragment with the correct data. myTextFrag = textFrag.newInstance(id) val transaction = supportFragmentManager.beginTransaction() // Replace whatever is in the fragment_container view with this fragment, // and add the transaction to the back stack so the user can navigate back transaction.replace(R.id.container, myTextFrag, "second") transaction.addToBackStack(null) // Commit the transaction transaction.commit() } } }
apache-2.0
Aptoide/aptoide-client-v8
app/src/main/java/cm/aptoide/pt/download/view/DownloadNavigator.kt
1
1585
package cm.aptoide.pt.download.view import android.app.Activity import android.content.pm.PackageManager import androidx.fragment.app.Fragment import cm.aptoide.pt.download.view.outofspace.OutOfSpaceDialogFragment import cm.aptoide.pt.download.view.outofspace.OutOfSpaceDialogFragment.Companion.newInstance import cm.aptoide.pt.download.view.outofspace.OutOfSpaceNavigatorWrapper import cm.aptoide.pt.navigator.FragmentNavigator import cm.aptoide.pt.navigator.Result import cm.aptoide.pt.utils.AptoideUtils import rx.Completable import rx.Observable class DownloadNavigator(val fragment: Fragment, val packageManager: PackageManager, val fragmentNavigator: FragmentNavigator) { fun openApp(packageName: String): Completable { return Completable.fromAction { AptoideUtils.SystemU.openApp(packageName, packageManager, fragment.context) } } fun openOutOfSpaceDialog(requiredSpace: Long, packageName: String): Completable { return Completable.fromAction { fragmentNavigator.navigateToDialogForResult( newInstance(requiredSpace, packageName), OutOfSpaceDialogFragment.OUT_OF_SPACE_REQUEST_CODE) } } fun outOfSpaceDialogResult(): Observable<OutOfSpaceNavigatorWrapper> { return fragmentNavigator.results(OutOfSpaceDialogFragment.OUT_OF_SPACE_REQUEST_CODE) .map { result: Result -> OutOfSpaceNavigatorWrapper(result.resultCode == Activity.RESULT_OK, if (result.data != null) result.data!! .getPackage() else "") } } }
gpl-3.0
alashow/music-android
app/src/main/kotlin/tm/alashow/datmusic/ui/AppNavigation.kt
1
4668
/* * Copyright (C) 2021, Alashov Berkeli * All rights reserved. */ package tm.alashow.datmusic.ui import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.Stable import androidx.compose.runtime.State import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.navigation.NavController import androidx.navigation.NavDestination.Companion.hierarchy import androidx.navigation.NavGraphBuilder import androidx.navigation.NavHostController import androidx.navigation.compose.NavHost import androidx.navigation.navigation import kotlinx.coroutines.InternalCoroutinesApi import timber.log.Timber import tm.alashow.common.compose.collectEvent import tm.alashow.datmusic.ui.album.AlbumDetail import tm.alashow.datmusic.ui.artist.ArtistDetail import tm.alashow.datmusic.ui.downloads.Downloads import tm.alashow.datmusic.ui.search.Search import tm.alashow.datmusic.ui.settings.Settings import tm.alashow.navigation.LeafScreen import tm.alashow.navigation.LocalNavigator import tm.alashow.navigation.NavigationEvent import tm.alashow.navigation.Navigator import tm.alashow.navigation.RootScreen import tm.alashow.navigation.composableScreen @OptIn(InternalCoroutinesApi::class) @Composable internal fun AppNavigation( navController: NavHostController, navigator: Navigator = LocalNavigator.current, ) { collectEvent(navigator.queue) { event -> Timber.i("Navigation event: $event") when (event) { is NavigationEvent.Destination -> navController.navigate(event.route) is NavigationEvent.Back -> navController.navigateUp() else -> Unit } } NavHost( navController = navController, startDestination = RootScreen.Search.route ) { addSearchRoot(navController) addDownloadsRoot(navController) addSettingsRoot(navController) } } private fun NavGraphBuilder.addSearchRoot(navController: NavController) { navigation( route = RootScreen.Search.route, startDestination = LeafScreen.Search.route ) { addSearch(navController) addArtistDetails(navController) addAlbumDetails(navController) } } private fun NavGraphBuilder.addDownloadsRoot(navController: NavController) { navigation( route = RootScreen.Downloads.route, startDestination = LeafScreen.Downloads.route ) { addDownloads(navController) } } private fun NavGraphBuilder.addSettingsRoot(navController: NavController) { navigation( route = RootScreen.Settings.route, startDestination = LeafScreen.Settings.route ) { addSettings(navController) } } private fun NavGraphBuilder.addSearch(navController: NavController) { composableScreen(LeafScreen.Search) { Search() } } private fun NavGraphBuilder.addSettings(navController: NavController) { composableScreen(LeafScreen.Settings) { Settings() } } private fun NavGraphBuilder.addDownloads(navController: NavController) { composableScreen(LeafScreen.Downloads) { Downloads() } } private fun NavGraphBuilder.addArtistDetails(navController: NavController) { composableScreen(LeafScreen.ArtistDetails) { ArtistDetail() } } private fun NavGraphBuilder.addAlbumDetails(navController: NavController) { composableScreen(LeafScreen.AlbumDetails) { AlbumDetail() } } /** * Adds an [NavController.OnDestinationChangedListener] to this [NavController] and updates the * returned [State] which is updated as the destination changes. */ @Stable @Composable internal fun NavController.currentScreenAsState(): State<RootScreen> { val selectedItem = remember { mutableStateOf<RootScreen>(RootScreen.Search) } DisposableEffect(this) { val listener = NavController.OnDestinationChangedListener { _, destination, _ -> when { destination.hierarchy.any { it.route == RootScreen.Search.route } -> { selectedItem.value = RootScreen.Search } destination.hierarchy.any { it.route == RootScreen.Downloads.route } -> { selectedItem.value = RootScreen.Downloads } destination.hierarchy.any { it.route == RootScreen.Settings.route } -> { selectedItem.value = RootScreen.Settings } } } addOnDestinationChangedListener(listener) onDispose { removeOnDestinationChangedListener(listener) } } return selectedItem }
apache-2.0
lbbento/pitchup
wear2/src/test/kotlin/com/lbbento/pitchupwear/main/MainPresenterTest.kt
1
3776
package com.lbbento.pitchupwear.main import com.lbbento.pitchupcore.TuningStatus.DEFAULT import com.lbbento.pitchupcore.TuningStatus.TOO_LOW import com.lbbento.pitchuptuner.GuitarTunerReactive import com.lbbento.pitchuptuner.service.TunerResult import com.lbbento.pitchupwear.common.StubAppScheduler import com.lbbento.pitchupwear.util.PermissionHelper import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.never import com.nhaarman.mockito_kotlin.verify import com.nhaarman.mockito_kotlin.whenever import org.junit.Before import org.junit.Test import rx.Observable import rx.Observable.just class MainPresenterTest { val mockPermissionHelper: PermissionHelper = mock() val mockView: MainView = mock() val mockGuitarTunerReactive: GuitarTunerReactive = mock() val mockMapper: TunerServiceMapper = mock() val stubAppSchedulers = StubAppScheduler() val mainPresenter = MainPresenter(stubAppSchedulers, mockPermissionHelper, mockGuitarTunerReactive, mockMapper) @Before fun setup() { mainPresenter.onAttachedToWindow(mockView) } @Test fun shouldSetAmbientEnabledOnCreate() { mainPresenter.onCreated() verify(mockView).setAmbientEnabled() } @Test fun shouldSetupGaugeOnCreate() { mainPresenter.onCreated() verify(mockView).setupGauge() } @Test fun shouldDoNothingWhenNoAudioPermissions() { whenever(mockPermissionHelper.handleMicrophonePermission()).thenReturn(false) mainPresenter.onViewResuming() verify(mockPermissionHelper).handleMicrophonePermission() verify(mockGuitarTunerReactive, never()).listenToNotes() } @Test fun shouldUpdateToDefaultStatus() { val tunerResult: TunerResult = mock() val tunerViewModel: TunerViewModel = mock { whenever(it.tuningStatus).thenReturn(DEFAULT) } whenever(mockPermissionHelper.handleMicrophonePermission()).thenReturn(true) whenever(mockGuitarTunerReactive.listenToNotes()).thenReturn(just(tunerResult)) whenever(mockMapper.tunerResultToViewModel(tunerResult)).thenReturn(tunerViewModel) mainPresenter.onViewResuming() verify(mockView).updateToDefaultStatus() } @Test fun shouldUpdateFrequencyIfStatusIsNotDefault() { val tunerResult: TunerResult = mock() val tunerViewModel: TunerViewModel = mock { whenever(it.tuningStatus).thenReturn(TOO_LOW) whenever(it.expectedFrequency).thenReturn(10.0) whenever(it.diffFrequency).thenReturn(1.0) whenever(it.diffInCents).thenReturn(11.0) whenever(it.note).thenReturn("A") } val setFreqTo = (tunerViewModel.expectedFrequency + (tunerViewModel.diffFrequency * -1)).toFloat() whenever(mockPermissionHelper.handleMicrophonePermission()).thenReturn(true) whenever(mockGuitarTunerReactive.listenToNotes()).thenReturn(just(tunerResult)) whenever(mockMapper.tunerResultToViewModel(tunerResult)).thenReturn(tunerViewModel) mainPresenter.onViewResuming() verify(mockView).updateIndicator(-11f) verify(mockView).updateNote(tunerViewModel.note) verify(mockView).updateCurrentFrequency(setFreqTo) } @Test fun shouldUpdateTunerViewWhenReceivedErrorFromService() { whenever(mockPermissionHelper.handleMicrophonePermission()).thenReturn(true) whenever(mockGuitarTunerReactive.listenToNotes()).thenReturn(Observable.error(IllegalStateException())) mainPresenter.onViewResuming() verify(mockPermissionHelper).handleMicrophonePermission() verify(mockGuitarTunerReactive).listenToNotes() verify(mockView).informError() } }
apache-2.0
kotlin-es/kotlin-JFrame-standalone
10-start-async-checkbutton-application/src/main/kotlin/components/button/radio/Radio.kt
2
178
package components.progressBar import components.Component import javax.swing.JComponent /** * Created by vicboma on 15/12/16. */ interface Radio : Component<JComponent> { }
mit