repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
53 values
size
stringlengths
2
6
content
stringlengths
73
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
977
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
JetBrains/intellij-community
plugins/kotlin/completion/impl-k1/src/org/jetbrains/kotlin/idea/completion/NamedArgumentCompletion.kt
1
7134
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.completion import com.intellij.codeInsight.lookup.LookupElementBuilder import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor import org.jetbrains.kotlin.idea.KotlinIcons import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.completion.implCommon.handlers.NamedArgumentInsertHandler import org.jetbrains.kotlin.idea.core.ArgumentPositionData import org.jetbrains.kotlin.idea.core.ExpectedInfo import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.idea.util.CallType import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.KtCallElement import org.jetbrains.kotlin.psi.KtSimpleNameExpression import org.jetbrains.kotlin.psi.KtValueArgument import org.jetbrains.kotlin.psi.ValueArgument import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.resolve.calls.components.isVararg import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall import org.jetbrains.kotlin.resolve.calls.util.getParameterForArgument import org.jetbrains.kotlin.types.KotlinType object NamedArgumentCompletion { fun isOnlyNamedArgumentExpected(nameExpression: KtSimpleNameExpression, resolutionFacade: ResolutionFacade): Boolean { val thisArgument = nameExpression.parent as? KtValueArgument ?: return false if (thisArgument.isNamed()) return false val resolvedCall = thisArgument.getStrictParentOfType<KtCallElement>()?.resolveToCall(resolutionFacade) ?: return false return !thisArgument.canBeUsedWithoutNameInCall(resolvedCall) } fun complete(collector: LookupElementsCollector, expectedInfos: Collection<ExpectedInfo>, callType: CallType<*>) { if (callType != CallType.DEFAULT) return val nameToParameterType = HashMap<Name, MutableSet<KotlinType>>() for (expectedInfo in expectedInfos) { val argumentData = expectedInfo.additionalData as? ArgumentPositionData.Positional ?: continue for (parameter in argumentData.namedArgumentCandidates) { nameToParameterType.getOrPut(parameter.name) { HashSet() }.add(parameter.type) } } for ((name, types) in nameToParameterType) { val typeText = types.singleOrNull()?.let { BasicLookupElementFactory.SHORT_NAMES_RENDERER.renderType(it) } ?: "..." val nameString = name.asString() val lookupElement = LookupElementBuilder.create("$nameString =") .withPresentableText("$nameString =") .withTailText(" $typeText") .withIcon(KotlinIcons.PARAMETER) .withInsertHandler(NamedArgumentInsertHandler(name)) lookupElement.putUserData(SmartCompletionInBasicWeigher.NAMED_ARGUMENT_KEY, Unit) collector.addElement(lookupElement) } } } /** * Checks whether argument in the [resolvedCall] can be used without its name (as positional argument). */ fun KtValueArgument.canBeUsedWithoutNameInCall(resolvedCall: ResolvedCall<out CallableDescriptor>): Boolean { if (resolvedCall.resultingDescriptor.valueParameters.isEmpty()) return true val argumentsThatCanBeUsedWithoutName = collectAllArgumentsThatCanBeUsedWithoutName(resolvedCall).map { it.argument } if (argumentsThatCanBeUsedWithoutName.isEmpty() || argumentsThatCanBeUsedWithoutName.none { it == this }) return false val argumentsBeforeThis = argumentsThatCanBeUsedWithoutName.takeWhile { it != this } return if (languageVersionSettings.supportsFeature(LanguageFeature.MixedNamedArgumentsInTheirOwnPosition)) { argumentsBeforeThis.none { it.isNamed() && !it.placedOnItsOwnPositionInCall(resolvedCall) } } else { argumentsBeforeThis.none { it.isNamed() } } } data class ArgumentThatCanBeUsedWithoutName( val argument: KtValueArgument, /** * When we didn't manage to map an argument to the appropriate parameter then the parameter is `null`. It's useful for cases when we * want to analyze possibility for the argument to be used without name even when appropriate parameter doesn't yet exist * (it may start existing when user will create the parameter from usage with "Add parameter to function" refactoring) */ val parameter: ValueParameterDescriptor? ) fun collectAllArgumentsThatCanBeUsedWithoutName( resolvedCall: ResolvedCall<out CallableDescriptor>, ): List<ArgumentThatCanBeUsedWithoutName> { val arguments = resolvedCall.call.valueArguments.filterIsInstance<KtValueArgument>() val argumentAndParameters = arguments.map { argument -> val parameter = resolvedCall.getParameterForArgument(argument) argument to parameter }.sortedBy { (_, parameter) -> parameter?.index ?: Int.MAX_VALUE } val firstVarargArgumentIndex = argumentAndParameters.indexOfFirst { (_, parameter) -> parameter?.isVararg ?: false } val lastVarargArgumentIndex = argumentAndParameters.indexOfLast { (_, parameter) -> parameter?.isVararg ?: false } return argumentAndParameters .asSequence() .mapIndexed { argumentIndex, (argument, parameter) -> val parameterIndex = parameter?.index ?: argumentIndex val isAfterVararg = lastVarargArgumentIndex != -1 && argumentIndex > lastVarargArgumentIndex val isVarargArg = argumentIndex in firstVarargArgumentIndex..lastVarargArgumentIndex if (!isVarargArg && argumentIndex != parameterIndex || isAfterVararg || isVarargArg && argumentAndParameters.drop(lastVarargArgumentIndex + 1).any { (argument, _) -> !argument.isNamed() } ) { null } else { ArgumentThatCanBeUsedWithoutName(argument, parameter) } } .takeWhile { it != null } // When any argument can't be used without a name then all subsequent arguments must have a name too! .map { it ?: error("It cannot be null because of the previous takeWhile in the chain") } .toList() } /** * Checks whether argument in the [resolvedCall] is on the same position as it listed in the callable definition. * * It is always true for the positional arguments, but may be untrue for the named arguments. * * ``` * fun foo(a: Int, b: Int, c: Int, d: Int) {} * * foo( * 10, // true * b = 10, // true, possible since Kotlin 1.4 with `MixedNamedArgumentsInTheirOwnPosition` feature * d = 30, // false, 3 vs 4 * c = 40 // false, 4 vs 3 * ) * ``` */ fun ValueArgument.placedOnItsOwnPositionInCall(resolvedCall: ResolvedCall<out CallableDescriptor>): Boolean { return resolvedCall.getParameterForArgument(this)?.index == resolvedCall.call.valueArguments.indexOf(this) }
apache-2.0
b6e862249907c05084b01629d3b75c34
50.323741
158
0.736754
5.226374
false
false
false
false
JetBrains/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/impl/ModuleVcsDetector.kt
1
6564
// 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.openapi.vcs.impl import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.service import com.intellij.openapi.extensions.ExtensionNotApplicableException import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.AbstractVcs import com.intellij.openapi.vcs.VcsDirectoryMapping import com.intellij.openapi.vcs.ex.ProjectLevelVcsManagerEx.MAPPING_DETECTION_LOG import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.Alarm import com.intellij.util.concurrency.annotations.RequiresBackgroundThread import com.intellij.util.ui.update.DisposableUpdate import com.intellij.util.ui.update.MergingUpdateQueue import com.intellij.workspaceModel.ide.WorkspaceModelTopics internal class ModuleVcsDetector(private val project: Project) { private val vcsManager by lazy(LazyThreadSafetyMode.NONE) { ProjectLevelVcsManagerImpl.getInstanceImpl(project) } private val queue = MergingUpdateQueue("ModuleVcsDetector", 1000, true, null, project, null, Alarm.ThreadToUse.POOLED_THREAD).also { it.setRestartTimerOnAdd(true) } private fun startDetection() { MAPPING_DETECTION_LOG.debug("ModuleVcsDetector.startDetection") project.messageBus.connect().subscribe(WorkspaceModelTopics.CHANGED, MyWorkspaceModelChangeListener()) if (vcsManager.needAutodetectMappings() && vcsManager.haveDefaultMapping() == null) { queue.queue(DisposableUpdate.createDisposable(queue, "initial scan") { autoDetectDefaultRoots() }) } } @RequiresBackgroundThread private fun autoDetectDefaultRoots() { MAPPING_DETECTION_LOG.debug("ModuleVcsDetector.autoDetectDefaultRoots") if (vcsManager.haveDefaultMapping() != null) return val contentRoots = DefaultVcsRootPolicy.getInstance(project).defaultVcsRoots MAPPING_DETECTION_LOG.debug("ModuleVcsDetector.autoDetectDefaultRoots - contentRoots", contentRoots) val usedVcses = mutableSetOf<AbstractVcs>() val detectedRoots = mutableSetOf<Pair<VirtualFile, AbstractVcs>>() contentRoots .forEach { root -> val foundVcs = vcsManager.findVersioningVcs(root) if (foundVcs != null) { detectedRoots.add(Pair(root, foundVcs)) usedVcses.add(foundVcs) } } if (detectedRoots.isEmpty()) return MAPPING_DETECTION_LOG.debug("ModuleVcsDetector.autoDetectDefaultRoots - detectedRoots", detectedRoots) val commonVcs = usedVcses.singleOrNull() if (commonVcs != null) { // Remove existing mappings that will duplicate added <Project> mapping. val rootPaths = detectedRoots.mapTo(mutableSetOf()) { it.first.path } val additionalMappings = vcsManager.directoryMappings.filter { it.vcs != commonVcs.name || it.directory !in rootPaths } vcsManager.setAutoDirectoryMappings(additionalMappings + VcsDirectoryMapping.createDefault(commonVcs.name)) } else { registerNewDirectMappings(detectedRoots) } } @RequiresBackgroundThread private fun autoDetectForContentRoots(contentRoots: List<VirtualFile>) { MAPPING_DETECTION_LOG.debug("ModuleVcsDetector.autoDetectForContentRoots - contentRoots", contentRoots) if (vcsManager.haveDefaultMapping() != null) return val usedVcses = mutableSetOf<AbstractVcs>() val detectedRoots = mutableSetOf<Pair<VirtualFile, AbstractVcs>>() contentRoots .filter { it.isInLocalFileSystem } .filter { it.isDirectory } .forEach { root -> val foundVcs = vcsManager.findVersioningVcs(root) if (foundVcs != null && foundVcs !== vcsManager.getVcsFor(root)) { detectedRoots.add(Pair(root, foundVcs)) usedVcses.add(foundVcs) } } if (detectedRoots.isEmpty()) return MAPPING_DETECTION_LOG.debug("ModuleVcsDetector.autoDetectForContentRoots - detectedRoots", detectedRoots) val commonVcs = usedVcses.singleOrNull() if (commonVcs != null && !vcsManager.hasAnyMappings()) { vcsManager.setAutoDirectoryMappings(listOf(VcsDirectoryMapping.createDefault(commonVcs.name))) } else { registerNewDirectMappings(detectedRoots) } } private fun registerNewDirectMappings(detectedRoots: Collection<Pair<VirtualFile, AbstractVcs>>) { val oldMappings = vcsManager.directoryMappings val knownMappedRoots = oldMappings.mapTo(mutableSetOf()) { it.directory } val newMappings = detectedRoots.asSequence() .map { (root, vcs) -> VcsDirectoryMapping(root.path, vcs.name) } .filter { it.directory !in knownMappedRoots } vcsManager.setAutoDirectoryMappings(oldMappings + newMappings) } private inner class MyWorkspaceModelChangeListener : ContentRootChangeListener(skipFileChanges = true) { private val dirtyContentRoots = mutableSetOf<VirtualFile>() override fun contentRootsChanged(removed: List<VirtualFile>, added: List<VirtualFile>) { if (added.isNotEmpty()) { MAPPING_DETECTION_LOG.debug("ModuleVcsDetector.contentRootsChanged - roots added", added) if (vcsManager.haveDefaultMapping() == null) { synchronized(dirtyContentRoots) { dirtyContentRoots.addAll(added) dirtyContentRoots.removeAll(removed.toSet()) } queue.queue(DisposableUpdate.createDisposable(queue, "modules scan") { runScanForNewContentRoots() }) } } if (removed.isNotEmpty()) { MAPPING_DETECTION_LOG.debug("ModuleVcsDetector.contentRootsChanged - roots removed", removed) val remotedPaths = removed.map { it.path }.toSet() val removedMappings = vcsManager.directoryMappings.filter { it.directory in remotedPaths } removedMappings.forEach { mapping -> vcsManager.removeDirectoryMapping(mapping) } } } private fun runScanForNewContentRoots() { val contentRoots: List<VirtualFile> synchronized(dirtyContentRoots) { contentRoots = dirtyContentRoots.toList() dirtyContentRoots.clear() } autoDetectForContentRoots(contentRoots) } } internal class MyStartUpActivity : VcsStartupActivity { init { if (ApplicationManager.getApplication().isUnitTestMode) { throw ExtensionNotApplicableException.create() } } override fun runActivity(project: Project) { project.service<ModuleVcsDetector>().startDetection() } override fun getOrder(): Int { return VcsInitObject.MAPPINGS.order + 10; } } }
apache-2.0
e49fec9774d00bdb14fc1fa489e71b73
40.808917
134
0.738117
4.991635
false
false
false
false
seatgeek/spreedly-java
src/main/java/cc/protea/spreedly/model/SpreedlyBankAccount.kt
1
956
package cc.protea.spreedly.model import org.simpleframework.xml.Default import org.simpleframework.xml.Element @Default(required = false) data class SpreedlyBankAccount( @field:Element(name = "first_name") var firstName: String? = null, @field:Element(name = "last_name") var lastName: String? = null, @field:Element(name = "bank_routing_number") var bankRoutingNumber: String? = null, @field:Element(name = "bank_account_number") var bankAccountNumber: String? = null, @field:Element(name = "phone_number") var phoneNumber: String? = null, var email: String? = null, var address1: String? = null, var address2: String? = null, var city: String? = null, var state: String? = null, var zip: String? = null ) { override fun toString(): String { return "SpreedlyBankAccount(firstName=$firstName)" } }
mit
8886c542024561c28f764fbc31790cc0
22.9
58
0.619247
3.854839
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/codeInsight/AbstractInspectionTest.kt
1
7448
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.codeInsight import com.intellij.codeInspection.ex.EntryPointsManagerBase import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.fileTypes.FileTypeManager import com.intellij.openapi.util.io.FileUtil import com.intellij.psi.PsiFile import com.intellij.testFramework.TestLoggerFactory import com.intellij.util.ThrowableRunnable import org.jdom.Document import org.jdom.input.SAXBuilder import org.jetbrains.kotlin.formatter.FormatSettingsUtil import org.jetbrains.kotlin.idea.compiler.configuration.KotlinPluginLayout import org.jetbrains.kotlin.idea.inspections.runInspection import org.jetbrains.kotlin.idea.test.* import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.idea.test.InTextDirectivesUtils import org.jetbrains.kotlin.idea.test.KotlinTestUtils import org.jetbrains.plugins.groovy.GroovyFileType import org.junit.runner.Description import java.io.File abstract class AbstractInspectionTest : KotlinLightCodeInsightFixtureTestCase() { companion object { const val ENTRY_POINT_ANNOTATION = "test.anno.EntryPoint" } override fun setUp() { try { super.setUp() EntryPointsManagerBase.getInstance(project).ADDITIONAL_ANNOTATIONS.add(ENTRY_POINT_ANNOTATION) registerGradlPlugin() } catch (e: Throwable) { TestLoggerFactory.logTestFailure(e) TestLoggerFactory.onTestFinished(false, Description.createTestDescription(javaClass, name)) throw e } } protected open fun registerGradlPlugin() { runWriteAction { FileTypeManager.getInstance().associateExtension(GroovyFileType.GROOVY_FILE_TYPE, "gradle") } } override fun tearDown() { runAll( ThrowableRunnable { EntryPointsManagerBase.getInstance(project).ADDITIONAL_ANNOTATIONS.remove(ENTRY_POINT_ANNOTATION) }, ThrowableRunnable { super.tearDown() } ) } protected open fun configExtra(psiFiles: List<PsiFile>, options: String) { } protected open val forceUsePackageFolder: Boolean = false //workaround for IDEA-176033 protected open fun inspectionClassDirective(): String = "// INSPECTION_CLASS: " protected open fun doTest(path: String) { val optionsFile = File(path) val options = FileUtil.loadFile(optionsFile, true) val inspectionClass = Class.forName(InTextDirectivesUtils.findStringWithPrefixes(options, inspectionClassDirective()) ?: error("Not found line with directive ${inspectionClassDirective()}")) val fixtureClasses = InTextDirectivesUtils.findListWithPrefixes(options, "// FIXTURE_CLASS: ") withCustomCompilerOptions(options, project, module) { val inspectionsTestDir = optionsFile.parentFile!! val srcDir = inspectionsTestDir.parentFile!! val settingsFile = File(inspectionsTestDir, "settings.xml") val settingsElement = if (settingsFile.exists()) { (SAXBuilder().build(settingsFile) as Document).rootElement } else { null } with(myFixture) { testDataPath = srcDir.path val afterFiles = srcDir.listFiles { it -> it.name == "inspectionData" } ?.single() ?.listFiles { it -> it.extension == "after" } ?: emptyArray() val psiFiles = srcDir.walkTopDown().onEnter { it.name != "inspectionData" }.mapNotNull { file -> when { file.isDirectory -> null file.extension == "kt" -> { val text = FileUtil.loadFile(file, true) val fileText = if (text.lines().any { it.startsWith("package") }) text else "package ${file.nameWithoutExtension};$text" if (forceUsePackageFolder) { val packageName = fileText.substring( "package".length, fileText.indexOfAny(charArrayOf(';', '\n')), ).trim() val projectFileName = packageName.replace('.', '/') + "/" + file.name addFileToProject(projectFileName, fileText) } else { configureByText(file.name, fileText)!! } } file.extension == "gradle" -> { val text = FileUtil.loadFile(file, true) val kgpArtifactVersion = KotlinPluginLayout.standaloneCompilerVersion.artifactVersion val fileText = text.replace("\$PLUGIN_VERSION", kgpArtifactVersion) configureByText(file.name, fileText)!! } else -> { val filePath = file.relativeTo(srcDir).invariantSeparatorsPath configureByFile(filePath) } } }.toList() configureCodeStyleAndRun( project, configurator = { FormatSettingsUtil.createConfigurator(options, it).configureSettings() } ) { configureRegistryAndRun(options) { try { fixtureClasses.forEach { TestFixtureExtension.loadFixture(it, myFixture.module) } configExtra(psiFiles, options) val presentation = runInspection( inspectionClass, project, settings = settingsElement, files = psiFiles.map { it.virtualFile!! }, withTestDir = inspectionsTestDir.path, ) if (afterFiles.isNotEmpty()) { presentation.problemDescriptors.forEach { problem -> problem.fixes?.forEach { quickFix -> project.executeWriteCommand(quickFix.name, quickFix.familyName) { quickFix.applyFix(project, problem) } } } for (filePath in afterFiles) { val kotlinFile = psiFiles.first { filePath.name == it.name + ".after" } KotlinTestUtils.assertEqualsToFile(filePath, kotlinFile.text) } } } finally { fixtureClasses.forEach { TestFixtureExtension.unloadFixture(it) } } } } } } } }
apache-2.0
5b4a761a662cdc163223034b08b3cb1b
44.693252
158
0.544039
6.104918
false
true
false
false
allotria/intellij-community
plugins/devkit/devkit-core/src/inspections/missingApi/resolve/PublicIntelliJSdkExternalAnnotationsRepository.kt
3
4097
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.devkit.inspections.missingApi.resolve import com.intellij.jarRepository.JarRepositoryManager import com.intellij.jarRepository.RemoteRepositoryDescription import com.intellij.openapi.project.Project import com.intellij.openapi.util.BuildNumber import com.intellij.openapi.vfs.VirtualFile import org.jetbrains.annotations.NonNls import org.jetbrains.idea.maven.aether.ArtifactKind import org.jetbrains.jps.model.library.JpsMavenRepositoryLibraryDescriptor /** * Default implementation of [IntelliJSdkExternalAnnotationsRepository] that delegates to [JarRepositoryManager] * for searching and downloading artifacts from the IntelliJ Artifacts Repositories. */ class PublicIntelliJSdkExternalAnnotationsRepository(private val project: Project) : IntelliJSdkExternalAnnotationsRepository { @Suppress("HardCodedStringLiteral") companion object { const val RELEASES_REPO_URL = "https://www.jetbrains.com/intellij-repository/releases/" const val SNAPSHOTS_REPO_URL = "https://www.jetbrains.com/intellij-repository/snapshots/" val RELEASES_REPO_DESCRIPTION = RemoteRepositoryDescription( "IntelliJ Artifacts Repository (Releases)", "IntelliJ Artifacts Repository (Releases)", RELEASES_REPO_URL ) val SNAPSHOTS_REPO_DESCRIPTION = RemoteRepositoryDescription( "IntelliJ Artifacts Repository (Snapshots)", "IntelliJ Artifacts Repository (Snapshots)", SNAPSHOTS_REPO_URL ) } private fun getAnnotationsCoordinates(): Pair<String, String>? { //Currently, for any IDE download ideaIU's annotations. return "com.jetbrains.intellij.idea" to "ideaIU" } override fun downloadExternalAnnotations(ideBuildNumber: BuildNumber): IntelliJSdkExternalAnnotations? { val (groupId, artifactId) = getAnnotationsCoordinates() ?: return null val lastReleaseVersion = "${ideBuildNumber.baselineVersion}.999999" val lastReleaseAnnotations = tryDownload(groupId, artifactId, lastReleaseVersion, listOf(RELEASES_REPO_DESCRIPTION)) if (lastReleaseAnnotations != null && lastReleaseAnnotations.annotationsBuild >= ideBuildNumber) { return lastReleaseAnnotations } @NonNls val snapshotVersion = "${ideBuildNumber.baselineVersion}-SNAPSHOT" val snapshotAnnotations = tryDownload(groupId, artifactId, snapshotVersion, listOf(SNAPSHOTS_REPO_DESCRIPTION)) if (snapshotAnnotations != null && snapshotAnnotations.annotationsBuild >= ideBuildNumber) { return snapshotAnnotations } @NonNls val latestTrunkSnapshot = "LATEST-TRUNK-SNAPSHOT" val latestTrunkSnapshotAnnotations = tryDownload(groupId, artifactId, latestTrunkSnapshot, listOf(SNAPSHOTS_REPO_DESCRIPTION)) if (latestTrunkSnapshotAnnotations != null && latestTrunkSnapshotAnnotations.annotationsBuild >= ideBuildNumber) { return latestTrunkSnapshotAnnotations } return sequenceOf(lastReleaseAnnotations, snapshotAnnotations, latestTrunkSnapshotAnnotations).filterNotNull().maxBy { it.annotationsBuild } } private fun tryDownload( groupId: String, artifactId: String, version: String, repos: List<RemoteRepositoryDescription> ): IntelliJSdkExternalAnnotations? { val annotations = tryDownloadAnnotationsArtifact(groupId, artifactId, version, repos) if (annotations != null) { val buildNumber = getAnnotationsBuildNumber(annotations) if (buildNumber != null) { return IntelliJSdkExternalAnnotations(buildNumber, annotations) } } return null } private fun tryDownloadAnnotationsArtifact( groupId: String, artifactId: String, version: String, repos: List<RemoteRepositoryDescription> ): VirtualFile? { return JarRepositoryManager.loadDependenciesSync( project, JpsMavenRepositoryLibraryDescriptor(groupId, artifactId, version), setOf(ArtifactKind.ANNOTATIONS), repos, null )?.firstOrNull()?.file } }
apache-2.0
baac2ff159370d1b2ee62ebe503a23e8
40.393939
140
0.767147
5.286452
false
true
false
false
allotria/intellij-community
platform/lang-impl/src/com/intellij/util/indexing/diagnostic/TimeStats.kt
2
1069
// 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.util.indexing.diagnostic class TimeStats { private var _count: Long? = null private var _minTime: TimeNano? = null private var _maxTime: TimeNano? = null private var _sum: TimeNano? = null @Synchronized fun addTime(time: TimeNano) { if (_maxTime == null || _maxTime!! < time) _maxTime = time if (_minTime == null || _minTime!! > time) _minTime = time _sum = (_sum ?: 0) + time _count = (_count ?: 0) + 1 } private fun failEmpty(): Nothing = throw IllegalStateException("No times have been added yet") val isEmpty: Boolean @Synchronized get() = _sum == null val sumTime: TimeNano @Synchronized get() = _sum ?: failEmpty() val minTime: TimeNano @Synchronized get() = _minTime ?: failEmpty() val maxTime: TimeNano @Synchronized get() = _maxTime ?: failEmpty() val meanTime: Double @Synchronized get() = (_sum ?: failEmpty()).toDouble() / (_count ?: failEmpty()) }
apache-2.0
ff88c5aad855e5af344a1a415c56e7ea
41.8
140
0.671656
3.988806
false
false
false
false
leafclick/intellij-community
plugins/github/src/org/jetbrains/plugins/github/authentication/util/GHSecurityUtil.kt
1
2164
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.authentication.util import com.intellij.openapi.progress.ProgressIndicator import org.jetbrains.plugins.github.api.* import org.jetbrains.plugins.github.api.data.GithubAuthenticatedUser object GHSecurityUtil { private const val REPO_SCOPE = "repo" private const val GIST_SCOPE = "gist" private const val READ_ORG_SCOPE = "read:org" val MASTER_SCOPES = listOf(REPO_SCOPE, GIST_SCOPE, READ_ORG_SCOPE) const val DEFAULT_CLIENT_NAME = "Github Integration Plugin" @JvmStatic internal fun loadCurrentUserWithScopes(executor: GithubApiRequestExecutor, progressIndicator: ProgressIndicator, server: GithubServerPath): Pair<GithubAuthenticatedUser, String?> { var scopes: String? = null val details = executor.execute(progressIndicator, object : GithubApiRequest.Get.Json<GithubAuthenticatedUser>( GithubApiRequests.getUrl(server, GithubApiRequests.CurrentUser.urlSuffix), GithubAuthenticatedUser::class.java) { override fun extractResult(response: GithubApiResponse): GithubAuthenticatedUser { scopes = response.findHeader("X-OAuth-Scopes") return super.extractResult(response) } }.withOperationName("get profile information")) return details to scopes } @JvmStatic internal fun isEnoughScopes(grantedScopes: String): Boolean { val scopesArray = grantedScopes.split(", ") if (scopesArray.isEmpty()) return false if (!scopesArray.contains(REPO_SCOPE)) return false if (!scopesArray.contains(GIST_SCOPE)) return false if (scopesArray.none { it.endsWith(":org") }) return false return true } }
apache-2.0
3842f00636abc2ef2a8cb51d70197d3d
48.204545
140
0.62061
5.57732
false
false
false
false
nobuoka/vc-oauth-java
core/src/main/kotlin/info/vividcode/oauth/OAuthProtocolParameters.kt
1
2668
package info.vividcode.oauth import java.time.Instant object OAuthProtocolParameters { sealed class Options { data class PlaintextSigning(val nonce: String?, val timestamp: Instant?) : Options() data class HmcSha1Signing(val nonce: String, val timestamp: Instant) : Options() } fun createProtocolParametersExcludingSignature( clientIdentifier: String, temporaryOrTokenIdentifier: String?, options: Options, additionalProtocolParameters: List<ProtocolParameter<*>>? ) = ProtocolParameterSet.Builder().apply { add(ProtocolParameter.ConsumerKey(clientIdentifier)) when (options) { is Options.PlaintextSigning -> { add(ProtocolParameter.SignatureMethod.Plaintext) options.nonce?.let { add(ProtocolParameter.Nonce(it)) } options.timestamp?.let { add(ProtocolParameter.Timestamp(it)) } } is Options.HmcSha1Signing -> { add(ProtocolParameter.SignatureMethod.HmacSha1) add(ProtocolParameter.Nonce(options.nonce)) add(ProtocolParameter.Timestamp(options.timestamp)) } } temporaryOrTokenIdentifier?.let { add(ProtocolParameter.Token(it)) } additionalProtocolParameters?.let { add(it) } }.build() fun createProtocolParametersExcludingSignatureForTemporaryCredentialRequest( clientCredentials: OAuthCredentials, options: Options, callbackUrl: String? = null, additionalProtocolParameters: List<ProtocolParameter<*>>? = null ): ProtocolParameterSet = createProtocolParametersExcludingSignature( clientCredentials.identifier, null, options, mutableListOf<ProtocolParameter<*>>().apply { additionalProtocolParameters?.let { addAll(it) } callbackUrl?.let { add(ProtocolParameter.Callback(it)) } } ) fun createProtocolParametersForTokenCredentialRequest( clientCredentials: OAuthCredentials, temporaryCredentials: OAuthCredentials, options: Options, verifier: String, additionalProtocolParameters: List<ProtocolParameter<*>>? = null ): ProtocolParameterSet = createProtocolParametersExcludingSignature( clientCredentials.identifier, temporaryCredentials.identifier, options, mutableListOf<ProtocolParameter<*>>().apply { additionalProtocolParameters?.let { addAll(it) } add(ProtocolParameter.Verifier(verifier)) } ) }
apache-2.0
5e8e4f4db710f789a98873b872138b80
40.6875
92
0.648426
5.955357
false
false
false
false
io53/Android_RuuvitagScanner
app/src/main/java/com/ruuvi/station/settings/ui/AppSettingsGraphViewModel.kt
1
1410
package com.ruuvi.station.settings.ui import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.ruuvi.station.app.preferences.Preferences import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.launch class AppSettingsGraphViewModel(private val preferences: Preferences) : ViewModel() { private val pointInterval = Channel<Int>(1) private val viewPeriod = Channel<Int>(1) private val showAllPoints = MutableStateFlow<Boolean>(preferences.graphShowAllPoint) val showAllPointsFlow: StateFlow<Boolean> = showAllPoints init { viewModelScope.launch { pointInterval.send(preferences.graphPointInterval) viewPeriod.send(preferences.graphViewPeriod) } } fun observePointInterval(): Flow<Int> = pointInterval.receiveAsFlow() fun observeViewPeriod(): Flow<Int> = viewPeriod.receiveAsFlow() fun setPointInterval(newInterval: Int) { preferences.graphPointInterval = newInterval } fun setViewPeriod(newPeriod: Int) { preferences.graphViewPeriod = newPeriod } fun setShowAllPoints(checked: Boolean) { preferences.graphShowAllPoint = checked showAllPoints.value = checked } }
mit
1baa203f9dadaab73aff32b516415a14
31.813953
88
0.757447
4.668874
false
false
false
false
zdary/intellij-community
plugins/git4idea/src/git4idea/ignore/GitIgnoredFilesHolder.kt
3
1248
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.ignore import com.intellij.dvcs.ignore.VcsIgnoredFilesHolderBase import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.changes.ChangesViewRefresher import com.intellij.openapi.vcs.changes.VcsIgnoredFilesHolder import git4idea.GitVcs import git4idea.repo.GitRepository import git4idea.repo.GitRepositoryManager class GitIgnoredFilesHolder(val project: Project, val manager: GitRepositoryManager) : VcsIgnoredFilesHolderBase<GitRepository>(manager) { override fun getHolder(repository: GitRepository) = repository.ignoredFilesHolder override fun copy() = GitIgnoredFilesHolder(project, manager) class Provider(val project: Project) : VcsIgnoredFilesHolder.Provider, ChangesViewRefresher { private val gitVcs = GitVcs.getInstance(project) private val manager = GitRepositoryManager.getInstance(project) override fun getVcs() = gitVcs override fun createHolder() = GitIgnoredFilesHolder(project, manager) override fun refresh(project: Project) { manager.repositories.forEach { r -> r.ignoredFilesHolder.startRescan() } } } }
apache-2.0
6b4631756721336e388dd6de04fdae79
39.290323
140
0.801282
4.588235
false
false
false
false
code-helix/slatekit
src/lib/kotlin/slatekit-server/src/main/kotlin/slatekit/server/ktor/KtorRequests.kt
1
977
package slatekit.server.ktor import io.ktor.application.ApplicationCall import io.ktor.request.uri import slatekit.requests.Request object KtorRequests { /** * Gets all the parts of the uri path * @sample "/api/account/signup" * @return ["api", "account", "signup"] */ fun getPathParts(req: Request): List<String> { val kreq = req as KtorRequest? return kreq?.call?.let { getPathParts(it) } ?: listOf() } /** * Gets all the parts of the uri path * @sample "/api/account/signup" * @return ["api", "account", "signup"] */ fun getPathParts(call: ApplicationCall): List<String> { val rawUri = call.request.uri // E.g. app/users/recent?count=20 // Only get up until "?" val uri = if (rawUri.contains("?")) { rawUri.substring(0, rawUri.indexOf("?")) } else { rawUri } val parts = uri.split('/') return parts } }
apache-2.0
4759bcb27ae813943d8d7ac8073ddae4
26.166667
63
0.574207
3.86166
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/refIndex/src/org/jetbrains/kotlin/idea/search/refIndex/KotlinCompilerReferenceIndexStorage.kt
1
7836
// 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.search.refIndex import com.intellij.compiler.server.BuildManager import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.SmartList import com.intellij.util.concurrency.AppExecutorUtil import com.intellij.util.containers.MultiMap import com.intellij.util.indexing.UnindexedFilesUpdater import com.intellij.util.io.CorruptedException import com.intellij.util.io.EnumeratorStringDescriptor import com.intellij.util.io.PersistentHashMap import org.jetbrains.annotations.TestOnly import org.jetbrains.jps.builders.impl.BuildDataPathsImpl import org.jetbrains.jps.builders.java.JavaModuleBuildTargetType import org.jetbrains.jps.builders.storage.BuildDataPaths import org.jetbrains.kotlin.config.SettingConstants import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.incremental.KOTLIN_CACHE_DIRECTORY_NAME import org.jetbrains.kotlin.incremental.storage.BasicMapsOwner import org.jetbrains.kotlin.incremental.storage.CollectionExternalizer import org.jetbrains.kotlin.name.FqName import java.nio.file.Path import java.util.concurrent.Future import kotlin.io.path.* import kotlin.system.measureTimeMillis class KotlinCompilerReferenceIndexStorage private constructor( kotlinDataContainerPath: Path, private val lookupStorageReader: LookupStorageReader, ) { companion object { /** * [org.jetbrains.kotlin.incremental.AbstractIncrementalCache.Companion.SUBTYPES] */ private val SUBTYPES_STORAGE_NAME = "subtypes.${BasicMapsOwner.CACHE_EXTENSION}" private val STORAGE_INDEXING_EXECUTOR = AppExecutorUtil.createBoundedApplicationPoolExecutor( "Kotlin compiler references indexing", UnindexedFilesUpdater.getMaxNumberOfIndexingThreads() ) private val LOG = logger<KotlinCompilerReferenceIndexStorage>() fun open(project: Project): KotlinCompilerReferenceIndexStorage? { val projectPath = runReadAction { project.takeUnless(Project::isDisposed)?.basePath } ?: return null val buildDataPaths = project.buildDataPaths val kotlinDataContainerPath = buildDataPaths?.kotlinDataContainer ?: kotlin.run { LOG.warn("${SettingConstants.KOTLIN_DATA_CONTAINER_ID} is not found") return null } val lookupStorageReader = LookupStorageReader.create(kotlinDataContainerPath, projectPath) ?: kotlin.run { LOG.warn("LookupStorage not found or corrupted") return null } val storage = KotlinCompilerReferenceIndexStorage(kotlinDataContainerPath, lookupStorageReader) if (!storage.initialize(buildDataPaths)) return null return storage } fun close(storage: KotlinCompilerReferenceIndexStorage?) { storage?.close().let { LOG.info("KCRI storage is closed" + if (it == null) " (didn't exist)" else "") } } fun hasIndex(project: Project): Boolean = LookupStorageReader.hasStorage(project) @TestOnly fun initializeForTests( buildDataPaths: BuildDataPaths, destination: ClassOneToManyStorage, ) = initializeSubtypeStorage(buildDataPaths, destination) internal val Project.buildDataPaths: BuildDataPaths? get() = BuildManager.getInstance().getProjectSystemDirectory(this)?.let(::BuildDataPathsImpl) internal val BuildDataPaths.kotlinDataContainer: Path? get() = targetsDataRoot?.toPath() ?.resolve(SettingConstants.KOTLIN_DATA_CONTAINER_ID) ?.takeIf { it.exists() && it.isDirectory() } ?.listDirectoryEntries("${SettingConstants.KOTLIN_DATA_CONTAINER_ID}*") ?.firstOrNull() private fun initializeSubtypeStorage(buildDataPaths: BuildDataPaths, destination: ClassOneToManyStorage): Boolean { var wasCorrupted = false val destinationMap = MultiMap.createConcurrentSet<String, String>() val futures = mutableListOf<Future<*>>() val timeOfFilling = measureTimeMillis { visitSubtypeStorages(buildDataPaths) { storagePath -> futures += STORAGE_INDEXING_EXECUTOR.submit { try { initializeStorage(destinationMap, storagePath) } catch (e: CorruptedException) { wasCorrupted = true LOG.warn("KCRI storage was corrupted", e) } } } try { for (future in futures) { future.get() } } catch (e: InterruptedException) { LOG.warn("KCRI initialization was interrupted") throw e } } if (wasCorrupted) return false val timeOfFlush = measureTimeMillis { for ((key, values) in destinationMap.entrySet()) { destination.put(key, values) } } LOG.info("KCRI storage is opened: took ${timeOfFilling + timeOfFlush} ms for ${futures.size} storages (filling map: $timeOfFilling ms, flush to storage: $timeOfFlush ms)") return true } private fun visitSubtypeStorages(buildDataPaths: BuildDataPaths, processor: (Path) -> Unit) { for (buildTargetType in JavaModuleBuildTargetType.ALL_TYPES) { val buildTargetPath = buildDataPaths.getTargetTypeDataRoot(buildTargetType).toPath() if (buildTargetPath.notExists() || !buildTargetPath.isDirectory()) continue buildTargetPath.forEachDirectoryEntry { targetDataRoot -> val workingPath = targetDataRoot.takeIf { it.isDirectory() } ?.resolve(KOTLIN_CACHE_DIRECTORY_NAME) ?.resolve(SUBTYPES_STORAGE_NAME) ?.takeUnless { it.notExists() } ?: return@forEachDirectoryEntry processor(workingPath) } } } } private val subtypesStorage = ClassOneToManyStorage(kotlinDataContainerPath.resolve(SUBTYPES_STORAGE_NAME)) /** * @return true if initialization was successful */ private fun initialize(buildDataPaths: BuildDataPaths): Boolean = initializeSubtypeStorage(buildDataPaths, subtypesStorage) private fun close() { lookupStorageReader.close() subtypesStorage.closeAndClean() } fun getUsages(fqName: FqName): List<VirtualFile> = lookupStorageReader[fqName].mapNotNull { VfsUtil.findFile(it, true) } fun getSubtypesOf(fqName: FqName, deep: Boolean): Sequence<FqName> = subtypesStorage[fqName, deep] } private fun initializeStorage(destinationMap: MultiMap<String, String>, subtypesSourcePath: Path) { createKotlinDataReader(subtypesSourcePath).use { source -> source.processKeys { key -> source[key]?.let { values -> destinationMap.putValues(key, values) } true } } } private fun createKotlinDataReader(storagePath: Path): PersistentHashMap<String, Collection<String>> = openReadOnlyPersistentHashMap( storagePath, EnumeratorStringDescriptor.INSTANCE, CollectionExternalizer<String>(EnumeratorStringDescriptor.INSTANCE, ::SmartList), )
apache-2.0
90ccdd672e189a7444275663d60787e3
43.022472
183
0.664497
5.381868
false
false
false
false
anthonycr/Lightning-Browser
app/src/main/java/acr/browser/lightning/browser/BrowserActivity.kt
1
28641
package acr.browser.lightning.browser import acr.browser.lightning.AppTheme import acr.browser.lightning.R import acr.browser.lightning.ThemableBrowserActivity import acr.browser.lightning.animation.AnimationUtils import acr.browser.lightning.browser.bookmark.BookmarkRecyclerViewAdapter import acr.browser.lightning.browser.color.ColorAnimator import acr.browser.lightning.browser.image.ImageLoader import acr.browser.lightning.browser.keys.KeyEventAdapter import acr.browser.lightning.browser.menu.MenuItemAdapter import acr.browser.lightning.browser.search.IntentExtractor import acr.browser.lightning.browser.search.SearchListener import acr.browser.lightning.browser.ui.BookmarkConfiguration import acr.browser.lightning.browser.ui.TabConfiguration import acr.browser.lightning.browser.ui.UiConfiguration import acr.browser.lightning.browser.search.StyleRemovingTextWatcher import acr.browser.lightning.constant.HTTP import acr.browser.lightning.database.Bookmark import acr.browser.lightning.database.HistoryEntry import acr.browser.lightning.database.SearchSuggestion import acr.browser.lightning.database.WebPage import acr.browser.lightning.database.downloads.DownloadEntry import acr.browser.lightning.databinding.BrowserActivityBinding import acr.browser.lightning.browser.di.injector import acr.browser.lightning.browser.tab.DesktopTabRecyclerViewAdapter import acr.browser.lightning.browser.tab.DrawerTabRecyclerViewAdapter import acr.browser.lightning.browser.tab.TabPager import acr.browser.lightning.browser.tab.TabViewHolder import acr.browser.lightning.browser.tab.TabViewState import acr.browser.lightning.dialog.BrowserDialog import acr.browser.lightning.dialog.DialogItem import acr.browser.lightning.dialog.LightningDialogBuilder import acr.browser.lightning.search.SuggestionsAdapter import acr.browser.lightning.ssl.createSslDrawableForState import acr.browser.lightning.utils.ProxyUtils import acr.browser.lightning.utils.value import android.content.Intent import android.content.pm.ActivityInfo import android.graphics.drawable.ColorDrawable import android.os.Bundle import android.view.inputmethod.InputMethodManager import android.widget.AdapterView import android.widget.ImageView import androidx.activity.result.contract.ActivityResultContracts import androidx.annotation.DrawableRes import androidx.annotation.MenuRes import androidx.appcompat.app.AlertDialog import androidx.core.view.isVisible import androidx.drawerlayout.widget.DrawerLayout import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.SimpleItemAnimator import acr.browser.lightning.browser.view.targetUrl.LongPress import acr.browser.lightning.extensions.color import acr.browser.lightning.extensions.drawable import acr.browser.lightning.extensions.resizeAndShow import acr.browser.lightning.extensions.takeIfInstance import acr.browser.lightning.extensions.tint import android.view.Gravity import android.view.KeyEvent import android.view.LayoutInflater import android.view.Menu import android.view.MenuItem import android.view.View import android.view.WindowManager import javax.inject.Inject /** * The base browser activity that governs the browsing experience for both default and incognito * browsers. */ abstract class BrowserActivity : ThemableBrowserActivity() { private lateinit var binding: BrowserActivityBinding private lateinit var tabsAdapter: ListAdapter<TabViewState, TabViewHolder> private lateinit var bookmarksAdapter: BookmarkRecyclerViewAdapter private var menuItemShare: MenuItem? = null private var menuItemCopyLink: MenuItem? = null private var menuItemAddToHome: MenuItem? = null private var menuItemAddBookmark: MenuItem? = null private var menuItemReaderMode: MenuItem? = null private val defaultColor by lazy { color(R.color.primary_color) } private val backgroundDrawable by lazy { ColorDrawable(defaultColor) } private var customView: View? = null @Suppress("ConvertLambdaToReference") private val launcher = registerForActivityResult( ActivityResultContracts.StartActivityForResult() ) { presenter.onFileChooserResult(it) } @Inject internal lateinit var imageLoader: ImageLoader @Inject internal lateinit var keyEventAdapter: KeyEventAdapter @Inject internal lateinit var menuItemAdapter: MenuItemAdapter @Inject internal lateinit var inputMethodManager: InputMethodManager @Inject internal lateinit var presenter: BrowserPresenter @Inject internal lateinit var tabPager: TabPager @Inject internal lateinit var intentExtractor: IntentExtractor @Inject internal lateinit var lightningDialogBuilder: LightningDialogBuilder @Inject internal lateinit var uiConfiguration: UiConfiguration @Inject internal lateinit var proxyUtils: ProxyUtils /** * True if the activity is operating in incognito mode, false otherwise. */ abstract fun isIncognito(): Boolean /** * Provide the menu used by the browser instance. */ @MenuRes abstract fun menu(): Int /** * Provide the home icon used by the browser instance. */ @DrawableRes abstract fun homeIcon(): Int override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = BrowserActivityBinding.inflate(LayoutInflater.from(this)) setContentView(binding.root) setSupportActionBar(binding.toolbar) injector.browser2ComponentBuilder() .activity(this) .browserFrame(binding.contentFrame) .toolbarRoot(binding.uiLayout) .toolbar(binding.toolbarLayout) .initialIntent(intent) .incognitoMode(isIncognito()) .build() .inject(this) binding.drawerLayout.addDrawerListener(object : DrawerLayout.SimpleDrawerListener() { override fun onDrawerOpened(drawerView: View) { if (drawerView == binding.tabDrawer) { presenter.onTabDrawerMoved(isOpen = true) } else if (drawerView == binding.bookmarkDrawer) { presenter.onBookmarkDrawerMoved(isOpen = true) } } override fun onDrawerClosed(drawerView: View) { if (drawerView == binding.tabDrawer) { presenter.onTabDrawerMoved(isOpen = false) } else if (drawerView == binding.bookmarkDrawer) { presenter.onBookmarkDrawerMoved(isOpen = false) } } }) binding.bookmarkDrawer.layoutParams = (binding.bookmarkDrawer.layoutParams as DrawerLayout.LayoutParams).apply { gravity = when (uiConfiguration.bookmarkConfiguration) { BookmarkConfiguration.LEFT -> Gravity.START BookmarkConfiguration.RIGHT -> Gravity.END } } binding.tabDrawer.layoutParams = (binding.tabDrawer.layoutParams as DrawerLayout.LayoutParams).apply { gravity = when (uiConfiguration.bookmarkConfiguration) { BookmarkConfiguration.LEFT -> Gravity.END BookmarkConfiguration.RIGHT -> Gravity.START } } binding.homeImageView.isVisible = uiConfiguration.tabConfiguration == TabConfiguration.DESKTOP || isIncognito() binding.homeImageView.setImageResource(homeIcon()) binding.tabCountView.isVisible = uiConfiguration.tabConfiguration == TabConfiguration.DRAWER && !isIncognito() if (uiConfiguration.tabConfiguration == TabConfiguration.DESKTOP) { binding.drawerLayout.setDrawerLockMode( DrawerLayout.LOCK_MODE_LOCKED_CLOSED, binding.tabDrawer ) } if (uiConfiguration.tabConfiguration == TabConfiguration.DRAWER) { tabsAdapter = DrawerTabRecyclerViewAdapter( onClick = presenter::onTabClick, onCloseClick = presenter::onTabClose, onLongClick = presenter::onTabLongClick ) binding.drawerTabsList.isVisible = true binding.drawerTabsList.adapter = tabsAdapter binding.drawerTabsList.layoutManager = LinearLayoutManager(this) binding.desktopTabsList.isVisible = false } else { tabsAdapter = DesktopTabRecyclerViewAdapter( context = this, onClick = presenter::onTabClick, onCloseClick = presenter::onTabClose, onLongClick = presenter::onTabLongClick ) binding.desktopTabsList.isVisible = true binding.desktopTabsList.adapter = tabsAdapter binding.desktopTabsList.layoutManager = LinearLayoutManager(this, RecyclerView.HORIZONTAL, false) binding.desktopTabsList.itemAnimator?.takeIfInstance<SimpleItemAnimator>() ?.supportsChangeAnimations = false binding.drawerTabsList.isVisible = false } bookmarksAdapter = BookmarkRecyclerViewAdapter( onClick = presenter::onBookmarkClick, onLongClick = presenter::onBookmarkLongClick, imageLoader = imageLoader ) binding.bookmarkListView.adapter = bookmarksAdapter binding.bookmarkListView.layoutManager = LinearLayoutManager(this) presenter.onViewAttached(BrowserStateAdapter(this)) val suggestionsAdapter = SuggestionsAdapter(this, isIncognito = isIncognito()).apply { onSuggestionInsertClick = { if (it is SearchSuggestion) { binding.search.setText(it.title) binding.search.setSelection(it.title.length) } else { binding.search.setText(it.url) binding.search.setSelection(it.url.length) } } } binding.search.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ -> binding.search.clearFocus() presenter.onSearchSuggestionClicked(suggestionsAdapter.getItem(position) as WebPage) inputMethodManager.hideSoftInputFromWindow(binding.root.windowToken, 0) } binding.search.setAdapter(suggestionsAdapter) val searchListener = SearchListener( onConfirm = { presenter.onSearch(binding.search.text.toString()) }, inputMethodManager = inputMethodManager ) binding.search.setOnEditorActionListener(searchListener) binding.search.setOnKeyListener(searchListener) binding.search.addTextChangedListener(StyleRemovingTextWatcher()) binding.search.setOnFocusChangeListener { _, hasFocus -> presenter.onSearchFocusChanged(hasFocus) binding.search.selectAll() } binding.findPrevious.setOnClickListener { presenter.onFindPrevious() } binding.findNext.setOnClickListener { presenter.onFindNext() } binding.findQuit.setOnClickListener { presenter.onFindDismiss() } binding.homeButton.setOnClickListener { presenter.onTabCountViewClick() } binding.actionBack.setOnClickListener { presenter.onBackClick() } binding.actionForward.setOnClickListener { presenter.onForwardClick() } binding.actionHome.setOnClickListener { presenter.onHomeClick() } binding.newTabButton.setOnClickListener { presenter.onNewTabClick() } binding.newTabButton.setOnLongClickListener { presenter.onNewTabLongClick() true } binding.searchRefresh.setOnClickListener { presenter.onRefreshOrStopClick() } binding.actionAddBookmark.setOnClickListener { presenter.onStarClick() } binding.actionPageTools.setOnClickListener { presenter.onToolsClick() } binding.tabHeaderButton.setOnClickListener { presenter.onTabMenuClick() } binding.actionReading.setOnClickListener { presenter.onReadingModeClick() } binding.bookmarkBackButton.setOnClickListener { presenter.onBookmarkMenuClick() } binding.searchSslStatus.setOnClickListener { presenter.onSslIconClick() } tabPager.longPressListener = presenter::onPageLongPress } override fun onNewIntent(intent: Intent?) { intent?.let(intentExtractor::extractUrlFromIntent)?.let(presenter::onNewAction) super.onNewIntent(intent) } override fun onDestroy() { super.onDestroy() presenter.onViewDetached() } override fun onPause() { super.onPause() presenter.onViewHidden() } override fun onBackPressed() { presenter.onNavigateBack() } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(menu(), menu) menuItemShare = menu.findItem(R.id.action_share) menuItemCopyLink = menu.findItem(R.id.action_copy) menuItemAddToHome = menu.findItem(R.id.action_add_to_homescreen) menuItemAddBookmark = menu.findItem(R.id.action_add_bookmark) menuItemReaderMode = menu.findItem(R.id.action_reading_mode) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return menuItemAdapter.adaptMenuItem(item)?.let(presenter::onMenuClick)?.let { true } ?: super.onOptionsItemSelected(item) } override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean { return keyEventAdapter.adaptKeyEvent(event)?.let(presenter::onKeyComboClick)?.let { true } ?: super.onKeyUp(keyCode, event) } /** * @see BrowserContract.View.renderState */ fun renderState(viewState: PartialBrowserViewState) { viewState.isBackEnabled?.let { binding.actionBack.isEnabled = it } viewState.isForwardEnabled?.let { binding.actionForward.isEnabled = it } viewState.displayUrl?.let(binding.search::setText) viewState.sslState?.let { binding.searchSslStatus.setImageDrawable(createSslDrawableForState(it)) binding.searchSslStatus.updateVisibilityForDrawable() } viewState.enableFullMenu?.let { menuItemShare?.isVisible = it menuItemCopyLink?.isVisible = it menuItemAddToHome?.isVisible = it menuItemAddBookmark?.isVisible = it menuItemReaderMode?.isVisible = it } viewState.themeColor?.value()?.let(::animateColorChange) viewState.progress?.let { binding.progressView.progress = it } viewState.isRefresh?.let { binding.searchRefresh.setImageResource( if (it) { R.drawable.ic_action_refresh } else { R.drawable.ic_action_delete } ) } viewState.bookmarks?.let(bookmarksAdapter::submitList) viewState.isBookmarked?.let { binding.actionAddBookmark.isSelected = it } viewState.isBookmarkEnabled?.let { binding.actionAddBookmark.isEnabled = it } viewState.isRootFolder?.let { binding.bookmarkBackButton.startAnimation( AnimationUtils.createRotationTransitionAnimation( binding.bookmarkBackButton, if (it) { R.drawable.ic_action_star } else { R.drawable.ic_action_back } ) ) } viewState.findInPage?.let { if (it.isEmpty()) { binding.findBar.isVisible = false } else { binding.findBar.isVisible = true binding.findQuery.text = it } } } /** * @see BrowserContract.View.renderTabs */ fun renderTabs(tabListState: List<TabViewState>) { binding.tabCountView.updateCount(tabListState.size) tabsAdapter.submitList(tabListState) } /** * @see BrowserContract.View.showAddBookmarkDialog */ fun showAddBookmarkDialog(title: String, url: String, folders: List<String>) { lightningDialogBuilder.showAddBookmarkDialog( activity = this, currentTitle = title, currentUrl = url, folders = folders, onSave = presenter::onBookmarkConfirmed ) } /** * @see BrowserContract.View.showBookmarkOptionsDialog */ fun showBookmarkOptionsDialog(bookmark: Bookmark.Entry) { lightningDialogBuilder.showLongPressedDialogForBookmarkUrl( activity = this, onClick = { presenter.onBookmarkOptionClick(bookmark, it) } ) } /** * @see BrowserContract.View.showEditBookmarkDialog */ fun showEditBookmarkDialog(title: String, url: String, folder: String, folders: List<String>) { lightningDialogBuilder.showEditBookmarkDialog( activity = this, currentTitle = title, currentUrl = url, currentFolder = folder, folders = folders, onSave = presenter::onBookmarkEditConfirmed ) } /** * @see BrowserContract.View.showFolderOptionsDialog */ fun showFolderOptionsDialog(folder: Bookmark.Folder) { lightningDialogBuilder.showBookmarkFolderLongPressedDialog( activity = this, onClick = { presenter.onFolderOptionClick(folder, it) } ) } /** * @see BrowserContract.View.showEditFolderDialog */ fun showEditFolderDialog(oldTitle: String) { lightningDialogBuilder.showRenameFolderDialog( activity = this, oldTitle = oldTitle, onSave = presenter::onBookmarkFolderRenameConfirmed ) } /** * @see BrowserContract.View.showDownloadOptionsDialog */ fun showDownloadOptionsDialog(download: DownloadEntry) { lightningDialogBuilder.showLongPressedDialogForDownloadUrl( activity = this, onClick = { presenter.onDownloadOptionClick(download, it) } ) } /** * @see BrowserContract.View.showHistoryOptionsDialog */ fun showHistoryOptionsDialog(historyEntry: HistoryEntry) { lightningDialogBuilder.showLongPressedHistoryLinkDialog( activity = this, onClick = { presenter.onHistoryOptionClick(historyEntry, it) } ) } /** * @see BrowserContract.View.showFindInPageDialog */ fun showFindInPageDialog() { BrowserDialog.showEditText( this, R.string.action_find, R.string.search_hint, R.string.search_hint, presenter::onFindInPage ) } /** * @see BrowserContract.View.showLinkLongPressDialog */ fun showLinkLongPressDialog(longPress: LongPress) { BrowserDialog.show(this, longPress.targetUrl?.replace(HTTP, ""), DialogItem(title = R.string.dialog_open_new_tab) { presenter.onLinkLongPressEvent( longPress, BrowserContract.LinkLongPressEvent.NEW_TAB ) }, DialogItem(title = R.string.dialog_open_background_tab) { presenter.onLinkLongPressEvent( longPress, BrowserContract.LinkLongPressEvent.BACKGROUND_TAB ) }, DialogItem( title = R.string.dialog_open_incognito_tab, isConditionMet = !isIncognito() ) { presenter.onLinkLongPressEvent( longPress, BrowserContract.LinkLongPressEvent.INCOGNITO_TAB ) }, DialogItem(title = R.string.action_share) { presenter.onLinkLongPressEvent(longPress, BrowserContract.LinkLongPressEvent.SHARE) }, DialogItem(title = R.string.dialog_copy_link) { presenter.onLinkLongPressEvent( longPress, BrowserContract.LinkLongPressEvent.COPY_LINK ) }) } /** * @see BrowserContract.View.showImageLongPressDialog */ fun showImageLongPressDialog(longPress: LongPress) { BrowserDialog.show(this, longPress.targetUrl?.replace(HTTP, ""), DialogItem(title = R.string.dialog_open_new_tab) { presenter.onImageLongPressEvent( longPress, BrowserContract.ImageLongPressEvent.NEW_TAB ) }, DialogItem(title = R.string.dialog_open_background_tab) { presenter.onImageLongPressEvent( longPress, BrowserContract.ImageLongPressEvent.BACKGROUND_TAB ) }, DialogItem( title = R.string.dialog_open_incognito_tab, isConditionMet = !isIncognito() ) { presenter.onImageLongPressEvent( longPress, BrowserContract.ImageLongPressEvent.INCOGNITO_TAB ) }, DialogItem(title = R.string.action_share) { presenter.onImageLongPressEvent( longPress, BrowserContract.ImageLongPressEvent.SHARE ) }, DialogItem(title = R.string.dialog_copy_link) { presenter.onImageLongPressEvent( longPress, BrowserContract.ImageLongPressEvent.COPY_LINK ) }, DialogItem(title = R.string.dialog_download_image) { presenter.onImageLongPressEvent( longPress, BrowserContract.ImageLongPressEvent.DOWNLOAD ) }) } /** * @see BrowserContract.View.showCloseBrowserDialog */ fun showCloseBrowserDialog(id: Int) { BrowserDialog.show( this, R.string.dialog_title_close_browser, DialogItem(title = R.string.close_tab) { presenter.onCloseBrowserEvent(id, BrowserContract.CloseTabEvent.CLOSE_CURRENT) }, DialogItem(title = R.string.close_other_tabs) { presenter.onCloseBrowserEvent(id, BrowserContract.CloseTabEvent.CLOSE_OTHERS) }, DialogItem(title = R.string.close_all_tabs, onClick = { presenter.onCloseBrowserEvent(id, BrowserContract.CloseTabEvent.CLOSE_ALL) }) ) } /** * @see BrowserContract.View.openBookmarkDrawer */ fun openBookmarkDrawer() { binding.drawerLayout.closeDrawer(binding.tabDrawer) binding.drawerLayout.openDrawer(binding.bookmarkDrawer) } /** * @see BrowserContract.View.closeBookmarkDrawer */ fun closeBookmarkDrawer() { binding.drawerLayout.closeDrawer(binding.bookmarkDrawer) } /** * @see BrowserContract.View.openTabDrawer */ fun openTabDrawer() { binding.drawerLayout.closeDrawer(binding.bookmarkDrawer) binding.drawerLayout.openDrawer(binding.tabDrawer) } /** * @see BrowserContract.View.closeTabDrawer */ fun closeTabDrawer() { binding.drawerLayout.closeDrawer(binding.tabDrawer) } /** * @see BrowserContract.View.showToolbar */ fun showToolbar() { tabPager.showToolbar() } /** * @see BrowserContract.View.showToolsDialog */ fun showToolsDialog(areAdsAllowed: Boolean, shouldShowAdBlockOption: Boolean) { val whitelistString = if (areAdsAllowed) { R.string.dialog_adblock_enable_for_site } else { R.string.dialog_adblock_disable_for_site } BrowserDialog.showWithIcons( this, getString(R.string.dialog_tools_title), DialogItem( icon = drawable(R.drawable.ic_action_desktop), title = R.string.dialog_toggle_desktop, onClick = presenter::onToggleDesktopAgent ), DialogItem( icon = drawable(R.drawable.ic_block), colorTint = color(R.color.error_red).takeIf { areAdsAllowed }, title = whitelistString, isConditionMet = shouldShowAdBlockOption, onClick = presenter::onToggleAdBlocking ) ) } /** * @see BrowserContract.View.showLocalFileBlockedDialog */ fun showLocalFileBlockedDialog() { AlertDialog.Builder(this) .setCancelable(true) .setTitle(R.string.title_warning) .setMessage(R.string.message_blocked_local) .setNegativeButton(android.R.string.cancel) { _, _ -> presenter.onConfirmOpenLocalFile(allow = false) } .setPositiveButton(R.string.action_open) { _, _ -> presenter.onConfirmOpenLocalFile(allow = true) } .setOnCancelListener { presenter.onConfirmOpenLocalFile(allow = false) } .resizeAndShow() } /** * @see BrowserContract.View.showFileChooser */ fun showFileChooser(intent: Intent) { launcher.launch(intent) } /** * @see BrowserContract.View.showCustomView */ fun showCustomView(view: View) { requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE binding.root.addView(view) customView = view setFullscreen(enabled = true, immersive = true) } /** * @see BrowserContract.View.hideCustomView */ fun hideCustomView() { requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED customView?.let(binding.root::removeView) customView = null setFullscreen(enabled = false, immersive = false) } /** * @see BrowserContract.View.clearSearchFocus */ fun clearSearchFocus() { binding.search.clearFocus() } // TODO: update to use non deprecated flags private fun setFullscreen(enabled: Boolean, immersive: Boolean) { val window = window val decor = window.decorView if (enabled) { if (immersive) { decor.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY) } else { decor.systemUiVisibility = View.SYSTEM_UI_FLAG_VISIBLE } window.setFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN ) } else { window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN) decor.systemUiVisibility = View.SYSTEM_UI_FLAG_VISIBLE } } private fun animateColorChange(color: Int) { if (!userPreferences.colorModeEnabled || userPreferences.useTheme != AppTheme.LIGHT || isIncognito()) { return } val shouldShowTabsInDrawer = userPreferences.showTabsInDrawer val adapter = tabsAdapter as? DesktopTabRecyclerViewAdapter val colorAnimator = ColorAnimator(defaultColor) binding.toolbar.startAnimation(colorAnimator.animateTo( color ) { mainColor, secondaryColor -> if (shouldShowTabsInDrawer) { backgroundDrawable.color = mainColor window.setBackgroundDrawable(backgroundDrawable) } else { adapter?.updateForegroundTabColor(mainColor) } binding.toolbar.setBackgroundColor(mainColor) binding.searchContainer.background?.tint(secondaryColor) }) } private fun ImageView.updateVisibilityForDrawable() { visibility = if (drawable == null) { View.GONE } else { View.VISIBLE } } }
mpl-2.0
6f93d96acb655ee6c5c7665cb19ecaf2
36.292969
111
0.64495
5.34347
false
false
false
false
siosio/intellij-community
platform/platform-api/src/com/intellij/ui/tabs/impl/JBEditorTabsBorder.kt
1
2409
// 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.ui.tabs.impl import com.intellij.openapi.util.registry.ExperimentalUI import com.intellij.ui.tabs.JBTabsBorder import com.intellij.ui.tabs.JBTabsPosition import java.awt.* class JBEditorTabsBorder(tabs: JBTabsImpl) : JBTabsBorder(tabs) { override val effectiveBorder: Insets get() = Insets(thickness, 0, 0, 0) override fun paintBorder(c: Component, g: Graphics, x: Int, y: Int, width: Int, height: Int) { g as Graphics2D tabs.tabPainter.paintBorderLine(g, thickness, Point(x, y), Point(x + width, y)) if(tabs.isEmptyVisible || tabs.isHideTabs) return if (JBTabsImpl.NEW_TABS) { val borderLines = tabs.lastLayoutPass.extraBorderLines ?: return for (borderLine in borderLines) { tabs.tabPainter.paintBorderLine(g, thickness, borderLine.from(), borderLine.to()) } } else { val myInfo2Label = tabs.myInfo2Label val firstLabel = myInfo2Label[tabs.visibleInfos[0]] ?: return val startY = firstLabel.y - if (tabs.position == JBTabsPosition.bottom) 0 else thickness when(tabs.position) { JBTabsPosition.top -> { if (!ExperimentalUI.isNewEditorTabs()) { for (eachRow in 0..tabs.lastLayoutPass.rowCount) { val yl = (eachRow * tabs.myHeaderFitSize.height) + startY tabs.tabPainter.paintBorderLine(g, thickness, Point(x, yl), Point(x + width, yl)) } } } JBTabsPosition.bottom -> { tabs.tabPainter.paintBorderLine(g, thickness, Point(x, startY), Point(x + width, startY)) tabs.tabPainter.paintBorderLine(g, thickness, Point(x, y), Point(x + width, y)) } JBTabsPosition.right -> { val lx = firstLabel.x tabs.tabPainter.paintBorderLine(g, thickness, Point(lx, y), Point(lx, y + height)) } JBTabsPosition.left -> { val bounds = firstLabel.bounds val i = bounds.x + bounds.width - thickness tabs.tabPainter.paintBorderLine(g, thickness, Point(i, y), Point(i, y + height)) } } } val selectedLabel = tabs.selectedLabel ?: return tabs.tabPainter.paintUnderline(tabs.position, selectedLabel.bounds, thickness, g, tabs.isActiveTabs(tabs.selectedInfo)) } }
apache-2.0
4eb74416eae56d96039309f16e9cc1a0
39.166667
140
0.660025
3.942717
false
false
false
false
siosio/intellij-community
platform/util/src/com/intellij/openapi/diagnostic/logger.kt
1
1525
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.diagnostic import com.intellij.openapi.progress.ProcessCanceledException import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.NonNls import java.util.concurrent.CancellationException inline fun <reified T : Any> @Suppress("unused") T.thisLogger() = Logger.getInstance(T::class.java) inline fun <reified T : Any> logger() = Logger.getInstance(T::class.java) @Deprecated(level = DeprecationLevel.ERROR, message = "Use Logger directly", replaceWith = ReplaceWith("Logger.getInstance(category)")) @ApiStatus.ScheduledForRemoval(inVersion = "2021.3") fun logger(@NonNls category: String) = Logger.getInstance(category) inline fun Logger.debug(e: Exception? = null, lazyMessage: () -> @NonNls String) { if (isDebugEnabled) { debug(lazyMessage(), e) } } inline fun Logger.trace(@NonNls lazyMessage : () -> String) { if (isTraceEnabled) { trace(lazyMessage()) } } /** Consider using [Result.getOrLogException] for more straight-forward API instead. */ inline fun <T> Logger.runAndLogException(runnable: () -> T): T? { return runCatching { runnable() }.getOrLogException(this) } fun <T> Result<T>.getOrLogException(logger: Logger): T? { return onFailure { e -> when (e) { is ProcessCanceledException, is CancellationException -> throw e else -> logger.error(e) } }.getOrNull() }
apache-2.0
2f91d36820c5afdc5997c4341b13e033
33.659091
140
0.727869
4.045093
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinMutableMethodDescriptor.kt
6
1409
// 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.refactoring.changeSignature import org.jetbrains.kotlin.descriptors.DescriptorVisibility class KotlinMutableMethodDescriptor(override val original: KotlinMethodDescriptor) : KotlinMethodDescriptor by original { private val parameters: MutableList<KotlinParameterInfo> = original.parameters override var receiver: KotlinParameterInfo? = original.receiver set(value) { if (value != null && value !in parameters) { parameters.add(value) } field = value } fun addParameter(parameter: KotlinParameterInfo) { parameters.add(parameter) } fun addParameter(index: Int, parameter: KotlinParameterInfo) { parameters.add(index, parameter) } fun removeParameter(index: Int) { val paramInfo = parameters.removeAt(index) if (paramInfo == receiver) { receiver = null } } fun renameParameter(index: Int, newName: String) { parameters[index].name = newName } fun clearNonReceiverParameters() { parameters.clear() receiver?.let { parameters.add(it) } } override fun getVisibility(): DescriptorVisibility = original.visibility }
apache-2.0
c9b6d234b18fc154fd539e69d7ca7c72
31.022727
158
0.679915
5.050179
false
false
false
false
JetBrains/kotlin-native
Interop/Indexer/src/main/kotlin/org/jetbrains/kotlin/native/interop/indexer/NativeIndex.kt
2
10892
/* * 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 to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.native.interop.indexer enum class Language(val sourceFileExtension: String) { C("c"), OBJECTIVE_C("m") } interface HeaderInclusionPolicy { /** * Whether unused declarations from given header should be excluded. * * @param headerName header path relative to the appropriate include path element (e.g. `time.h` or `curl/curl.h`), * or `null` for builtin declarations. */ fun excludeUnused(headerName: String?): Boolean } interface HeaderExclusionPolicy { /** * Whether all declarations from this header should be excluded. * * Note: the declarations from such headers can be actually present in the internal representation, * but not included into the root collections. */ fun excludeAll(headerId: HeaderId): Boolean } sealed class NativeLibraryHeaderFilter { class NameBased( val policy: HeaderInclusionPolicy, val excludeDepdendentModules: Boolean ) : NativeLibraryHeaderFilter() class Predefined(val headers: Set<String>) : NativeLibraryHeaderFilter() } interface Compilation { val includes: List<String> val additionalPreambleLines: List<String> val compilerArgs: List<String> val language: Language } data class CompilationWithPCH( override val compilerArgs: List<String>, override val language: Language ) : Compilation { constructor(compilerArgs: List<String>, precompiledHeader: String, language: Language) : this(compilerArgs + listOf("-include-pch", precompiledHeader), language) override val includes: List<String> get() = emptyList() override val additionalPreambleLines: List<String> get() = emptyList() } // TODO: Compilation hierarchy seems to require some refactoring. data class NativeLibrary(override val includes: List<String>, override val additionalPreambleLines: List<String>, override val compilerArgs: List<String>, val headerToIdMapper: HeaderToIdMapper, override val language: Language, val excludeSystemLibs: Boolean, // TODO: drop? val headerExclusionPolicy: HeaderExclusionPolicy, val headerFilter: NativeLibraryHeaderFilter) : Compilation data class IndexerResult(val index: NativeIndex, val compilation: CompilationWithPCH) /** * Retrieves the definitions from given C header file using given compiler arguments (e.g. defines). */ fun buildNativeIndex(library: NativeLibrary, verbose: Boolean): IndexerResult = buildNativeIndexImpl(library, verbose) /** * This class describes the IR of definitions from C header file(s). */ abstract class NativeIndex { abstract val structs: Collection<StructDecl> abstract val enums: Collection<EnumDef> abstract val objCClasses: Collection<ObjCClass> abstract val objCProtocols: Collection<ObjCProtocol> abstract val objCCategories: Collection<ObjCCategory> abstract val typedefs: Collection<TypedefDef> abstract val functions: Collection<FunctionDecl> abstract val macroConstants: Collection<ConstantDef> abstract val wrappedMacros: Collection<WrappedMacroDef> abstract val globals: Collection<GlobalDecl> abstract val includedHeaders: Collection<HeaderId> } /** * The (contents-based) header id. * Its [value] remains valid across different runs of the indexer and the process, * and thus can be used to 'serialize' the id. */ data class HeaderId(val value: String) data class Location(val headerId: HeaderId) interface TypeDeclaration { val location: Location } sealed class StructMember(val name: String, val type: Type) { abstract val offset: Long? } /** * C struct field. */ class Field(name: String, type: Type, override val offset: Long, val typeSize: Long, val typeAlign: Long) : StructMember(name, type) val Field.isAligned: Boolean get() = offset % (typeAlign * 8) == 0L class BitField(name: String, type: Type, override val offset: Long, val size: Int) : StructMember(name, type) class IncompleteField(name: String, type: Type) : StructMember(name, type) { override val offset: Long? get() = null } /** * C struct declaration. */ abstract class StructDecl(val spelling: String) : TypeDeclaration { abstract val def: StructDef? } /** * C struct definition. * * @param hasNaturalLayout must be `false` if the struct has unnatural layout, e.g. it is `packed`. * May be `false` even if the struct has natural layout. */ abstract class StructDef(val size: Long, val align: Int, val decl: StructDecl) { enum class Kind { STRUCT, UNION } abstract val members: List<StructMember> abstract val kind: Kind val fields: List<Field> get() = members.filterIsInstance<Field>() val bitFields: List<BitField> get() = members.filterIsInstance<BitField>() } /** * C enum value. */ class EnumConstant(val name: String, val value: Long, val isExplicitlyDefined: Boolean) /** * C enum definition. */ abstract class EnumDef(val spelling: String, val baseType: Type) : TypeDeclaration { abstract val constants: List<EnumConstant> } sealed class ObjCContainer { abstract val protocols: List<ObjCProtocol> abstract val methods: List<ObjCMethod> abstract val properties: List<ObjCProperty> } sealed class ObjCClassOrProtocol(val name: String) : ObjCContainer(), TypeDeclaration { abstract val isForwardDeclaration: Boolean } data class ObjCMethod( val selector: String, val encoding: String, val parameters: List<Parameter>, private val returnType: Type, val isVariadic: Boolean, val isClass: Boolean, val nsConsumesSelf: Boolean, val nsReturnsRetained: Boolean, val isOptional: Boolean, val isInit: Boolean, val isExplicitlyDesignatedInitializer: Boolean ) { fun returnsInstancetype(): Boolean = returnType is ObjCInstanceType fun getReturnType(container: ObjCClassOrProtocol): Type = if (returnType is ObjCInstanceType) { when (container) { is ObjCClass -> ObjCObjectPointer(container, returnType.nullability, protocols = emptyList()) is ObjCProtocol -> ObjCIdType(returnType.nullability, protocols = listOf(container)) } } else { returnType } } data class ObjCProperty(val name: String, val getter: ObjCMethod, val setter: ObjCMethod?) { fun getType(container: ObjCClassOrProtocol): Type = getter.getReturnType(container) } abstract class ObjCClass(name: String) : ObjCClassOrProtocol(name) { abstract val binaryName: String? abstract val baseClass: ObjCClass? } abstract class ObjCProtocol(name: String) : ObjCClassOrProtocol(name) abstract class ObjCCategory(val name: String, val clazz: ObjCClass) : ObjCContainer() /** * C function parameter. */ data class Parameter(val name: String?, val type: Type, val nsConsumed: Boolean) /** * C function declaration. */ class FunctionDecl(val name: String, val parameters: List<Parameter>, val returnType: Type, val binaryName: String, val isDefined: Boolean, val isVararg: Boolean) /** * C typedef definition. * * ``` * typedef $aliased $name; * ``` */ class TypedefDef(val aliased: Type, val name: String, override val location: Location) : TypeDeclaration abstract class MacroDef(val name: String) abstract class ConstantDef(name: String, val type: Type): MacroDef(name) class IntegerConstantDef(name: String, type: Type, val value: Long) : ConstantDef(name, type) class FloatingConstantDef(name: String, type: Type, val value: Double) : ConstantDef(name, type) class StringConstantDef(name: String, type: Type, val value: String) : ConstantDef(name, type) class WrappedMacroDef(name: String, val type: Type) : MacroDef(name) class GlobalDecl(val name: String, val type: Type, val isConst: Boolean) /** * C type. */ interface Type interface PrimitiveType : Type object CharType : PrimitiveType open class BoolType: PrimitiveType object CBoolType : BoolType() object ObjCBoolType : BoolType() // We omit `const` qualifier for IntegerType and FloatingType to make `CBridgeGen` simpler. // See KT-28102. data class IntegerType(val size: Int, val isSigned: Boolean, val spelling: String) : PrimitiveType // TODO: floating type is not actually defined entirely by its size. data class FloatingType(val size: Int, val spelling: String) : PrimitiveType data class VectorType(val elementType: Type, val elementCount: Int, val spelling: String) : PrimitiveType object VoidType : Type data class RecordType(val decl: StructDecl) : Type data class EnumType(val def: EnumDef) : Type data class PointerType(val pointeeType: Type, val pointeeIsConst: Boolean = false) : Type // TODO: refactor type representation and support type modifiers more generally. data class FunctionType(val parameterTypes: List<Type>, val returnType: Type) : Type interface ArrayType : Type { val elemType: Type } data class ConstArrayType(override val elemType: Type, val length: Long) : ArrayType data class IncompleteArrayType(override val elemType: Type) : ArrayType data class VariableArrayType(override val elemType: Type) : ArrayType data class Typedef(val def: TypedefDef) : Type sealed class ObjCPointer : Type { enum class Nullability { Nullable, NonNull, Unspecified } abstract val nullability: Nullability } sealed class ObjCQualifiedPointer : ObjCPointer() { abstract val protocols: List<ObjCProtocol> } data class ObjCObjectPointer( val def: ObjCClass, override val nullability: Nullability, override val protocols: List<ObjCProtocol> ) : ObjCQualifiedPointer() data class ObjCClassPointer( override val nullability: Nullability, override val protocols: List<ObjCProtocol> ) : ObjCQualifiedPointer() data class ObjCIdType( override val nullability: Nullability, override val protocols: List<ObjCProtocol> ) : ObjCQualifiedPointer() data class ObjCInstanceType(override val nullability: Nullability) : ObjCPointer() data class ObjCBlockPointer( override val nullability: Nullability, val parameterTypes: List<Type>, val returnType: Type ) : ObjCPointer() object UnsupportedType : Type
apache-2.0
47c91e7bd7c093b8c4ff08a342f28826
31.906344
119
0.724385
4.465765
false
false
false
false
androidx/androidx
tv/tv-material/src/main/java/androidx/tv/material/Tab.kt
3
8728
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.tv.material import androidx.compose.animation.animateColorAsState import androidx.compose.foundation.focusable import androidx.compose.foundation.interaction.Interaction import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.RowScope import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.graphics.Color import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.role import androidx.compose.ui.semantics.selected import androidx.compose.ui.semantics.semantics /** * Material Design tab. * * A default Tab, also known as a Primary Navigation Tab. Tabs organize content across different * screens, data sets, and other interactions. * * This should typically be used inside of a [TabRow], see the corresponding documentation for * example usage. * * @param selected whether this tab is selected or not * @param onSelect called when this tab is selected (when in focus). Doesn't trigger if the tab is * already selected * @param modifier the [Modifier] to be applied to this tab * @param enabled controls the enabled state of this tab. When `false`, this component will not * respond to user input, and it will appear visually disabled and disabled to accessibility * services. * @param colors these will be used by the tab when in different states (focused, * selected, etc.) * @param interactionSource the [MutableInteractionSource] representing the stream of [Interaction]s * for this tab. You can create and pass in your own `remember`ed instance to observe [Interaction]s * and customize the appearance / behavior of this tab in different states. * @param content content of the [Tab] */ @Composable fun Tab( selected: Boolean, onSelect: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, colors: TabColors = TabDefaults.pillIndicatorTabColors(), interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, content: @Composable RowScope.() -> Unit ) { val contentColor by animateColorAsState( getTabContentColor( colors = colors, anyTabFocused = LocalTabRowHasFocus.current, selected = selected, enabled = enabled, ) ) CompositionLocalProvider(LocalContentColor provides contentColor) { Row( modifier = modifier .semantics { this.selected = selected this.role = Role.Tab } .onFocusChanged { if (it.isFocused && !selected) { onSelect() } } .focusable(enabled, interactionSource), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically, content = content ) } } /** * Represents the colors used in a tab in different states. * * - See [TabDefaults.pillIndicatorTabColors] for the default colors used in a [Tab] when using a * Pill indicator. * - See [TabDefaults.underlinedIndicatorTabColors] for the default colors used in a [Tab] when * using an Underlined indicator */ class TabColors internal constructor( private val activeContentColor: Color, private val selectedContentColor: Color, private val focusedContentColor: Color, private val disabledActiveContentColor: Color, private val disabledSelectedContentColor: Color, ) { /** * Represents the content color for this tab, depending on whether it is inactive and [enabled] * * [Tab] is inactive when the [TabRow] is not focused * * @param enabled whether the button is enabled */ internal fun inactiveContentColor(enabled: Boolean): Color { return if (enabled) activeContentColor.copy(alpha = 0.4f) else disabledActiveContentColor.copy(alpha = 0.4f) } /** * Represents the content color for this tab, depending on whether it is active and [enabled] * * [Tab] is active when some other [Tab] is focused * * @param enabled whether the button is enabled */ internal fun activeContentColor(enabled: Boolean): Color { return if (enabled) activeContentColor else disabledActiveContentColor } /** * Represents the content color for this tab, depending on whether it is selected and [enabled] * * [Tab] is selected when the current [Tab] is selected and not focused * * @param enabled whether the button is enabled */ internal fun selectedContentColor(enabled: Boolean): Color { return if (enabled) selectedContentColor else disabledSelectedContentColor } /** * Represents the content color for this tab, depending on whether it is focused * * * [Tab] is focused when the current [Tab] is selected and focused */ internal fun focusedContentColor(): Color { return focusedContentColor } override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || other !is TabColors) return false if (activeContentColor != other.activeContentColor(true)) return false if (selectedContentColor != other.selectedContentColor(true)) return false if (focusedContentColor != other.focusedContentColor()) return false if (disabledActiveContentColor != other.activeContentColor(false)) return false if (disabledSelectedContentColor != other.selectedContentColor(false)) return false return true } override fun hashCode(): Int { var result = activeContentColor.hashCode() result = 31 * result + selectedContentColor.hashCode() result = 31 * result + focusedContentColor.hashCode() result = 31 * result + disabledActiveContentColor.hashCode() result = 31 * result + disabledSelectedContentColor.hashCode() return result } } object TabDefaults { /** * [Tab]'s content colors to in conjunction with underlined indicator */ // TODO: get selected & focused values from theme @Composable fun underlinedIndicatorTabColors( activeContentColor: Color = LocalContentColor.current, selectedContentColor: Color = Color(0xFFC9C2E8), focusedContentColor: Color = Color(0xFFC9BFFF), disabledActiveContentColor: Color = activeContentColor, disabledSelectedContentColor: Color = selectedContentColor, ): TabColors = TabColors( activeContentColor = activeContentColor, selectedContentColor = selectedContentColor, focusedContentColor = focusedContentColor, disabledActiveContentColor = disabledActiveContentColor, disabledSelectedContentColor = disabledSelectedContentColor, ) /** * [Tab]'s content colors to in conjunction with pill indicator */ // TODO: get selected & focused values from theme @Composable fun pillIndicatorTabColors( activeContentColor: Color = LocalContentColor.current, selectedContentColor: Color = Color(0xFFE5DEFF), focusedContentColor: Color = Color(0xFF313033), disabledActiveContentColor: Color = activeContentColor, disabledSelectedContentColor: Color = selectedContentColor, ): TabColors = TabColors( activeContentColor = activeContentColor, selectedContentColor = selectedContentColor, focusedContentColor = focusedContentColor, disabledActiveContentColor = disabledActiveContentColor, disabledSelectedContentColor = disabledSelectedContentColor, ) } /** Returns the [Tab]'s content color based on focused/selected state */ private fun getTabContentColor( colors: TabColors, anyTabFocused: Boolean, selected: Boolean, enabled: Boolean, ): Color = when { anyTabFocused && selected -> colors.focusedContentColor() selected -> colors.selectedContentColor(enabled) anyTabFocused -> colors.activeContentColor(enabled) else -> colors.inactiveContentColor(enabled) }
apache-2.0
844cd95a62fa45f4b7e38815d2a513db
35.518828
100
0.739688
4.96191
false
false
false
false
androidx/androidx
compose/runtime/runtime/src/androidMain/kotlin/androidx/compose/runtime/ParcelableSnapshotMutableState.kt
3
3164
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.runtime import android.annotation.SuppressLint import android.os.Parcel import android.os.Parcelable @SuppressLint("BanParcelableUsage") internal class ParcelableSnapshotMutableState<T>( value: T, policy: SnapshotMutationPolicy<T> ) : SnapshotMutableStateImpl<T>(value, policy), Parcelable { override fun writeToParcel(parcel: Parcel, flags: Int) { parcel.writeValue(value) parcel.writeInt( when (policy) { neverEqualPolicy<Any?>() -> PolicyNeverEquals structuralEqualityPolicy<Any?>() -> PolicyStructuralEquality referentialEqualityPolicy<Any?>() -> PolicyReferentialEquality else -> throw IllegalStateException( "Only known types of MutableState's SnapshotMutationPolicy are supported" ) } ) } override fun describeContents(): Int { return 0 } companion object { private const val PolicyNeverEquals = 0 private const val PolicyStructuralEquality = 1 private const val PolicyReferentialEquality = 2 @Suppress("unused") @JvmField val CREATOR: Parcelable.Creator<ParcelableSnapshotMutableState<Any?>> = object : Parcelable.ClassLoaderCreator<ParcelableSnapshotMutableState<Any?>> { override fun createFromParcel( parcel: Parcel, loader: ClassLoader? ): ParcelableSnapshotMutableState<Any?> { val value = parcel.readValue(loader ?: javaClass.classLoader) val policyIndex = parcel.readInt() return ParcelableSnapshotMutableState( value, when (policyIndex) { PolicyNeverEquals -> neverEqualPolicy() PolicyStructuralEquality -> structuralEqualityPolicy() PolicyReferentialEquality -> referentialEqualityPolicy() else -> throw IllegalStateException( "Unsupported MutableState policy $policyIndex was restored" ) } ) } override fun createFromParcel(parcel: Parcel) = createFromParcel(parcel, null) override fun newArray(size: Int) = arrayOfNulls<ParcelableSnapshotMutableState<Any?>?>(size) } } }
apache-2.0
44675f2b637e5cc1c9247b5e30961b19
38.061728
94
0.610303
5.837638
false
false
false
false
GunoH/intellij-community
platform/script-debugger/protocol/protocol-model-generator/src/TypeDescriptor.kt
2
1095
package org.jetbrains.protocolModelGenerator import org.jetbrains.jsonProtocol.ItemDescriptor import org.jetbrains.jsonProtocol.ProtocolMetaModel import org.jetbrains.protocolReader.TextOutput internal class TypeDescriptor(val type: BoxableType, private val descriptor: ItemDescriptor, private val asRawString: Boolean = false) { private val optional = descriptor is ItemDescriptor.Named && descriptor.optional fun writeAnnotations(out: TextOutput) { val default = (descriptor as? ProtocolMetaModel.Parameter)?.default if (default != null) { out.append("@Optional").append("(\"").append(default).append("\")").newLine() } if (asRawString) { out.append("@org.jetbrains.jsonProtocol.JsonField(") if (asRawString) { out.append("allowAnyPrimitiveValue=true") } out.append(")").newLine() } } val isNullableType: Boolean get() = !isPrimitive && (optional || asRawString) val isPrimitive: Boolean get() = type == BoxableType.BOOLEAN || type == BoxableType.INT || type == BoxableType.LONG || type == BoxableType.NUMBER }
apache-2.0
acae19d1657628ac86dc4ea63131507c
35.5
136
0.714155
4.719828
false
false
false
false
GunoH/intellij-community
plugins/evaluation-plugin/src/com/intellij/cce/interpreter/DelegationCompletionInvoker.kt
4
2796
package com.intellij.cce.interpreter import com.intellij.cce.core.Lookup import com.intellij.cce.core.Session import com.intellij.cce.core.TokenProperties import com.intellij.cce.util.ListSizeRestriction import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.Project class DelegationCompletionInvoker(private val invoker: CompletionInvoker, project: Project) : CompletionInvoker { private val applicationListenersRestriction = ListSizeRestriction.applicationListeners() private val dumbService = DumbService.getInstance(project) override fun moveCaret(offset: Int) = onEdt { invoker.moveCaret(offset) } override fun callCompletion(expectedText: String, prefix: String?): Lookup { return readActionWaitingForSize { invoker.callCompletion(expectedText, prefix) } } override fun finishCompletion(expectedText: String, prefix: String) = readAction { invoker.finishCompletion(expectedText, prefix) } override fun printText(text: String) = writeAction { invoker.printText(text) } override fun deleteRange(begin: Int, end: Int) = writeAction { invoker.deleteRange(begin, end) } override fun emulateUserSession(expectedText: String, nodeProperties: TokenProperties, offset: Int): Session { return readActionWaitingForSize { invoker.emulateUserSession(expectedText, nodeProperties, offset) } } override fun emulateCompletionGolfSession(expectedLine: String, offset: Int, nodeProperties: TokenProperties): Session { return readActionWaitingForSize { invoker.emulateCompletionGolfSession(expectedLine, offset, nodeProperties) } } override fun openFile(file: String): String = readAction { invoker.openFile(file) } override fun closeFile(file: String) = onEdt { invoker.closeFile(file) } override fun isOpen(file: String) = readAction { invoker.isOpen(file) } override fun save() = writeAction { invoker.save() } override fun getText(): String = readAction { invoker.getText() } private fun <T> readActionWaitingForSize(size: Int = 100, action: () -> T): T { applicationListenersRestriction.waitForSize(size) return readAction(action) } private fun <T> readAction(runnable: () -> T): T { var result: T? = null ApplicationManager.getApplication().invokeAndWait { result = dumbService.runReadActionInSmartMode<T>(runnable) } return result!! } private fun writeAction(action: () -> Unit) { ApplicationManager.getApplication().invokeAndWait { ApplicationManager.getApplication().runWriteAction(action) } } private fun onEdt(action: () -> Unit) = ApplicationManager.getApplication().invokeAndWait { action() } }
apache-2.0
d89174173e9b88968f10d8af979f2844
29.391304
122
0.742489
4.591133
false
false
false
false
GunoH/intellij-community
uast/uast-common/src/org/jetbrains/uast/UastContext.kt
3
9011
// 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.uast import com.intellij.ide.plugins.DynamicPluginListener import com.intellij.ide.plugins.IdeaPluginDescriptor import com.intellij.lang.Language import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.project.Project import com.intellij.psi.* import com.intellij.util.containers.CollectionFactory import com.intellij.util.containers.map2Array import org.jetbrains.annotations.Contract import org.jetbrains.uast.util.ClassSet import org.jetbrains.uast.util.ClassSetsWrapper import org.jetbrains.uast.util.emptyClassSet import java.util.* @Deprecated("use UastFacade or UastLanguagePlugin instead", ReplaceWith("UastFacade")) class UastContext(val project: Project) : UastLanguagePlugin by UastFacade { fun findPlugin(element: PsiElement): UastLanguagePlugin? = UastFacade.findPlugin(element) fun getMethod(method: PsiMethod): UMethod = convertWithParent(method)!! fun getVariable(variable: PsiVariable): UVariable = convertWithParent(variable)!! fun getClass(clazz: PsiClass): UClass = convertWithParent(clazz)!! } /** * The main entry point to uast-conversions. * * In the most cases you could use [toUElement] or [toUElementOfExpectedTypes] extension methods instead of using the `UastFacade` directly */ object UastFacade : UastLanguagePlugin { override val language: Language = object : Language("UastContextLanguage") {} override val priority: Int get() = 0 val languagePlugins: Collection<UastLanguagePlugin> get() = UastLanguagePlugin.getInstances() private var cachedLastPlugin: UastLanguagePlugin = this fun findPlugin(element: PsiElement): UastLanguagePlugin? = findPlugin(element.language) fun findPlugin(language: Language): UastLanguagePlugin? { val cached = cachedLastPlugin if (language === cached.language) return cached val plugin = languagePlugins.firstOrNull { it.language === language } if (plugin != null) cachedLastPlugin = plugin return plugin } override fun isFileSupported(fileName: String): Boolean = languagePlugins.any { it.isFileSupported(fileName) } override fun convertElement(element: PsiElement, parent: UElement?, requiredType: Class<out UElement>?): UElement? { return findPlugin(element)?.convertElement(element, parent, requiredType) } override fun convertElementWithParent(element: PsiElement, requiredType: Class<out UElement>?): UElement? { if (element is PsiWhiteSpace) { return null } return findPlugin(element)?.convertElementWithParent(element, requiredType) } override fun getMethodCallExpression( element: PsiElement, containingClassFqName: String?, methodName: String ): UastLanguagePlugin.ResolvedMethod? { return findPlugin(element)?.getMethodCallExpression(element, containingClassFqName, methodName) } override fun getConstructorCallExpression( element: PsiElement, fqName: String ): UastLanguagePlugin.ResolvedConstructor? { return findPlugin(element)?.getConstructorCallExpression(element, fqName) } override fun isExpressionValueUsed(element: UExpression): Boolean { val language = element.getLanguage() return findPlugin(language)?.isExpressionValueUsed(element) ?: false } private tailrec fun UElement.getLanguage(): Language { sourcePsi?.language?.let { return it } val containingElement = this.uastParent ?: throw IllegalStateException("At least UFile should have a language") return containingElement.getLanguage() } override fun <T : UElement> convertElementWithParent(element: PsiElement, requiredTypes: Array<out Class<out T>>): T? = findPlugin(element)?.convertElementWithParent(element, requiredTypes) override fun <T : UElement> convertToAlternatives(element: PsiElement, requiredTypes: Array<out Class<out T>>): Sequence<T> = findPlugin(element)?.convertToAlternatives(element, requiredTypes) ?: emptySequence() private interface UastPluginListener { fun onPluginsChanged() } private val exposedListeners = Collections.newSetFromMap(CollectionFactory.createConcurrentWeakIdentityMap<UastPluginListener, Boolean>()) init { ApplicationManager.getApplication().getMessageBus().simpleConnect().subscribe(DynamicPluginListener.TOPIC, object: DynamicPluginListener { override fun pluginUnloaded(pluginDescriptor: IdeaPluginDescriptor, isUpdate: Boolean) { // avoid Language mem-leak on its plugin unload cachedLastPlugin = this@UastFacade } }) UastLanguagePlugin.extensionPointName.addChangeListener({ exposedListeners.forEach(UastPluginListener::onPluginsChanged) }, null) } override fun getPossiblePsiSourceTypes(vararg uastTypes: Class<out UElement>): ClassSet<PsiElement> = object : ClassSet<PsiElement>, UastPluginListener { fun initInner(): ClassSetsWrapper<PsiElement> = ClassSetsWrapper(languagePlugins.map2Array { it.getPossiblePsiSourceTypes(*uastTypes) }) private var inner: ClassSetsWrapper<PsiElement> = initInner() override fun onPluginsChanged() { inner = initInner() } override fun isEmpty(): Boolean = inner.isEmpty() override fun contains(element: Class<out PsiElement>): Boolean = inner.contains(element) override fun toList(): List<Class<out PsiElement>> = inner.toList() }.also { exposedListeners.add(it) } } /** * Converts the element to UAST. */ fun PsiElement?.toUElement(): UElement? = if (this == null) null else UastFacade.convertElementWithParent(this, null) /** * Converts the element to an UAST element of the given type. Returns null if the PSI element type does not correspond * to the given UAST element type. */ @Suppress("UNCHECKED_CAST") @Contract("null, _ -> null") fun <T : UElement> PsiElement?.toUElement(cls: Class<out T>): T? = if (this == null) null else UastFacade.convertElementWithParent(this, cls) as T? @Suppress("UNCHECKED_CAST") @SafeVarargs fun <T : UElement> PsiElement?.toUElementOfExpectedTypes(vararg classes: Class<out T>): T? = this?.let { if (classes.isEmpty()) { UastFacade.convertElementWithParent(this, UElement::class.java) as T? } else if (classes.size == 1) { UastFacade.convertElementWithParent(this, classes[0]) as T? } else { UastFacade.convertElementWithParent(this, classes) } } inline fun <reified T : UElement> PsiElement?.toUElementOfType(): T? = toUElement(T::class.java) /** * Finds an UAST element of a given type at the given [offset] in the specified file. Returns null if there is no UAST * element of the given type at the given offset. */ fun <T : UElement> PsiFile.findUElementAt(offset: Int, cls: Class<out T>): T? { val element = findElementAt(offset) ?: return null val uElement = element.toUElement() ?: return null @Suppress("UNCHECKED_CAST") return uElement.withContainingElements.firstOrNull { cls.isInstance(it) } as T? } /** * Finds an UAST element of the given type among the parents of the given PSI element. */ @JvmOverloads fun <T : UElement> PsiElement?.getUastParentOfType(cls: Class<out T>, strict: Boolean = false): T? = this?.run { val firstUElement = getFirstUElement(this, strict) ?: return null @Suppress("UNCHECKED_CAST") return firstUElement.withContainingElements.firstOrNull { cls.isInstance(it) } as T? } /** * Finds an UAST element of any given type among the parents of the given PSI element. */ @JvmOverloads fun PsiElement?.getUastParentOfTypes(classes: Array<Class<out UElement>>, strict: Boolean = false): UElement? = this?.run { val firstUElement = getFirstUElement(this, strict) ?: return null return firstUElement.withContainingElements.firstOrNull { uElement -> classes.any { cls -> cls.isInstance(uElement) } } } inline fun <reified T : UElement> PsiElement?.getUastParentOfType(strict: Boolean = false): T? = getUastParentOfType(T::class.java, strict) @JvmField val DEFAULT_TYPES_LIST: Array<Class<out UElement>> = arrayOf(UElement::class.java) @JvmField val DEFAULT_EXPRESSION_TYPES_LIST: Array<Class<out UExpression>> = arrayOf(UExpression::class.java) /** * @return types of possible source PSI elements of [language], which instances in principle * can be converted to at least one of the specified [uastTypes] * (or to [UElement] if no type was specified) * * @see UastFacade.getPossiblePsiSourceTypes */ fun getPossiblePsiSourceTypes(language: Language, vararg uastTypes: Class<out UElement>): ClassSet<PsiElement> = UastFacade.findPlugin(language)?.getPossiblePsiSourceTypes(*uastTypes) ?: emptyClassSet() private fun getFirstUElement(psiElement: PsiElement, strict: Boolean = false): UElement? { val startingElement = if (strict) psiElement.parent else psiElement val parentSequence = generateSequence(startingElement, PsiElement::getParent) return parentSequence.mapNotNull { it.toUElement() }.firstOrNull() }
apache-2.0
850f1081a3d99ce1de30369b6d1bf38b
39.227679
147
0.754411
4.623397
false
false
false
false
GunoH/intellij-community
plugins/kotlin/base/project-structure/src/org/jetbrains/kotlin/idea/base/projectStructure/moduleInfo/KlibCompatibilityInfo.kt
2
2805
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:JvmName("KlibCompatibilityInfoUtils") package org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.project.Project import com.intellij.openapi.roots.impl.libraries.LibraryEx import org.jetbrains.kotlin.backend.common.serialization.metadata.KlibMetadataVersion import org.jetbrains.kotlin.backend.common.serialization.metadata.metadataVersion import org.jetbrains.kotlin.idea.base.util.asKotlinLogger import org.jetbrains.kotlin.konan.file.File import org.jetbrains.kotlin.library.* import org.jetbrains.kotlin.platform.TargetPlatform /** * Whether a certain KLIB is compatible for the purposes of IDE: indexation, resolve, etc. */ sealed class KlibCompatibilityInfo(val isCompatible: Boolean) { object Compatible : KlibCompatibilityInfo(true) object Pre14Layout : KlibCompatibilityInfo(false) class IncompatibleMetadata(val isOlder: Boolean) : KlibCompatibilityInfo(false) } abstract class AbstractKlibLibraryInfo internal constructor(project: Project, library: LibraryEx, val libraryRoot: String) : LibraryInfo(project, library) { val resolvedKotlinLibrary: KotlinLibrary = resolveSingleFileKlib( libraryFile = File(libraryRoot), logger = LOG, strategy = ToolingSingleFileKlibResolveStrategy ) val compatibilityInfo: KlibCompatibilityInfo by lazy { resolvedKotlinLibrary.compatibilityInfo } final override fun getLibraryRoots() = listOf(libraryRoot) abstract override val platform: TargetPlatform // must override val uniqueName: String? by lazy { resolvedKotlinLibrary.safeRead(null) { uniqueName } } val isInterop: Boolean by lazy { resolvedKotlinLibrary.safeRead(false) { isInterop } } companion object { private val LOG = Logger.getInstance(AbstractKlibLibraryInfo::class.java).asKotlinLogger() } } val KotlinLibrary.compatibilityInfo: KlibCompatibilityInfo get() { val hasPre14Manifest = safeRead(false) { has_pre_1_4_manifest } if (hasPre14Manifest) return KlibCompatibilityInfo.Pre14Layout val metadataVersion = safeRead(null) { metadataVersion } return when { metadataVersion == null -> { // Too old KLIB format, even doesn't have metadata version KlibCompatibilityInfo.IncompatibleMetadata(true) } !metadataVersion.isCompatible() -> { val isOlder = metadataVersion.isAtLeast(KlibMetadataVersion.INSTANCE) KlibCompatibilityInfo.IncompatibleMetadata(!isOlder) } else -> KlibCompatibilityInfo.Compatible } }
apache-2.0
6fdc8278ec83b88bcad7b516d87f7c62
40.264706
124
0.742959
5.017889
false
false
false
false
fvasco/pinpoi
app/src/main/java/io/github/fvasco/pinpoi/importer/ZipImporter.kt
1
1437
package io.github.fvasco.pinpoi.importer import android.util.Log import io.github.fvasco.pinpoi.util.ZipGuardInputStream import java.io.IOException import java.io.InputStream import java.util.* import java.util.zip.ZipEntry import java.util.zip.ZipInputStream /** * Import ZIP collection and KMZ file * @author Francesco Vasco */ class ZipImporter : AbstractImporter() { @Throws(IOException::class) override fun importImpl(inputStream: InputStream) { val zipInputStream = ZipInputStream(inputStream) var zipEntry: ZipEntry? = zipInputStream.nextEntry while (zipEntry != null) { val entryName = zipEntry.name val filename = entryName.substringAfterLast('/') val extension = filename.substringAfterLast('.').lowercase() if (!zipEntry.isDirectory && !filename.startsWith(".") && (fileFormatFilter == FileFormatFilter.NONE || extension in fileFormatFilter.validExtensions) ) { val importer = ImporterFacade.createImporter(entryName, null, fileFormatFilter) if (importer != null) { Log.d(ZipImporter::class.java.simpleName, "Import entry $entryName") importer.configureFrom(this) importer.importImpl(ZipGuardInputStream(zipInputStream)) } } zipEntry = zipInputStream.nextEntry } } }
gpl-3.0
659953d38f60d4fad700df57f80ee0ee
35.846154
111
0.651357
5.077739
false
false
false
false
GunoH/intellij-community
platform/vcs-log/impl/src/com/intellij/vcs/log/data/ContainingBranchesGetter.kt
2
8031
// 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.vcs.log.data import com.github.benmanes.caffeine.cache.Caffeine import com.intellij.diagnostic.telemetry.TraceManager import com.intellij.diagnostic.telemetry.computeWithSpan import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.progress.util.BackgroundTaskUtil import com.intellij.openapi.vcs.VcsException import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.util.ui.UIUtil import com.intellij.vcs.log.* import com.intellij.vcs.log.graph.impl.facade.PermanentGraphImpl import com.intellij.vcs.log.util.SequentialLimitedLifoExecutor import org.jetbrains.annotations.CalledInAny import java.awt.EventQueue /** * Provides capabilities to asynchronously calculate "contained in branches" information. */ class ContainingBranchesGetter internal constructor(private val logData: VcsLogData, parentDisposable: Disposable) { private val taskExecutor: SequentialLimitedLifoExecutor<CachingTask> // other fields accessed only from EDT private val loadingFinishedListeners: MutableList<Runnable> = ArrayList() private val cache = Caffeine.newBuilder() .maximumSize(2000) .build<CommitId, List<String>>() private val conditionsCache: CurrentBranchConditionCache private var currentBranchesChecksum = 0 init { conditionsCache = CurrentBranchConditionCache(logData, parentDisposable) taskExecutor = SequentialLimitedLifoExecutor(parentDisposable, 10, CachingTask::run) logData.addDataPackChangeListener { dataPack: DataPack -> val checksum = dataPack.refsModel.branches.hashCode() if (currentBranchesChecksum != checksum) { // clear cache if branches set changed after refresh clearCache() } currentBranchesChecksum = checksum } } @RequiresEdt private fun cache(commitId: CommitId, branches: List<String>, branchesChecksum: Int) { if (branchesChecksum == currentBranchesChecksum) { cache.put(commitId, branches) notifyListeners() } } @RequiresEdt private fun clearCache() { cache.invalidateAll() taskExecutor.clear() conditionsCache.clear() // re-request containing branches information for the commit user (possibly) currently stays on ApplicationManager.getApplication().invokeLater { notifyListeners() } } /** * This task will be executed each time the calculating process completes. */ fun addTaskCompletedListener(runnable: Runnable) { LOG.assertTrue(EventQueue.isDispatchThread()) loadingFinishedListeners.add(runnable) } fun removeTaskCompletedListener(runnable: Runnable) { LOG.assertTrue(EventQueue.isDispatchThread()) loadingFinishedListeners.remove(runnable) } private fun notifyListeners() { LOG.assertTrue(EventQueue.isDispatchThread()) for (listener in loadingFinishedListeners) { listener.run() } } /** * Returns the alphabetically sorted list of branches containing the specified node, if this information is ready; * if it is not available, starts calculating in the background and returns null. */ fun requestContainingBranches(root: VirtualFile, hash: Hash): List<String>? { LOG.assertTrue(EventQueue.isDispatchThread()) val refs = getContainingBranchesFromCache(root, hash) if (refs == null) { taskExecutor.queue(CachingTask(createTask(root, hash, logData.dataPack), currentBranchesChecksum)) } return refs } fun getContainingBranchesFromCache(root: VirtualFile, hash: Hash): List<String>? { LOG.assertTrue(EventQueue.isDispatchThread()) return cache.getIfPresent(CommitId(hash, root)) } @CalledInAny fun getContainingBranchesQuickly(root: VirtualFile, hash: Hash): List<String>? { val cachedBranches = cache.getIfPresent(CommitId(hash, root)) if (cachedBranches != null) return cachedBranches val dataPack = logData.dataPack val commitIndex = logData.getCommitIndex(hash, root) val pg = dataPack.permanentGraph if (pg is PermanentGraphImpl<Int>) { val nodeId = pg.permanentCommitsInfo.getNodeId(commitIndex) if (nodeId < 10000 && canUseGraphForComputation(logData.getLogProvider(root))) { return getContainingBranchesSynchronously(dataPack, root, hash) } } return BackgroundTaskUtil.tryComputeFast({ return@tryComputeFast getContainingBranchesSynchronously(dataPack, root, hash) }, 100) } @CalledInAny fun getContainedInCurrentBranchCondition(root: VirtualFile) = conditionsCache.getContainedInCurrentBranchCondition(root) @CalledInAny fun getContainingBranchesSynchronously(root: VirtualFile, hash: Hash): List<String> { return getContainingBranchesSynchronously(logData.dataPack, root, hash) } @CalledInAny private fun getContainingBranchesSynchronously(dataPack: DataPack, root: VirtualFile, hash: Hash): List<String> { return CachingTask(createTask(root, hash, dataPack), dataPack.refsModel.branches.hashCode()).run() } private fun createTask(root: VirtualFile, hash: Hash, dataPack: DataPack): Task { val provider = logData.getLogProvider(root) return if (canUseGraphForComputation(provider)) { GraphTask(provider, root, hash, dataPack) } else ProviderTask(provider, root, hash) } private abstract class Task(private val myProvider: VcsLogProvider, val myRoot: VirtualFile, val myHash: Hash) { @Throws(VcsException::class) fun getContainingBranches(): List<String> { return computeWithSpan(TraceManager.getTracer("vcs"), "get containing branches") { try { getContainingBranches(myProvider, myRoot, myHash) } catch (e: VcsException) { LOG.warn(e) emptyList() } } } @Throws(VcsException::class) protected abstract fun getContainingBranches(provider: VcsLogProvider, root: VirtualFile, hash: Hash): List<String> } private inner class GraphTask constructor(provider: VcsLogProvider, root: VirtualFile, hash: Hash, dataPack: DataPack) : Task(provider, root, hash) { private val graph = dataPack.permanentGraph private val refs = dataPack.refsModel override fun getContainingBranches(provider: VcsLogProvider, root: VirtualFile, hash: Hash): List<String> { val commitIndex = logData.getCommitIndex(hash, root) return graph.getContainingBranches(commitIndex) .map(::getBranchesRefs) .flatten() .sortedWith(provider.referenceManager.labelsOrderComparator) .map(VcsRef::getName) } private fun getBranchesRefs(branchIndex: Int) = refs.refsToCommit(branchIndex).filter { it.type.isBranch } } private class ProviderTask(provider: VcsLogProvider, root: VirtualFile, hash: Hash) : Task(provider, root, hash) { @Throws(VcsException::class) override fun getContainingBranches(provider: VcsLogProvider, root: VirtualFile, hash: Hash) = provider.getContainingBranches(root, hash).sorted() } private inner class CachingTask(private val delegate: Task, private val branchesChecksum: Int) { fun run(): List<String> { val branches = delegate.getContainingBranches() val commitId = CommitId(delegate.myHash, delegate.myRoot) UIUtil.invokeLaterIfNeeded { cache(commitId, branches, branchesChecksum) } return branches } } companion object { private val LOG = Logger.getInstance(ContainingBranchesGetter::class.java) private fun canUseGraphForComputation(logProvider: VcsLogProvider) = VcsLogProperties.LIGHTWEIGHT_BRANCHES.getOrDefault(logProvider) } }
apache-2.0
f679143718fc34156ecae4886c8999ee
37.990291
158
0.731665
4.920956
false
false
false
false
dpisarenko/econsim-tr01
src/main/java/cc/altruix/econsimtr01/flourprod/FlourProductionSimulationAccountant.kt
1
3341
/* * Copyright 2012-2016 Dmitri Pisarenko * * WWW: http://altruix.cc * E-Mail: dp@altruix.co * Skype: dp118m (voice calls must be scheduled in advance) * * Physical address: * * 4-i Rostovskii pereulok 2/1/20 * 119121 Moscow * Russian Federation * * This file is part of econsim-tr01. * * econsim-tr01 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * econsim-tr01 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with econsim-tr01. If not, see <http://www.gnu.org/licenses/>. * */ package cc.altruix.econsimtr01.flourprod import cc.altruix.econsimtr01.* import cc.altruix.econsimtr01.ch0202.SimResRow import cc.altruix.econsimtr01.ch03.AgriculturalSimulationAccountant import cc.altruix.econsimtr01.ch03.AgriculturalSimulationRowField import cc.altruix.econsimtr01.ch03.Shack import org.joda.time.DateTime import org.slf4j.LoggerFactory import java.util.* /** * @author Dmitri Pisarenko (dp@altruix.co) * @version $Id$ * @since 1.0 */ open class FlourProductionSimulationAccountant( resultsStorage: MutableMap<DateTime, SimResRow<FlourProductionSimRowField>>, scenarioName: String, val asacc:AgriculturalSimulationAccountant = AgriculturalSimulationAccountant( resultsStorage = HashMap<DateTime, SimResRow<AgriculturalSimulationRowField>>(), scenarioName = "" ) ) : AbstractAccountant2<FlourProductionSimRowField>( resultsStorage, scenarioName ) { val LOGGER = LoggerFactory.getLogger( FlourProductionSimulationAccountant::class.java ) override fun timeToMeasure(time: DateTime): Boolean = time.evenHourAndMinute(0, 0) override fun saveRowData( agents: List<IAgent>, target: MutableMap<FlourProductionSimRowField, Double>) { target.put(FlourProductionSimRowField.SEEDS_IN_SHACK, asacc.calculateSeedsInShack(agents)) target.put(FlourProductionSimRowField.FIELD_AREA_WITH_SEEDS, asacc.calculateFieldAreaWithSeeds(agents)) target.put(FlourProductionSimRowField.EMPTY_FIELD_AREA, asacc.calculateEmptyFieldArea(agents)) target.put(FlourProductionSimRowField.FIELD_AREA_WITH_CROP, asacc.calculateFieldAreaWithCrop(agents)) target.put(FlourProductionSimRowField.FLOUR_IN_SHACK, calculateFieldInShack(agents)) } open internal fun calculateFieldInShack(agents: List<IAgent>): Double { val shack = findAgent(Shack.ID, agents) as DefaultAgent if (shack == null) { LOGGER.error("Can't find the shack") return 0.0 } return shack.amount(FlourProductionSimulationParametersProvider .RESOURCE_FLOUR.id) } }
gpl-3.0
55cf2d9d3a4e4b9f4ccb0d76d53035c3
34.315217
75
0.683029
4.646732
false
false
false
false
GunoH/intellij-community
plugins/kotlin/code-insight/kotlin.code-insight.k2/src/org/jetbrains/kotlin/idea/k2/codeinsight/structureView/KotlinFirStructureViewElement.kt
1
6223
// 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.k2.codeinsight.structureView import com.intellij.ide.structureView.StructureViewTreeElement import com.intellij.ide.structureView.impl.common.PsiTreeElementBase import com.intellij.navigation.ItemPresentation import com.intellij.openapi.project.DumbService import com.intellij.openapi.ui.Queryable import com.intellij.psi.NavigatablePsiElement import com.intellij.psi.PsiElement import org.jetbrains.annotations.TestOnly import org.jetbrains.kotlin.analysis.api.analyze import org.jetbrains.kotlin.analysis.api.symbols.KtSymbol import org.jetbrains.kotlin.analysis.api.symbols.markers.KtSymbolWithVisibility import org.jetbrains.kotlin.analysis.api.symbols.pointers.KtSymbolPointer import org.jetbrains.kotlin.descriptors.Visibilities import org.jetbrains.kotlin.idea.structureView.AbstractKotlinStructureViewElement import com.intellij.openapi.application.runReadAction import org.jetbrains.kotlin.psi.* import javax.swing.Icon import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty class KotlinFirStructureViewElement( override val element: NavigatablePsiElement, ktElement : KtElement, private val isInherited: Boolean = false ) : PsiTreeElementBase<NavigatablePsiElement>(element), AbstractKotlinStructureViewElement, Queryable { private var kotlinPresentation by AssignableLazyProperty { KotlinFirStructureElementPresentation(isInherited, element, ktElement, createSymbolAndThen { it.createPointer() }) } private var visibility by AssignableLazyProperty { analyze(ktElement) { Visibility(createSymbolAndThen { it }) } } /** * @param element represents node element, can be in current file or from super class (e.g. java) * @param inheritElement represents element in the current kotlin file */ constructor(element: NavigatablePsiElement, inheritElement: KtElement, descriptor: KtSymbolPointer<*>, isInherited: Boolean) : this(element, inheritElement, isInherited) { if (element !is KtElement) { // Avoid storing descriptor in fields kotlinPresentation = KotlinFirStructureElementPresentation(isInherited, element, inheritElement, descriptor) analyze(inheritElement) { visibility = Visibility(descriptor.restoreSymbol()) } } } override val accessLevel: Int? get() = visibility.accessLevel override val isPublic: Boolean get() = visibility.isPublic override fun getPresentation(): ItemPresentation = kotlinPresentation override fun getLocationString(): String? = kotlinPresentation.locationString override fun getIcon(open: Boolean): Icon? = kotlinPresentation.getIcon(open) override fun getPresentableText(): String? = kotlinPresentation.presentableText @TestOnly override fun putInfo(info: MutableMap<in String, in String?>) { // Sanity check for API consistency assert(presentation.presentableText == presentableText) { "Two different ways of getting presentableText" } assert(presentation.locationString == locationString) { "Two different ways of getting locationString" } info["text"] = presentableText info["location"] = locationString } override fun getChildrenBase(): Collection<StructureViewTreeElement> { val children = when (val element = element) { is KtFile -> element.declarations is KtClass -> element.getStructureDeclarations() is KtClassOrObject -> element.declarations is KtFunction, is KtClassInitializer, is KtProperty -> element.collectLocalDeclarations() else -> emptyList() } return children.map { KotlinFirStructureViewElement(it, it, isInherited = false) } } private fun PsiElement.collectLocalDeclarations(): List<KtDeclaration> { val result = mutableListOf<KtDeclaration>() acceptChildren(object : KtTreeVisitorVoid() { override fun visitClassOrObject(classOrObject: KtClassOrObject) { result.add(classOrObject) } override fun visitNamedFunction(function: KtNamedFunction) { result.add(function) } }) return result } private fun <T> createSymbolAndThen(modifier : (KtSymbol) -> T): T? { val element = element return when { !element.isValid -> null element !is KtDeclaration -> null element is KtAnonymousInitializer -> null else -> runReadAction { if (!DumbService.isDumb(element.getProject())) { analyze(element) { modifier.invoke(element.getSymbol()) } } else null } } } class Visibility(symbol: KtSymbol?) { private val visibility: org.jetbrains.kotlin.descriptors.Visibility? = (symbol as? KtSymbolWithVisibility)?.visibility val isPublic: Boolean get() = visibility == Visibilities.Public val accessLevel: Int? get() = when { visibility == Visibilities.Public -> 1 visibility == Visibilities.Internal -> 2 visibility == Visibilities.Protected -> 3 visibility?.let { Visibilities.isPrivate(it) } == true -> 4 else -> null } } } private class AssignableLazyProperty<in R, T : Any>(val init: () -> T) : ReadWriteProperty<R, T> { private var _value: T? = null override fun getValue(thisRef: R, property: KProperty<*>): T { return _value ?: init().also { _value = it } } override fun setValue(thisRef: R, property: KProperty<*>, value: T) { _value = value } } fun KtClassOrObject.getStructureDeclarations() = buildList { primaryConstructor?.let { add(it) } primaryConstructorParameters.filterTo(this) { it.hasValOrVar() } addAll(declarations) }
apache-2.0
11ac40a71217feb8cb85d0049f0bdc2a
39.148387
175
0.676683
5.439685
false
false
false
false
GunoH/intellij-community
plugins/git4idea/src/git4idea/ui/ComboBoxWithAutoCompletion.kt
7
6859
// 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 git4idea.ui import com.intellij.codeInsight.AutoPopupController import com.intellij.codeInsight.completion.CompletionType import com.intellij.openapi.actionSystem.CustomShortcutSet import com.intellij.openapi.actionSystem.IdeActions import com.intellij.openapi.editor.SpellCheckingEditorCustomizationProvider import com.intellij.openapi.editor.event.BulkAwareDocumentListener import com.intellij.openapi.editor.event.DocumentEvent import com.intellij.openapi.editor.event.DocumentListener import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.fileTypes.PlainTextLanguage import com.intellij.openapi.keymap.KeymapManager import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.ui.ComboBox import com.intellij.ui.ComboBoxCompositeEditor import com.intellij.ui.EditorTextField import com.intellij.ui.LanguageTextField import com.intellij.ui.TextFieldWithAutoCompletion.installCompletion import com.intellij.ui.TextFieldWithAutoCompletionListProvider import org.jetbrains.annotations.Nls import javax.swing.ComboBoxModel import javax.swing.JComponent import javax.swing.JLabel import javax.swing.event.ListDataEvent import javax.swing.event.ListDataListener class ComboBoxWithAutoCompletion<E>(model: ComboBoxModel<E>, private val project: Project) : ComboBox<E>(model) { private val autoPopupController = AutoPopupController.getInstance(project) private val completionProvider = object : TextFieldWithAutoCompletionListProvider<E>(emptyList()) { override fun getLookupString(item: E) = item.toString() } private var myEditor: EditorEx? = null private var myEditableComponent: EditorTextField? = null private var selectingItem = false @Nls private var myPlaceHolder: String? = null init { isEditable = true initEditor() subscribeForModelChange(model) } override fun setSelectedItem(anObject: Any?) { selectingItem = true super.setSelectedItem(anObject) editor.item = anObject selectingItem = false } override fun getSelectedItem(): Any? { val text = getText() return if (selectingItem || text.isNullOrEmpty()) super.getSelectedItem() else getItems().find { item -> item.toString() == text } } override fun requestFocus() { myEditableComponent?.requestFocus() } @Nls fun getText(): String? { return myEditor?.document?.text } fun updatePreserving(update: () -> Unit) { val oldItem = item if (oldItem != null) { update() item = oldItem return } val editorField = myEditableComponent val editor = editorField?.editor if (editor != null) { val oldText = editorField.text val offset = editor.caretModel.offset val selectionStart = editor.selectionModel.selectionStart val selectionStartPosition = editor.selectionModel.selectionStartPosition val selectionEnd = editor.selectionModel.selectionEnd val selectionEndPosition = editor.selectionModel.selectionEndPosition update() editorField.text = oldText editor.caretModel.moveToOffset(offset) editor.selectionModel.setSelection(selectionStartPosition, selectionStart, selectionEndPosition, selectionEnd) return } update() } fun setPlaceholder(@Nls placeHolder: String) { myPlaceHolder = placeHolder myEditor?.apply { setPlaceholder(myPlaceHolder) } } fun selectAll() { myEditableComponent?.selectAll() } fun addDocumentListener(listener: DocumentListener) { myEditableComponent?.addDocumentListener(listener) } fun removeDocumentListener(listener: DocumentListener) { myEditableComponent?.removeDocumentListener(listener) } private fun initEditor() { val editableComponent = createEditableComponent() myEditableComponent = editableComponent editableComponent.document.addDocumentListener(object : BulkAwareDocumentListener.Simple { override fun documentChanged(e: DocumentEvent) { if (!selectingItem && !isValueReplaced(e)) { showCompletion() } } }) editor = ComboBoxCompositeEditor<String, EditorTextField>(editableComponent, JLabel()) installCompletion(editableComponent.document, project, completionProvider, true) installForceCompletionShortCut(editableComponent) } private fun installForceCompletionShortCut(editableComponent: JComponent) { val completionShortcutSet = getCompletionShortcuts().firstOrNull()?.let { CustomShortcutSet(it) } ?: return DumbAwareAction.create { showCompletion() }.registerCustomShortcutSet(completionShortcutSet, editableComponent) } private fun showCompletion() { if (myEditor != null) { hidePopup() autoPopupController.scheduleAutoPopup(myEditor!!, CompletionType.BASIC) { true } } } private fun getCompletionShortcuts() = KeymapManager.getInstance().activeKeymap.getShortcuts(IdeActions.ACTION_CODE_COMPLETION) private fun createEditableComponent() = object : LanguageTextField(PlainTextLanguage.INSTANCE, project, "") { override fun createEditor(): EditorEx { myEditor = super.createEditor().apply { setShowPlaceholderWhenFocused(true) setPlaceholder(myPlaceHolder) SpellCheckingEditorCustomizationProvider.getInstance().disabledCustomization?.customize(this) } return myEditor!! } } private fun subscribeForModelChange(model: ComboBoxModel<E>) { model.addListDataListener(object : ListDataListener { override fun intervalAdded(e: ListDataEvent?) { completionProvider.setItems(collectItems()) } override fun intervalRemoved(e: ListDataEvent?) { completionProvider.setItems(collectItems()) } override fun contentsChanged(e: ListDataEvent?) { completionProvider.setItems(collectItems()) } private fun collectItems(): List<E> { val items = mutableListOf<E>() for (i in 0 until model.size) { items += model.getElementAt(i) } return items } }) } private fun isValueReplaced(e: DocumentEvent) = e.isWholeTextReplaced || isFieldCleared(e) || isItemSelected(e) private fun isFieldCleared(e: DocumentEvent) = e.oldLength != 0 && getCurrentText(e).isEmpty() private fun isItemSelected(e: DocumentEvent) = e.oldLength == 0 && getCurrentText(e).isNotEmpty() && getCurrentText(e) in getItems().map { it.toString() } private fun getCurrentText(e: DocumentEvent) = getText() ?: e.newFragment private fun getItems() = (0 until itemCount).map { getItemAt(it) } }
apache-2.0
0f0c3991f63de1da9eecfc57db061043
32.627451
140
0.734218
5.047093
false
false
false
false
smmribeiro/intellij-community
python/python-psi-impl/src/com/jetbrains/python/psi/resolve/IPythonBuiltinConstants.kt
1
704
package com.jetbrains.python.psi.resolve object IPythonBuiltinConstants { const val DISPLAY = "display" const val GET_IPYTHON = "get_ipython" const val IN = "In" const val OUT = "Out" const val IPYTHON_PACKAGE = "IPython" const val CORE_PACKAGE = "core" const val HISTORY_MANAGER = "HistoryManager" const val OUT_HIST_DICT = "output_hist" const val IN_HIST_DICT = "input_hist_parsed" const val DISPLAY_DOTTED_PATH = "IPython.core.display.display" const val GET_IPYTHON_DOTTED_PATH = "IPython.core.getipython.get_ipython" const val HISTORY_MANAGER_DOTTED_PATH = "IPython.core.history.HistoryManager" const val DOUBLE_UNDERSCORE = "__" const val TRIPLE_UNDERSCORE = "___" }
apache-2.0
d245faa4d1c664375dba409825282ea1
31.045455
79
0.725852
3.52
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/quickfix/deprecatedSymbolUsage/optionalParameters/optionalParameterAndLambdaComplex.kt
9
1450
// "Replace with 'addA(d(createDummy, dummyParam1, initDummy = initDummy), dummyParam)'" "true" // WITH_STDLIB typealias NewDummyRef<V> = (Any) -> V inline fun <A : Any> Any.d( createDummy: NewDummyRef<A>, dummyParam1: Int = 0, dummyParam2: Int = 0, initDummy: A.() -> Unit = {} ) = createDummy(this).also(initDummy).also { dummyParam1 + dummyParam2 } @Deprecated("Use d instead", ReplaceWith("addA(d(createDummy, dummyParam1, initDummy = initDummy), dummyParam)")) inline fun <A : Any> MutableList<A>.addA( createDummy: NewDummyRef<A>, dummyParam1: Int = 0, dummyParam: Unit, initDummy: A.() -> Unit = {} ) = createDummy(this).also(initDummy).also { dummyParam1 }.also { add(it) } @Deprecated("Use d instead", ReplaceWith("addA(d(createDummy, dummyParam1, dummyParam2, initDummy), dummyParam)")) inline fun <A : Any> MutableList<A>.addA( createDummy: NewDummyRef<A>, dummyParam1: Int = 0, dummyParam2: Int = 0, dummyParam: Unit, initDummy: A.() -> Unit = {} ) = createDummy(this).also(initDummy).also { dummyParam1 + dummyParam2 }.also { add(it) } @Suppress("NOTHING_TO_INLINE") inline fun <A : Any> MutableList<A>.addA(a: A, dummyParam: Unit): A = a.also { add(a) } fun createHi(any: Any) = "Hi $any" val unDeprecateMe = mutableListOf("Hello").apply { addA<caret>(::createHi, 1, Unit) { // Run the quick fix from the IDE and watch it produce broken code. println("Yo") } }
apache-2.0
1ac52918bb485b74abc1b65f97831240
36.179487
114
0.662069
3.403756
false
false
false
false
80998062/Fank
presentation/src/main/java/com/sinyuk/fanfou/util/linkfy/HtmlUtils.kt
1
4523
/* * * * Apache License * * * * Copyright [2017] Sinyuk * * * * 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.sinyuk.fanfou.util.linkfy import android.content.res.ColorStateList import android.os.Build import android.support.annotation.ColorInt import android.text.* import android.text.style.URLSpan import android.widget.TextView /** * Utility methods for working with HTML. */ object HtmlUtils { /** * Work around some 'features' of TextView and URLSpans. i.e. vanilla URLSpans do not react to * touch so we replace them with our own [TouchableUrlSpan] * & [LinkTouchMovementMethod] to fix this. * * * Setting a custom MovementMethod on a TextView also alters touch handling (see * TextView#fixFocusableAndClickableSettings) so we need to correct this. * * @param textView the text view * @param input the input */ fun setTextWithNiceLinks(textView: TextView, input: CharSequence) { textView.text = input textView.movementMethod = LinkTouchMovementMethod.getInstance() textView.isFocusable = false textView.isClickable = false textView.isLongClickable = false } /** * Parse the given input using [TouchableUrlSpan]s rather than vanilla [URLSpan]s * so that they respond to touch. * * @param input the input * @param linkTextColor the link text color * @param linkHighlightColor the link highlight color * @return the spannable string builder */ fun parseHtml(input: String, linkTextColor: ColorStateList, @ColorInt linkHighlightColor: Int): SpannableStringBuilder { var spanned = fromHtml(input) // strip any trailing newlines while (spanned[spanned.length - 1] == '\n') { spanned = spanned.delete(spanned.length - 1, spanned.length) } return linkifyPlainLinks(spanned, linkTextColor, linkHighlightColor) } /** * Parse and set text. * * @param textView the text view * @param input the input */ fun parseAndSetText(textView: TextView, input: String) { if (TextUtils.isEmpty(input)) return setTextWithNiceLinks(textView, parseHtml(input, textView.linkTextColors, textView.highlightColor)) } /** * 把[URLSpan]转换成[TouchableUrlSpan] * * @param input the input * @param linkTextColor the link text color * @param linkHighlightColor the link highlight color * @return the spannable string builder */ fun linkifyPlainLinks(input: CharSequence, linkTextColor: ColorStateList, @ColorInt linkHighlightColor: Int): SpannableStringBuilder { val plainLinks = SpannableString(input) // copy of input // Linkify doesn't seem to work as expected on M+ // TODO: figure out why // Linkify.addLinks(plainLinks, Linkify.WEB_URLS); val urlSpans = plainLinks.getSpans(0, plainLinks.length, URLSpan::class.java) // add any plain links to the output val ssb = SpannableStringBuilder(input) for (urlSpan in urlSpans) { ssb.removeSpan(urlSpan) ssb.setSpan(TouchableUrlSpan( urlSpan.url, linkTextColor, linkHighlightColor), plainLinks.getSpanStart(urlSpan), plainLinks.getSpanEnd(urlSpan), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) } return ssb } /** * From html spannable string builder. * * @param input the input * @return the spannable string builder */ fun fromHtml(input: String): SpannableStringBuilder { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Html.fromHtml(input, Html.FROM_HTML_MODE_LEGACY) as SpannableStringBuilder } else { Html.fromHtml(input) as SpannableStringBuilder } } }
mit
1e9419f9863e4e8086c25cc8932d7101
31.956204
138
0.650277
4.588415
false
false
false
false
pinkjersey/mtlshipback
src/main/kotlin/com/ipmus/JerseyApp.kt
1
2706
package com.ipmus /** * Created by mozturk on 7/26/2017. */ import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.module.kotlin.KotlinModule import com.ipmus.filter.AuthFilter import com.ipmus.filter.CORSResponseFilter import com.ipmus.resources.* import com.ipmus.util.DigestPassword import org.glassfish.jersey.server.ResourceConfig import org.slf4j.LoggerFactory import java.io.File import javax.ws.rs.ApplicationPath import javax.ws.rs.ext.ContextResolver @ApplicationPath("/") class JerseyApp : ResourceConfig(setOf(ItemResource::class.java, CustomerResource::class.java, BrokerResource::class.java, VesselResource::class.java, VendorResource::class.java, DesignResource::class.java, DesignColorResource::class.java, ShipmentTypeResource::class.java, ShipmentResource::class.java, ContainerResource::class.java, PurchaseOrderResource::class.java, OurPurchaseOrderResource::class.java, VendorInvoiceResource::class.java, LoginResource::class.java, OurInvoiceResource::class.java)) { private val logger = LoggerFactory.getLogger(JerseyApp::class.java) init { register(AuthFilter::class.java) register(CORSResponseFilter::class.java) register(ContextResolver<ObjectMapper> { ObjectMapper().registerModule(KotlinModule()) }) val opsys = System.getProperty("os.name").toLowerCase() logger.info("JerseyApp init $opsys") val userFile = if (opsys.contains("windows")) { "c:/temp/users.txt" } else { "/home/ubuntu/users.txt" } initUsers(userFile) } private fun initUsers(filename: String) { val userType = "User" val es = GenericResource.entityStore val done = es.computeInReadonlyTransaction { txn -> val loadedUsers = txn.getAll(userType) if (!loadedUsers.isEmpty) { logger.info("Users exist. Doing nothing") true } else { false } } if (done) { return } logger.info("Users not initialized, initializing") val users = File(filename).readLines() users.forEach { val tokens = it.split("\t") if (tokens.size == 3) { logger.info("Adding user ${tokens[1]}") es.executeInTransaction { txn -> val user = txn.newEntity(userType) user.setProperty("email", tokens[0]) user.setProperty("name", tokens[1]) user.setProperty("pass", DigestPassword.doWork(tokens[2])) } } } } }
mit
aefc8814bb66f6ac3822550d84e3516a
34.142857
107
0.631929
4.357488
false
false
false
false
DrOptix/strava-intervall
strava-intervall/src/main/kotlin/com/worldexplorerblog/stravaintervall/layouts/CheckableRelativeLayout.kt
1
1054
package com.worldexplorerblog.stravaintervall.layouts import android.content.Context import android.util.AttributeSet import android.widget.Checkable import android.widget.RelativeLayout class CheckableRelativeLayout : RelativeLayout, Checkable { private var checkedLayout = false constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet) : super(context, attrs) override fun onCreateDrawableState(extraSpace: Int): IntArray? { val drawableState = super.onCreateDrawableState(extraSpace + 1) if (checkedLayout) { mergeDrawableStates(drawableState, intArrayOf(android.R.attr.state_checked)) } return drawableState } override fun toggle() { checkedLayout = !checkedLayout } override fun isChecked(): Boolean { return checkedLayout } override fun setChecked(checked: Boolean) { if (checkedLayout != checked) { checkedLayout = checked refreshDrawableState() } } }
gpl-3.0
13d73d786bf70bd0910a739373dc5ff6
25.375
88
0.695446
5.116505
false
false
false
false
joaomneto/TitanCompanion
src/main/java/pt/joaomneto/titancompanion/adventurecreation/AdventureCreation.kt
1
6280
package pt.joaomneto.titancompanion.adventurecreation import android.app.AlertDialog import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.View import android.widget.EditText import android.widget.TextView import java.io.BufferedWriter import java.io.File import java.io.FileWriter import java.io.IOException import pt.joaomneto.titancompanion.BaseFragmentActivity import pt.joaomneto.titancompanion.GamebookSelectionActivity import pt.joaomneto.titancompanion.LoadAdventureActivity import pt.joaomneto.titancompanion.R import pt.joaomneto.titancompanion.adventurecreation.impl.fragments.VitalStatisticsFragment import pt.joaomneto.titancompanion.consts.Constants import pt.joaomneto.titancompanion.consts.FightingFantasyGamebook import pt.joaomneto.titancompanion.util.AdventureFragmentRunner import pt.joaomneto.titancompanion.util.DiceRoller abstract class AdventureCreation( override val fragmentConfiguration: Array<AdventureFragmentRunner> = DEFAULT_FRAGMENTS ) : BaseFragmentActivity(fragmentConfiguration, R.layout.activity_adventure_creation) { companion object { const val NO_PARAMETERS_TO_VALIDATE = "" val DEFAULT_FRAGMENTS = arrayOf( AdventureFragmentRunner(R.string.title_adventure_creation_vitalstats, VitalStatisticsFragment::class) ) } protected var skill = -1 protected var luck = -1 protected var stamina = -1 protected var adventureName: String? = null var gamebook: FightingFantasyGamebook? = null private set override fun onCreate(savedInstanceState: Bundle?) { gamebook = FightingFantasyGamebook.values()[ intent.getIntExtra( GamebookSelectionActivity.GAMEBOOK_ID, -1 ) ] super.onCreate(savedInstanceState) } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.adventure_creation, menu) return true } fun rollStats(view: View) { skill = DiceRoller.rollD6() + 6 luck = DiceRoller.rollD6() + 6 stamina = DiceRoller.roll2D6().sum + 12 rollGamebookSpecificStats(view) val skillValue = findViewById<TextView>(R.id.skillValue) val staminaValue = findViewById<TextView>(R.id.staminaValue) val luckValue = findViewById<TextView>(R.id.luckValue) skillValue?.text = skill.toString() staminaValue?.text = stamina.toString() luckValue?.text = luck.toString() } fun saveAdventure() { try { val et = findViewById<EditText>(R.id.adventureNameInput) adventureName = et.text.toString() try { validateCreationParameters() } catch (e: IllegalArgumentException) { showAlert(e.message!!) return } val relDir = ( "save_" + gamebook!!.initials + "_" + adventureName!!.replace(' ', '-') ) var dir = File(filesDir, "ffgbutil") dir = File(dir, relDir) if (!dir.exists()) { dir.mkdirs() } else { dir.deleteRecursively() } val file = File(dir, "initial.xml") val bw = BufferedWriter(FileWriter(file)) bw.write("gamebook=" + gamebook + "\n") bw.write("name=" + adventureName + "\n") bw.write("initialSkill=" + skill + "\n") bw.write("initialLuck=" + luck + "\n") bw.write("initialStamina=" + stamina + "\n") bw.write("currentSkill=" + skill + "\n") bw.write("currentLuck=" + luck + "\n") bw.write("currentStamina=" + stamina + "\n") bw.write("currentReference=1\n") bw.write("equipment=\n") bw.write("notes=\n") bw.write("gold=0\n") storeAdventureSpecificValuesInFile(bw) bw.close() val intent = Intent( this, Constants .getRunActivity(this, gamebook!!) ) intent.putExtra( LoadAdventureActivity.ADVENTURE_SAVEGAME_CONTENT, File(File(File(filesDir, "ffgbutil"), dir.name), "initial.xml").readText() ) intent.putExtra(LoadAdventureActivity.ADVENTURE_NAME, relDir) startActivity(intent) } catch (e: Exception) { throw IllegalStateException(e) } } fun showAlert(message: String) { val builder = AlertDialog.Builder(this) builder.setTitle(R.string.result).setMessage(message).setCancelable(false) .setNegativeButton(R.string.close) { dialog, _ -> dialog.cancel() } val alert = builder.create() alert.show() } @Throws(IllegalArgumentException::class) private fun validateCreationParameters() { val sb = StringBuilder() var error = false sb.append(getString(R.string.someParametersMIssing)) if (this.stamina < 0) { sb.append(getString(R.string.skill2) + ", " + getString(R.string.stamina2) + " and " + getString(R.string.luck2)) error = true } sb.append(if (error) "; " else "") if (this.adventureName == null || this.adventureName!!.trim { it <= ' ' }.isEmpty()) { sb.append(getString(R.string.adventureName)) error = true } val specificParameters = validateCreationSpecificParameters() if (specificParameters != null && specificParameters.isNotEmpty()) { sb.append(if (error) "; " else "") error = true sb.append(specificParameters) } sb.append(")") if (error) { throw IllegalArgumentException(sb.toString()) } } @Throws(IOException::class) open fun storeAdventureSpecificValuesInFile(bw: BufferedWriter) { } open fun rollGamebookSpecificStats(view: View) {} open fun validateCreationSpecificParameters(): String? { return AdventureCreation.Companion.NO_PARAMETERS_TO_VALIDATE } }
lgpl-3.0
5b94a0fd6dc11586cc4912ea962bd7d9
33.130435
125
0.619268
4.676098
false
false
false
false
batagliao/onebible.android
app/src/main/java/com/claraboia/bibleandroid/helpers/CheatSheetHelper.kt
1
5178
package com.claraboia.bibleandroid.helpers /* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import android.content.Context import android.graphics.Rect import android.text.TextUtils import android.view.Gravity import android.view.View import android.widget.Toast /** * Helper class for showing cheat sheets (tooltips) for icon-only UI elements on long-press. This is * already default platform behavior for icon-only [android.app.ActionBar] items and tabs. * This class provides this behavior for any other such UI element. * * Based on the original action bar implementation in [ * ActionMenuItemView.java](https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/java/com/android/internal/view/menu/ActionMenuItemView.java). */ object CheatSheet { /** * The estimated height of a toast, in dips (density-independent pixels). This is used to * determine whether or not the toast should appear above or below the UI element. */ private val ESTIMATED_TOAST_HEIGHT_DIPS = 48 /** * Sets up a cheat sheet (tooltip) for the given view by setting its [ ]. When the view is long-pressed, a [Toast] with * the view's [content description][android.view.View.getContentDescription] will be * shown either above (default) or below the view (if there isn't room above it). * @param view The view to add a cheat sheet for. */ fun setup(view: View) { view.setOnLongClickListener { view -> showCheatSheet(view, view.contentDescription) } } /** * Sets up a cheat sheet (tooltip) for the given view by setting its [ ]. When the view is long-pressed, a [Toast] with * the given text will be shown either above (default) or below the view (if there isn't room * above it). * @param view The view to add a cheat sheet for. * * * @param textResId The string resource containing the text to show on long-press. */ fun setup(view: View, textResId: Int) { view.setOnLongClickListener { view -> showCheatSheet(view, view.context.getString(textResId)) } } /** * Sets up a cheat sheet (tooltip) for the given view by setting its [ ]. When the view is long-pressed, a [Toast] with * the given text will be shown either above (default) or below the view (if there isn't room * above it). * @param view The view to add a cheat sheet for. * * * @param text The text to show on long-press. */ fun setup(view: View, text: CharSequence) { view.setOnLongClickListener { view -> showCheatSheet(view, text) } } /** * Removes the cheat sheet for the given view by removing the view's [ ]. * @param view The view whose cheat sheet should be removed. */ fun remove(view: View) { view.setOnLongClickListener(null) } /** * Internal helper method to show the cheat sheet toast. */ private fun showCheatSheet(view: View, text: CharSequence): Boolean { if (TextUtils.isEmpty(text)) { return false } val screenPos = IntArray(2) // origin is device display val displayFrame = Rect() // includes decorations (e.g. status bar) view.getLocationOnScreen(screenPos) view.getWindowVisibleDisplayFrame(displayFrame) val context = view.context val viewWidth = view.width val viewHeight = view.height val viewCenterX = screenPos[0] + viewWidth / 2 val screenWidth = context.resources.displayMetrics.widthPixels val estimatedToastHeight = (ESTIMATED_TOAST_HEIGHT_DIPS * context.resources.displayMetrics.density).toInt() val cheatSheet = Toast.makeText(context, text, Toast.LENGTH_SHORT) val showBelow = screenPos[1] < estimatedToastHeight if (showBelow) { // Show below // Offsets are after decorations (e.g. status bar) are factored in cheatSheet.setGravity(Gravity.TOP or Gravity.CENTER_HORIZONTAL, viewCenterX - screenWidth / 2, screenPos[1] - displayFrame.top + viewHeight) } else { // Show above // Offsets are after decorations (e.g. status bar) are factored in // NOTE: We can't use Gravity.BOTTOM because when the keyboard is up // its height isn't factored in. cheatSheet.setGravity(Gravity.TOP or Gravity.CENTER_HORIZONTAL, viewCenterX - screenWidth / 2, screenPos[1] - displayFrame.top - estimatedToastHeight) } cheatSheet.show() return true } }
apache-2.0
f608f5c41bfe89a8a731d029044f3884
38.838462
174
0.668405
4.351261
false
false
false
false
AVnetWS/Hentoid
app/src/main/java/me/devsaki/hentoid/activities/DuplicateDetectorActivity.kt
1
5981
package me.devsaki.hentoid.activities import android.os.Bundle import androidx.appcompat.widget.Toolbar import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity import androidx.lifecycle.ViewModelProvider import androidx.viewpager2.adapter.FragmentStateAdapter import androidx.viewpager2.widget.ViewPager2 import androidx.viewpager2.widget.ViewPager2.OnPageChangeCallback import me.devsaki.hentoid.R import me.devsaki.hentoid.database.domains.Content import me.devsaki.hentoid.databinding.ActivityDuplicateDetectorBinding import me.devsaki.hentoid.events.CommunicationEvent import me.devsaki.hentoid.fragments.tools.DuplicateDetailsFragment import me.devsaki.hentoid.fragments.tools.DuplicateMainFragment import me.devsaki.hentoid.util.ThemeHelper import me.devsaki.hentoid.viewmodels.DuplicateViewModel import me.devsaki.hentoid.viewmodels.ViewModelFactory import org.greenrobot.eventbus.EventBus class DuplicateDetectorActivity : BaseActivity() { private var binding: ActivityDuplicateDetectorBinding? = null private lateinit var viewPager: ViewPager2 // Viewmodel private lateinit var viewModel: DuplicateViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) ThemeHelper.applyTheme(this) binding = ActivityDuplicateDetectorBinding.inflate(layoutInflater) binding?.let { setContentView(it.root) it.toolbar.setNavigationOnClickListener { onBackPressed() } } val vmFactory = ViewModelFactory(application) viewModel = ViewModelProvider(this, vmFactory).get(DuplicateViewModel::class.java) // Cancel any previous worker that might be running TODO CANCEL BUTTON // WorkManager.getInstance(application).cancelAllWorkByTag(DuplicateDetectorWorker.WORKER_TAG) initUI() updateToolbar(0, 0, 0) initSelectionToolbar() } override fun onDestroy() { super.onDestroy() binding = null } private fun initUI() { if (null == binding || null == binding?.duplicatesPager) return viewPager = binding?.duplicatesPager as ViewPager2 // Main tabs viewPager.isUserInputEnabled = false // Disable swipe to change tabs viewPager.registerOnPageChangeCallback(object : OnPageChangeCallback() { override fun onPageSelected(position: Int) { enableCurrentFragment() hideSettingsBar() updateToolbar(0, 0, 0) updateTitle(-1) updateSelectionToolbar() } }) updateDisplay() } fun initFragmentToolbars( toolbarOnItemClicked: Toolbar.OnMenuItemClickListener ) { binding?.toolbar?.setOnMenuItemClickListener(toolbarOnItemClicked) } private fun updateDisplay() { val pagerAdapter: FragmentStateAdapter = DuplicatePagerAdapter(this) viewPager.adapter = pagerAdapter pagerAdapter.notifyDataSetChanged() enableCurrentFragment() } fun goBackToMain() { enableFragment(0) // if (isGroupDisplayed()) return // viewModel.searchGroup(Preferences.getGroupingDisplay(), query, Preferences.getGroupSortField(), Preferences.isGroupSortDesc(), Preferences.getArtistGroupVisibility(), isGroupFavsChecked) viewPager.currentItem = 0 // if (titles.containsKey(0)) toolbar.setTitle(titles.get(0)) } fun showDetailsFor(content: Content) { enableFragment(1) viewModel.setContent(content) viewPager.currentItem = 1 } private fun enableCurrentFragment() { enableFragment(viewPager.currentItem) } private fun enableFragment(fragmentIndex: Int) { EventBus.getDefault().post( CommunicationEvent( CommunicationEvent.EV_ENABLE, if (0 == fragmentIndex) CommunicationEvent.RC_DUPLICATE_MAIN else CommunicationEvent.RC_DUPLICATE_DETAILS, null ) ) EventBus.getDefault().post( CommunicationEvent( CommunicationEvent.EV_DISABLE, if (0 == fragmentIndex) CommunicationEvent.RC_DUPLICATE_DETAILS else CommunicationEvent.RC_DUPLICATE_MAIN, null ) ) } fun updateTitle(count: Int) { binding!!.toolbar.title = if (count > -1) resources.getString( R.string.duplicate_detail_title, count ) else resources.getString(R.string.title_activity_duplicate_detector) } fun updateToolbar(localCount: Int, externalCount: Int, streamedCount: Int) { if (null == binding) return binding!!.toolbar.menu.findItem(R.id.action_settings).isVisible = (0 == viewPager.currentItem) binding!!.toolbar.menu.findItem(R.id.action_merge).isVisible = ( 1 == viewPager.currentItem && ( localCount > 1 && 0 == streamedCount && 0 == externalCount || streamedCount > 1 && 0 == localCount && 0 == externalCount || externalCount > 1 && 0 == localCount && 0 == streamedCount ) ) } private fun initSelectionToolbar() { // TODO } private fun hideSettingsBar() { // TODO } private fun updateSelectionToolbar() { // TODO } /** * ============================== SUBCLASS */ private class DuplicatePagerAdapter constructor(fa: FragmentActivity?) : FragmentStateAdapter(fa!!) { override fun createFragment(position: Int): Fragment { return if (0 == position) { DuplicateMainFragment() } else { DuplicateDetailsFragment() } } override fun getItemCount(): Int { return 2 } } }
apache-2.0
e6be1ec9b0bfd5ad70d1d7d28e47bba4
32.606742
196
0.647551
5.302305
false
false
false
false
junkdog/transducers-kotlin
src/main/kotlin/net/onedaybeard/transducers/Transducers.kt
1
24040
// Copyright 2014 Cognitect. All Rights Reserved. // Copyright 2015 Benjamin Gudehus (updated code to Kotlin 1.0.0). // // 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. // This is a Kotlin port of https://github.com/cognitect-labs/transducers-java package net.onedaybeard.transducers import java.util.* import java.util.concurrent.ThreadLocalRandom import java.util.concurrent.atomic.AtomicBoolean /** * A reducing step function. * @param [R] Type of first argument and return value * @param [T] Type of input to reduce */ interface StepFunction<R, in T> { /** * Applies the reducing function to the current result and * the new input, returning a new result. * * A reducing function can indicate that no more input * should be processed by setting the value of reduced to * true. This causes the reduction process to complete, * returning the most recent result. * @param result The current result value * @param input New input to process * @param reduced A boolean value which can be set to true * to stop the reduction process * @return A new result value */ fun apply(result: R, input: T, reduced: AtomicBoolean): R } private inline fun <R, T> makeStepFunction(crossinline step: (R, T) -> R): StepFunction<R, T> { return object : StepFunction<R, T> { override fun apply(result: R, input: T, reduced: AtomicBoolean): R { return step.invoke(result, input) } } } /** * A complete reducing function. Extends a single reducing step * function and adds a zero-arity function for initializing a new * result and a single-arity function for processing the final * result after the reduction process has completed. * @param [R] Type of first argument and return value * @param [T] Type of input to reduce */ interface ReducingFunction<R, in T> : StepFunction<R, T> { /** * Returns a newly initialized result. * @return a new result */ fun apply(): R = throw UnsupportedOperationException() /** * Completes processing of a final result. * @param result the final reduction result * @return the completed result */ fun apply(result: R): R = result } /** * Abstract base class for implementing a reducing function that chains to * another reducing function. Zero-arity and single-arity overloads of apply * delegate to the chained reducing function. Derived classes must implement * the three-arity overload of apply, and may implement either of the other * two overloads as required. * @param [R] Type of first argument and return value of the reducing functions * @param [A] Input type of reducing function being chained to * @param [B] Input type of this reducing function */ abstract class ReducingFunctionOn<R, in A, in B>( val rf: ReducingFunction<R, A>) : ReducingFunction<R, B> { override fun apply() = rf.apply() override fun apply(result: R) = rf.apply(result) } /** * A Transducer transforms a reducing function of one type into a * reducing function of another (possibly the same) type, applying * mapping, filtering, flattening, etc. logic as desired. * @param [B] The type of data processed by an input process * @param [C] The type of data processed by the transduced process */ interface Transducer<out B, C> { /** * Transforms a reducing function of B into a reducing function * of C. * @param rf The input reducing function * @param <R> The result type of both the input and the output * reducing functions * @return The transformed reducing function */ fun <R> apply(rf: ReducingFunction<R, B>): ReducingFunction<R, C> /** * Composes a transducer with another transducer, yielding * a new transducer. * * @param right the transducer to compose with this transducer * @param <A> the type of input processed by the reducing function * the composed transducer returns when applied * @return A new composite transducer */ fun <A> comp(right: Transducer<A, in B>): Transducer<A, C> = object : Transducer<A, C> { override fun <R> apply(rf: ReducingFunction<R, A>) = this@Transducer.apply(right.apply(rf)) } } /** * Applies given reducing function to current result and each T in input, using * the result returned from each reduction step as input to the next step. Returns * final result. * @param f a reducing function * @param result an initial result value * @param input the input to process * @param reduced a boolean flag that can be set to indicate that the reducing process * should stop, even though there is still input to process * @param <R> the type of the result * @param <T> the type of each item in input * @return the final reduced result */ fun <R, T> reduce(f: ReducingFunction<R, T>, result: R, input: Iterable<T>, reduced: AtomicBoolean = AtomicBoolean(), completing: Boolean = true): R { var ret = result for (t in input) { ret = f.apply(ret, t, reduced) if (reduced.get()) break } return if (completing) f.apply(ret) else ret } /** * Converts a [StepFunction] into a complete [ReducingFunction]. If [sf] is already * a `StepFunction`, returns it without modification; otherwise returns a new * `ReducingFunction` with a step function that forwards to [sf]. */ fun <R, T> completing(sf: StepFunction<R, T>): ReducingFunction<R, T> = sf as? ReducingFunction ?: object : ReducingFunction<R, T> { override fun apply(result: R, input: T, reduced: AtomicBoolean) = sf.apply(result, input, reduced) } /** * Reduces input using transformed reducing function. Transforms reducing function by applying * transducer. Reducing function must implement zero-arity apply that returns initial result * to start reducing process. * @param xf a transducer (or composed transducers) that transforms the reducing function * @param rf a reducing function * @param input the input to reduce * @param [R] return type * @param [A] type of input expected by reducing function * @param [B] type of input and type accepted by reducing function returned by transducer * @return result of reducing transformed input */ fun <R, A, B> transduce(xf: Transducer<A, B>, rf: ReducingFunction<R, A>, input: Iterable<B>): R = reduce(xf.apply(rf), rf.apply(), input) /** * Reduces input using transformed reducing function. Transforms reducing function by applying * transducer. Step function is converted to reducing function if necessary. Accepts initial value * for reducing process as argument. * @param xf a transducer (or composed transducers) that transforms the reducing function * @param rf a reducing function * @param init an initial value to start reducing process * @param input the input to reduce * @param [R] return type * @param [A] type expected by reducing function * @param [B] type of input and type accepted by reducing function returned by transducer * @return result of reducing transformed input */ fun <R, A, B> transduce(xf: Transducer<A, B>, rf: StepFunction<R, A>, init: R, input: Iterable<B>): R = reduce(xf.apply(completing(rf)), init, input) fun <R, A, B> transduce(xf: Transducer<A, B>, rf: StepFunction<R, A>, init: R, input: Sequence<B>): R = reduce(xf.apply(completing(rf)), init, input.asIterable()) fun <R, A, B> transduce(xf: Transducer<A, B>, rf: (R, A) -> R, init: R, input: Iterable<B>): R = transduce(xf, makeStepFunction(rf), init, input) fun <R, A, B> transduce(xf: Transducer<A, B>, rf: (R, A) -> R, init: R, input: Sequence<B>): R = transduce(xf, makeStepFunction(rf), init, input) /** * Composes a transducer with another transducer, yielding a new transducer. * @param left left hand transducer * @param right right hand transducer */ fun <A, B, C> compose(left: Transducer<B, C>, right: Transducer<A, B>): Transducer<A, C> = left.comp(right) /** * Creates a transducer that transforms a reducing function by applying a mapping * function to each input. * @param f a mapping function from one type to another (can be the same type) * @param [A] input type of input reducing function * @param [B] input type of output reducing function * @return a new transducer */ fun <A, B> map(f: (B) -> A): Transducer<A, B> = object : Transducer<A, B> { override fun <R> apply(rf: ReducingFunction<R, A>) = object : ReducingFunctionOn<R, A, B>(rf) { override fun apply(result: R, input: B, reduced: AtomicBoolean) = rf.apply(result, f(input), reduced) } } /** * Creates a transducer that transforms a reducing function by applying a * predicate to each input and processing only those inputs for which the * predicate is true. * @param p a predicate function * @param [A] input type of input and output reducing functions * @return a new transducer */ fun <A> filter(p: (A) -> Boolean): Transducer<A, A> = object : Transducer<A, A> { override fun <R> apply(rf: ReducingFunction<R, A>) = object : ReducingFunctionOn<R, A, A>(rf) { override fun apply(result: R, input: A, reduced: AtomicBoolean): R { return if (p(input)) rf.apply(result, input, reduced) else result } } } /** * Creates a transducer that transforms a reducing function by accepting * an iterable of the expected input type and reducing it * @param [A] input type of input reducing function * @param [B] input type of output reducing function * @return a new transducer */ fun <A> cat(): Transducer<A, Iterable<A>> = object : Transducer<A, Iterable<A>> { override fun <R> apply(rf: ReducingFunction<R, A>) = object : ReducingFunctionOn<R, A, Iterable<A>>(rf) { override fun apply(result: R, input: Iterable<A>, reduced: AtomicBoolean) = reduce(f = rf, result = result, input = input, reduced = reduced, completing = false) } } /** * Creates a transducer that transforms a reducing function using * a composition of map and cat. * @param f a mapping function from one type to another (can be the same type) * @param [A] input type of input reducing function * @param [B] output type of output reducing function and iterable of input type * of input reducing function * @param [C] input type of output reducing function * @return a new transducer */ fun <A, B : Iterable<A>, C> mapcat(f: (C) -> B): Transducer<A, C> = map(f).comp(cat()) /** * Creates a transducer that transforms a reducing function by applying a * predicate to each input and not processing those inputs for which the * predicate is true. * @param p a predicate function * @param [A] input type of input and output reducing functions * @return a new transducer */ fun <A> remove(p: (A) -> Boolean): Transducer<A, A> = filter { !p(it) } /** * Creates a transducer that transforms a reducing function such that * it only processes n inputs, then the reducing process stops. * @param n the number of inputs to process * @param [A] input type of input and output reducing functions * @return a new transducer */ fun <A> take(n: Int): Transducer<A, A> = object : Transducer<A, A> { override fun <R> apply(rf: ReducingFunction<R, A>) = object : ReducingFunctionOn<R, A, A>(rf) { private var taken = 0 override fun apply(result: R, input: A, reduced: AtomicBoolean): R { var ret = result if (taken < n) { ret = rf.apply(result, input, reduced) taken++ } else { reduced.set(true) } return ret } } } /** * Creates a transducer that transforms a reducing function such that * it processes inputs as long as the provided predicate returns true. * If the predicate returns false, the reducing process stops. * @param p a predicate used to test inputs * @param [A] input type of input and output reducing functions * @return a new transducer */ fun <A> takeWhile(p: (A) -> Boolean): Transducer<A, A> = object : Transducer<A, A> { override fun <R> apply(rf: ReducingFunction<R, A>) = object : ReducingFunctionOn<R, A, A>(rf) { override fun apply(result: R, input: A, reduced: AtomicBoolean): R { var ret = result if (p(input)) { ret = rf.apply(ret, input, reduced) } else { reduced.set(true) } return ret } } } fun <A> distinct(): Transducer<A, A> = object : Transducer<A, A> { override fun <R> apply(rf: ReducingFunction<R, A>) = object : ReducingFunction<R, A> { val intercepted = mutableSetOf<A>() override fun apply(result: R): R { intercepted.clear() return rf.apply(result) } override fun apply(result: R, input: A, reduced: AtomicBoolean): R { if (intercepted.add(input)) { return rf.apply(result, input, reduced) } else { return result } } override fun apply(): R = rf.apply() } } /** * Creates a transducer that transforms a reducing function such that * it skips n inputs, then processes the rest of the inputs. * @param n the number of inputs to skip * @param [A] input type of input and output reducing functionsi * @return a new transducer */ fun <A> drop(n: Int): Transducer<A, A> = object : Transducer<A, A> { override fun <R> apply(rf: ReducingFunction<R, A>) = object : ReducingFunctionOn<R, A, A>(rf) { private var dropped = 0 override fun apply(result: R, input: A, reduced: AtomicBoolean): R { var ret = result if (dropped < n) { dropped++ } else { ret = rf.apply(ret, input, reduced) } return ret } } } /** * Creates a transducer that transforms a reducing function such that * it skips inputs as long as the provided predicate returns true. * Once the predicate returns false, the rest of the inputs are * processed. * @param p a predicate used to test inputs * @param <A> input type of input and output reducing functions * @return a new transducer */ fun <A> dropWhile(p: (A) -> Boolean): Transducer<A, A> = object : Transducer<A, A> { override fun <R> apply(rf: ReducingFunction<R, A>) = object : ReducingFunctionOn<R, A, A>(rf) { private var drop = true override fun apply(result: R, input: A, reduced: AtomicBoolean): R { if (drop && p(input)) { return result } drop = false return rf.apply(result, input, reduced) } } } /** * Creates a transducer that transforms a reducing function such that * it processes every nth input. * @param n The frequence of inputs to process (e.g., 3 processes every third input). * @param [A] The input type of the input and output reducing functions * @return a new transducer */ fun <A> takeNth(n: Int): Transducer<A, A> = object : Transducer<A, A> { override fun <R> apply(rf: ReducingFunction<R, A>) = object : ReducingFunctionOn<R, A, A>(rf) { private var nth = 0 override fun apply(result: R, input: A, reduced: AtomicBoolean): R { return if ((nth++ % n) == 0) rf.apply(result, input, reduced) else result } } } /** * Creates a transducer that transforms a reducing function such that * inputs that are keys in the provided map are replaced by the corresponding * value in the map. * @param smap a map of replacement values * @param [A] the input type of the input and output reducing functions * @return a new transducer */ fun <A> replace(smap: Map<A, A>): Transducer<A, A> { return map { if (smap.containsKey(it)) smap[it]!! else it } } /** * Creates a transducer that transforms a reducing function by applying a * function to each input and processing the resulting value, ignoring values * that are null. * @param f a function for processing inputs * @param [A] the input type of the input and output reducing functions * @return a new transducer */ fun <A : Any> keep(f: (A) -> A?): Transducer<A, A> = object : Transducer<A, A> { override fun <R> apply(rf: ReducingFunction<R, A>) = object : ReducingFunctionOn<R, A, A>(rf) { override fun apply(result: R, input: A, reduced: AtomicBoolean): R { val _input = f(input) return if (_input != null) rf.apply(result, _input, reduced) else result } } } /** * Creates a transducer that transforms a reducing function by applying a * function to each input and processing the resulting value, ignoring values * that are null. * @param f a function for processing inputs * @param <A> the input type of the input and output reducing functions * @return a new transducer */ fun <A : Any> keepIndexed(f: (Int, A) -> A?): Transducer<A, A> = object : Transducer<A, A> { override fun <R> apply(rf: ReducingFunction<R, A>) = object : ReducingFunctionOn<R, A, A>(rf) { private var n = 0 override fun apply(result: R, input: A, reduced: AtomicBoolean): R { val _input = f(++n, input) return if (_input != null) rf.apply(result, _input, reduced) else result } } } /** * Creates a transducer that transforms a reducing function such that * consecutive identical input values are removed, only a single value * is processed. * @param [A] the input type of the input and output reducing functions * @return a new transducer */ fun <A : Any> dedupe(): Transducer<A, A> = object : Transducer<A, A> { override fun <R> apply(rf: ReducingFunction<R, A>) = object : ReducingFunctionOn<R, A, A>(rf) { var prior: A? = null override fun apply(result: R, input: A, reduced: AtomicBoolean): R { var ret = result if (prior != input) { prior = input ret = rf.apply(ret, input, reduced) } return ret } } } /** * Creates a transducer that transforms a reducing function such that * it has the specified probability of processing each input. * @param prob the probability between expressed as a value between 0 and 1. * @param [A] the input type of the input and output reducing functions * @return a new transducer */ fun <A : Any> randomSample(prob: Double): Transducer<A, A> = filter { ThreadLocalRandom.current().nextDouble() < prob } /** * Creates a transducer that transforms a reducing function that processes * iterables of input into a reducing function that processes individual inputs * by gathering series of inputs for which the provided partitioning function returns * the same value, only forwarding them to the next reducing function when the value * the partitioning function returns for a given input is different from the value * returned for the previous input. * @param f the partitioning function * @param [A] the input type of the input and output reducing functions * @param [P] the type returned by the partitioning function * @return a new transducer */ fun <A, P> partitionBy(f: (A) -> P): Transducer<Iterable<A>, A> = object : Transducer<Iterable<A>, A> { override fun <R> apply(rf: ReducingFunction<R, Iterable<A>>) = object : ReducingFunction<R, A> { val part = ArrayList<A>() val mark: Any = Unit var prior: Any? = mark override fun apply(): R = rf.apply() override fun apply(result: R): R { var ret = result if (part.isNotEmpty()) { ret = rf.apply(result, ArrayList(part), AtomicBoolean()) part.clear() } return rf.apply(ret) } override fun apply(result: R, input: A, reduced: AtomicBoolean): R { val p = f(input) if (prior === mark || prior == p) { prior = p part.add(input) return result } val copy = ArrayList(part) prior = p part.clear() val ret = rf.apply(result, copy, reduced) if (!reduced.get()) { part.add(input) } return ret } } } /** * Creates a transducer that transforms a reducing function that processes * iterables of input into a reducing function that processes individual inputs * by gathering series of inputs into partitions of a given size, only forwarding * them to the next reducing function when enough inputs have been accrued. Processes * any remaining buffered inputs when the reducing process completes. * @param n the size of each partition * @param [A] the input type of the input and output reducing functions * @return a new transducer */ fun <A> partitionAll(n: Int): Transducer<Iterable<A>, A> = object : Transducer<Iterable<A>, A> { override fun <R> apply(rf: ReducingFunction<R, Iterable<A>>) = object : ReducingFunction<R, A> { val part = ArrayList<A>() override fun apply(): R = rf.apply() override fun apply(result: R): R { var ret = result if (part.isNotEmpty()) { ret = rf.apply(result, ArrayList(part), AtomicBoolean()) part.clear() } return rf.apply(ret) } override fun apply(result: R, input: A, reduced: AtomicBoolean): R { part.add(input) return if (n == part.size) { try { rf.apply(result, ArrayList(part), reduced) } finally { part.clear() } } else { result } } } } operator fun <A, B, C> Transducer<B, C>.plus(right: Transducer<A, in B>): Transducer<A, C> = this.comp(right)
apache-2.0
6a939088afb4d51aabd63b7a488ad2fe
37.4656
109
0.605158
4.27758
false
false
false
false
kpspemu/kpspemu
src/commonMain/kotlin/com/soywiz/dynarek2/D2I.kt
1
2074
package com.soywiz.dynarek2 import kotlin.reflect.* inline operator fun KFunction<Int>.invoke(vararg args: D2Expr<*>): D2ExprI = D2Expr.Invoke(D2INT, this, *args) val Int.lit get() = D2Expr.ILit(this) operator fun D2ExprI.unaryMinus() = UNOP(this, D2UnOp.NEG) fun BINOP(l: D2ExprI, op: D2IBinOp, r: D2ExprI) = D2Expr.IBinOp(l, op, r) fun COMPOP(l: D2ExprI, op: D2CompOp, r: D2ExprI) = D2Expr.IComOp(l, op, r) fun UNOP(l: D2ExprI, op: D2UnOp) = D2Expr.IUnop(l, op) operator fun D2ExprI.plus(other: D2ExprI) = BINOP(this, D2IBinOp.ADD, other) operator fun D2ExprI.minus(other: D2ExprI) = BINOP(this, D2IBinOp.SUB, other) operator fun D2ExprI.times(other: D2ExprI) = BINOP(this, D2IBinOp.MUL, other) operator fun D2ExprI.div(other: D2ExprI) = BINOP(this, D2IBinOp.DIV, other) operator fun D2ExprI.rem(other: D2ExprI) = BINOP(this, D2IBinOp.REM, other) infix fun D2ExprI.SHL(other: D2ExprI) = BINOP(this, D2IBinOp.SHL, other) infix fun D2ExprI.SHR(other: D2ExprI) = BINOP(this, D2IBinOp.SHR, other) infix fun D2ExprI.USHR(other: D2ExprI) = BINOP(this, D2IBinOp.USHR, other) infix fun D2ExprI.AND(other: D2ExprI) = BINOP(this, D2IBinOp.AND, other) infix fun D2ExprI.OR(other: D2ExprI) = BINOP(this, D2IBinOp.OR, other) infix fun D2ExprI.XOR(other: D2ExprI) = BINOP(this, D2IBinOp.XOR, other) infix fun D2ExprI.EQ(other: D2ExprI) = COMPOP(this, D2CompOp.EQ, other) infix fun D2ExprI.NE(other: D2ExprI) = COMPOP(this, D2CompOp.NE, other) infix fun D2ExprI.LT(other: D2ExprI) = COMPOP(this, D2CompOp.LT, other) infix fun D2ExprI.LE(other: D2ExprI) = COMPOP(this, D2CompOp.LE, other) infix fun D2ExprI.GT(other: D2ExprI) = COMPOP(this, D2CompOp.GT, other) infix fun D2ExprI.GE(other: D2ExprI) = COMPOP(this, D2CompOp.GE, other) private fun Int.mask(): Int = (1 shl this) - 1 fun D2ExprI.EXTRACT(offset: Int, size: Int): D2ExprI = (this SHR offset.lit) AND size.mask().lit fun D2ExprI.INSERT(offset: Int, size: Int, value: D2ExprI): D2ExprI = (this AND (size.mask() shl offset).lit) OR ((value AND size.mask().lit) SHL offset.lit) fun INV(v: D2ExprI) = v XOR (-1).lit
mit
6a0683d9926bc62764654e1ae00d7f4a
48.380952
110
0.730955
2.566832
false
false
false
false
lisawray/groupie
example/src/main/java/com/xwray/groupie/example/ColumnGroup.kt
3
1526
package com.xwray.groupie.example import com.xwray.groupie.Group import com.xwray.groupie.GroupDataObserver import com.xwray.groupie.Item import java.util.* /** * A simple, non-editable, non-nested group of Items which displays a list as vertical columns. */ class ColumnGroup(items: List<Item<*>>) : Group { private val items = ArrayList<Item<*>>() init { for (i in items.indices) { // Rearrange items so that the adapter appears to arrange them in vertical columns var index: Int if (i % 2 == 0) { index = i / 2 } else { index = (i - 1) / 2 + (items.size / 2f).toInt() // If columns are uneven, we'll put an extra one at the end of the first column, // meaning the second column's indices will all be increased by 1 if (items.size % 2 == 1) index++ } val trackItem = items[index] this.items.add(trackItem) } } override fun registerGroupDataObserver(groupDataObserver: GroupDataObserver) { // no need to do anything here } override fun unregisterGroupDataObserver(groupDataObserver: GroupDataObserver) { // no need to do anything here } override fun getItem(position: Int): Item<*> { return items[position] } override fun getPosition(item: Item<*>): Int { return items.indexOf(item) } override fun getItemCount(): Int { return items.size } }
mit
38471c1fb37e6f102e1f9ba905a03886
28.921569
96
0.598296
4.397695
false
false
false
false
proxer/ProxerLibAndroid
library/src/main/kotlin/me/proxer/library/enums/MediaLanguage.kt
2
661
package me.proxer.library.enums import com.serjltt.moshi.adapters.FallbackEnum import com.squareup.moshi.Json import com.squareup.moshi.JsonClass import me.proxer.library.entity.info.Entry /** * Enum holding the available languages of an [Entry]. * * @author Ruben Gees */ @JsonClass(generateAdapter = false) @FallbackEnum(name = "OTHER") enum class MediaLanguage { @Json(name = "de") GERMAN, @Json(name = "en") ENGLISH, @Json(name = "gersub") GERMAN_SUB, @Json(name = "gerdub") GERMAN_DUB, @Json(name = "engsub") ENGLISH_SUB, @Json(name = "engdub") ENGLISH_DUB, @Json(name = "misc") OTHER }
gpl-3.0
f79deca3b4f2dff7966af72abab04b3c
16.864865
54
0.655068
3.372449
false
false
false
false
ThomasGaubert/zephyr
android/app/src/main/java/com/texasgamer/zephyr/util/BuildConfigUtils.kt
1
562
package com.texasgamer.zephyr.util import com.texasgamer.zephyr.BuildConfig /** * BuildConfig utilities. */ object BuildConfigUtils { @JvmStatic val versionCode: Int get() = BuildConfig.VERSION_CODE val versionName: String get() = BuildConfig.VERSION_NAME @JvmStatic val packageName: String get() = BuildConfig.APPLICATION_ID val flavor: String get() = BuildConfig.FLAVOR val buildType: String get() = BuildConfig.BUILD_TYPE val isDebug: Boolean get() = BuildConfig.DEBUG }
mit
a475a7309dea5aa2063b82ee4dc1766e
19.107143
42
0.661922
4.425197
false
true
false
false
google/private-compute-libraries
java/com/google/android/libraries/pcc/chronicle/api/Chronicle.kt
1
5130
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.libraries.pcc.chronicle.api import com.google.android.libraries.pcc.chronicle.api.error.ChronicleError import com.google.android.libraries.pcc.chronicle.api.policy.Policy import kotlin.reflect.KClass /** Chronicle is the primary entry point for features when accessing or manipulating data. */ interface Chronicle { /** * Checks policy adherence of the [ConnectionRequest.requester] and the data being requested. * @param isForReading true if the policy will be used in conjunction with a [ReadConnection] */ fun checkPolicy( dataTypeName: String, policy: Policy?, isForReading: Boolean, requester: ProcessorNode ): Result<Unit> /** * Returns the [ConnectionTypes] associated with the provided [dataTypeClass] which are available * via [getConnection]. */ fun getAvailableConnectionTypes(dataTypeClass: KClass<*>): ConnectionTypes /** * Returns the [ConnectionTypes] associated with the provided [dataTypeClass] which are available * via [getConnection]. */ fun getAvailableConnectionTypes(dataTypeClass: Class<*>): ConnectionTypes = getAvailableConnectionTypes(dataTypeClass.kotlin) /** * Returns a [Connection] of type [T] after checking policy adherence of the * [ConnectionRequest.requester] and the data being requested. */ fun <T : Connection> getConnection(request: ConnectionRequest<T>): ConnectionResult<T> /** * A convenience method which calls [getConnection], returning `null` for * [ConnectionResult.Failure] results. An optional [onError] parameter will be called with the * failure result. */ fun <T : Connection> getConnectionOrNull( request: ConnectionRequest<T>, onError: (ChronicleError) -> Unit = {} ): T? { return when (val result = getConnection(request)) { is ConnectionResult.Success<T> -> result.connection is ConnectionResult.Failure<T> -> { onError(result.error) null } } } /** * A convenience method which calls [getConnection], returning `null` for * [ConnectionResult.Failure] results. If a failure occurs, there will be no information provided * about the failure. */ fun <T : Connection> getConnectionOrNull( request: ConnectionRequest<T>, ): T? = getConnectionOrNull(request) {} /** * A convenience method which calls [getConnection], and throws [ChronicleError] for * [ConnectionResult.Failure] results. */ fun <T : Connection> getConnectionOrThrow(request: ConnectionRequest<T>): T { return when (val result = getConnection(request)) { is ConnectionResult.Success<T> -> result.connection is ConnectionResult.Failure<T> -> throw (result.error) } } data class ConnectionTypes( val readConnections: Set<Class<out ReadConnection>>, val writeConnections: Set<Class<out WriteConnection>> ) { companion object { val EMPTY = ConnectionTypes(emptySet(), emptySet()) } } } /** Result container for [Connection] attempts. */ sealed class ConnectionResult<T : Connection> { class Success<T : Connection>(val connection: T) : ConnectionResult<T>() class Failure<T : Connection>(val error: ChronicleError) : ConnectionResult<T>() } /** * A convenience method that will create a [ConnectionRequest] using the class provided as a type * parameter to the call, the provided processor, and provided policy. */ inline fun <reified T : Connection> Chronicle.getConnection( requester: ProcessorNode, policy: Policy? = null ) = getConnection(ConnectionRequest(T::class.java, requester, policy)) /** * A convenience method that will create a [ConnectionRequest] using the class provided as a type * parameter to the call, the provided processor, and provided policy. * * An optional [onError] callback will be called with the [ChronicleError] containing the failure * reason if the connection fails. */ inline fun <reified T : Connection> Chronicle.getConnectionOrNull( requester: ProcessorNode, policy: Policy? = null, noinline onError: (ChronicleError) -> Unit = {} ) = getConnectionOrNull(ConnectionRequest(T::class.java, requester, policy), onError) /** * A convenience method that will create a [ConnectionRequest] using the class provided as a type * parameter to the call, the provided processor, and provided policy. */ inline fun <reified T : Connection> Chronicle.getConnectionOrThrow( requester: ProcessorNode, policy: Policy? = null ) = getConnectionOrThrow(ConnectionRequest(T::class.java, requester, policy))
apache-2.0
577a3c41f43f80f36b1d1b190cc93e67
36.173913
99
0.72807
4.507909
false
false
false
false
AlexanderDashkov/hpcourse
csc/2016/vsv_1/src/handlers/SubmitRequestHandler.kt
3
1509
package handlers import communication.CommunicationProtos class SubmitRequestHandler(private val taskId: Int, private val waitDependentTask: (taskId: Int) -> Long?) { fun handle(request: CommunicationProtos.SubmitTask): Long? { val task: Task = getTask(request) ?: return null return calculate(task) } private fun calculate(task: Task): Long { var a = task.a var b = task.b var p = task.p var m = task.m var n = task.n while (n-- > 0) { b = (a * p + b) % m; a = b; } return a } private fun getTask(request: CommunicationProtos.SubmitTask): Task? { try { val a: Long = waitAndGet(request.task.a) val b: Long = waitAndGet(request.task.b) val p: Long = waitAndGet(request.task.p) val m: Long = waitAndGet(request.task.m) val n: Long = request.task.n return Task(a, b, p, m, n) } catch(e: RuntimeException) { println("Failed to wait dependent parameters") return null } } private fun waitAndGet(param: CommunicationProtos.Task.Param): Long { if (param.hasValue()) { return param.value } val result: Long = waitDependentTask(param.dependentTaskId) ?: throw RuntimeException("Dependent task waiting failed") return result } } data class Task(val a: Long, val b: Long, val p: Long, val m: Long, val n: Long)
gpl-2.0
890b6989496528f2f28085b8f9561469
29.795918
126
0.577866
4.100543
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-players-bukkit/src/main/kotlin/com/rpkit/players/bukkit/command/profile/ProfileLinkIRCCommand.kt
1
4796
/* * Copyright 2022 Ren 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.players.bukkit.command.profile import com.rpkit.chat.bukkit.irc.RPKIRCService import com.rpkit.core.command.RPKCommandExecutor import com.rpkit.core.command.result.* import com.rpkit.core.command.sender.RPKCommandSender import com.rpkit.core.service.Services import com.rpkit.players.bukkit.RPKPlayersBukkit import com.rpkit.players.bukkit.command.result.NoProfileSelfFailure import com.rpkit.players.bukkit.command.result.NotAPlayerFailure import com.rpkit.players.bukkit.profile.RPKProfile import com.rpkit.players.bukkit.profile.RPKProfileService import com.rpkit.players.bukkit.profile.irc.RPKIRCNick import com.rpkit.players.bukkit.profile.irc.RPKIRCProfile import com.rpkit.players.bukkit.profile.irc.RPKIRCProfileService import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfile import java.util.concurrent.CompletableFuture import java.util.logging.Level /** * Account link IRC command. * Links an IRC account to the current player. */ class ProfileLinkIRCCommand(private val plugin: RPKPlayersBukkit) : RPKCommandExecutor { class InvalidIRCNickFailure : CommandFailure() class IRCProfileAlreadyLinkedFailure(val ircProfile: RPKIRCProfile) : CommandFailure() override fun onCommand(sender: RPKCommandSender, args: Array<out String>): CompletableFuture<CommandResult> { if (sender !is RPKMinecraftProfile) { sender.sendMessage(plugin.messages.notFromConsole) return CompletableFuture.completedFuture(NotAPlayerFailure()) } if (!sender.hasPermission("rpkit.players.command.profile.link.irc")) { sender.sendMessage(plugin.messages.noPermissionProfileLinkIrc) return CompletableFuture.completedFuture(NoPermissionFailure("rpkit.players.command.profile.link.irc")) } if (args.isEmpty()) { sender.sendMessage(plugin.messages.profileLinkIrcUsage) return CompletableFuture.completedFuture(IncorrectUsageFailure()) } val nick = RPKIRCNick(args[0]) val ircService = Services[RPKIRCService::class.java] if (ircService == null) { sender.sendMessage(plugin.messages.noIrcService) return CompletableFuture.completedFuture(MissingServiceFailure(RPKIRCService::class.java)) } if (!ircService.isOnline(nick)) { sender.sendMessage(plugin.messages.profileLinkIrcInvalidNick) return CompletableFuture.completedFuture(InvalidIRCNickFailure()) } val profile = sender.profile if (profile !is RPKProfile) { sender.sendMessage(plugin.messages.noProfileSelf) return CompletableFuture.completedFuture(NoProfileSelfFailure()) } val profileService = Services[RPKProfileService::class.java] if (profileService == null) { sender.sendMessage(plugin.messages.noProfileService) return CompletableFuture.completedFuture(MissingServiceFailure(RPKProfileService::class.java)) } val ircProfileService = Services[RPKIRCProfileService::class.java] if (ircProfileService == null) { sender.sendMessage(plugin.messages.noIrcProfileService) return CompletableFuture.completedFuture(MissingServiceFailure(RPKIRCProfileService::class.java)) } return ircProfileService.getIRCProfile(nick).thenApplyAsync { ircProfile -> if (ircProfile != null && ircProfile.profile is RPKProfile) { sender.sendMessage(plugin.messages.profileLinkIrcInvalidAlreadyLinked) return@thenApplyAsync IRCProfileAlreadyLinkedFailure(ircProfile) } if (ircProfile == null) { ircProfileService.createIRCProfile(profile, nick).join() } else { ircProfile.profile = profile ircProfileService.updateIRCProfile(ircProfile).join() } sender.sendMessage(plugin.messages.profileLinkIrcValid) return@thenApplyAsync CommandSuccess }.exceptionally { exception -> plugin.logger.log(Level.SEVERE, "Failed to link IRC profile", exception) throw exception } } }
apache-2.0
fbf6cc6288306851945ffaf3b993e992
46.49505
115
0.721852
4.908905
false
false
false
false
j-selby/kotgb
core/src/main/kotlin/net/jselby/kotgb/cpu/interpreter/Interpreter.kt
1
1327
package net.jselby.kotgb.cpu.interpreter import net.jselby.kotgb.Gameboy import net.jselby.kotgb.cpu.CPU import net.jselby.kotgb.cpu.CPUExecutor /** * A reference CPU interpreter for the Gameboy. */ class Interpreter : CPUExecutor() { override fun execute(gameboy: Gameboy, state: CPU, approxInstructions: Int) : Int { val registers = state.registers var cycles = 0 for (i in 0 .. approxInstructions - 1) { state.before() val instructionPos = registers.pc // Read instruction at point var rawInstruction = gameboy.ram.readByte(registers.pc.toLong()).toInt() and 0xFF val is2Byte = rawInstruction == 0xCB // Check for 2-byte instructions if (is2Byte) { // Shift the previous instruction left, and add our new one rawInstruction = (rawInstruction shl 8) or (gameboy.ram.readByte(registers.pc.toLong() + 1).toInt() and 0xFF) } // Increment the program counter registers.pc += if (is2Byte) 2 else 1 // Invoke instruction val instCycles = InstructionSwitchboard.call(gameboy, rawInstruction, instructionPos) cycles += instCycles state.after(instCycles) } return cycles } }
mit
665645b0218e7a7dd3337c5da2b78139
30.619048
125
0.616428
4.35082
false
false
false
false
nickthecoder/tickle
tickle-editor/src/main/kotlin/uk/co/nickthecoder/tickle/editor/resources/DesignJsonScene.kt
1
8957
/* Tickle Copyright (C) 2017 Nick Robinson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.nickthecoder.tickle.editor.resources import com.eclipsesource.json.JsonArray import com.eclipsesource.json.JsonObject import uk.co.nickthecoder.tickle.resources.ActorXAlignment import uk.co.nickthecoder.tickle.resources.ActorYAlignment import uk.co.nickthecoder.tickle.resources.Resources import uk.co.nickthecoder.tickle.resources.StageResource import uk.co.nickthecoder.tickle.util.JsonScene import uk.co.nickthecoder.tickle.util.JsonUtil import java.io.BufferedWriter import java.io.File import java.io.FileOutputStream import java.io.OutputStreamWriter class DesignJsonScene : JsonScene { constructor(scene: DesignSceneResource) : super(scene) constructor(file: File) : super(DesignSceneResource()) { load(file) } override fun createActorResource() = DesignActorResource() override fun load(jroot: JsonObject) { super.load(jroot) sceneResource as DesignSceneResource // Ensure it is the correct sub-class jroot.get("snapToGrid")?.let { val jgrid = it.asObject() with(sceneResource.snapToGrid) { enabled = jgrid.getBoolean("enabled", false) spacing.x = jgrid.getDouble("xSpacing", 50.0) spacing.y = jgrid.getDouble("ySpacing", 50.0) offset.x = jgrid.getDouble("xOffset", 0.0) offset.y = jgrid.getDouble("yOffset", 0.0) closeness.x = jgrid.getDouble("xCloseness", 10.0) closeness.y = jgrid.getDouble("yCloseness", 10.0) } //println("Loaded grid ${sceneResource.grid}") } jroot.get("snapToGuides")?.let { val jguides = it.asObject() with(sceneResource.snapToGuides) { enabled = jguides.getBoolean("enabled", true) closeness = jguides.getDouble("closeness", 10.0) jguides.get("x")?.let { val jx = it.asArray() jx.forEach { xGuides.add(it.asDouble()) } } jguides.get("y")?.let { val jy = it.asArray() jy.forEach { yGuides.add(it.asDouble()) } } } //println("Loaded guides ${sceneResource.guides}") } jroot.get("snapToOthers")?.let { val jothers = it.asObject() with(sceneResource.snapToOthers) { enabled = jothers.getBoolean("enabled", true) closeness.x = jothers.getDouble("xCloseness", 10.0) closeness.y = jothers.getDouble("yCloseness", 10.0) } } jroot.get("snapRotation")?.let { val jrotation = it.asObject() with(sceneResource.snapRotation) { enabled = jrotation.getBoolean("enabled", true) stepDegrees = jrotation.getDouble("step", 15.0) closeness = jrotation.getDouble("closeness", 15.0) } } } fun save(file: File) { sceneResource.file = Resources.instance.sceneDirectory.resolve(file) val jroot = JsonObject() jroot.add("director", sceneResource.directorString) JsonUtil.saveAttributes(jroot, sceneResource.directorAttributes, "directorAttributes") jroot.add("background", sceneResource.background.toHashRGB()) jroot.add("showMouse", sceneResource.showMouse) jroot.add("layout", sceneResource.layoutName) val jgrid = JsonObject() jroot.add("snapToGrid", jgrid) with((sceneResource as DesignSceneResource).snapToGrid) { jgrid.add("enabled", enabled == true) jgrid.add("xSpacing", spacing.x) jgrid.add("ySpacing", spacing.y) jgrid.add("xOffset", offset.x) jgrid.add("yOffset", offset.y) jgrid.add("xCloseness", closeness.x) jgrid.add("yCloseness", closeness.y) } val jguides = JsonObject() jroot.add("snapToGuides", jguides) with(sceneResource.snapToGuides) { jguides.add("enabled", enabled) jguides.add("closeness", closeness) val jx = JsonArray() xGuides.forEach { jx.add(it) } jguides.add("x", jx) val jy = JsonArray() yGuides.forEach { jy.add(it) } jguides.add("y", jy) } val jothers = JsonObject() jroot.add("snapToOthers", jothers) with(sceneResource.snapToOthers) { jothers.add("enabled", enabled) jothers.add("xCloseness", closeness.x) jothers.add("yCloseness", closeness.y) } val jrotation = JsonObject() jroot.add("snapRotation", jrotation) with(sceneResource.snapRotation) { jrotation.add("enabled", enabled) jrotation.add("step", stepDegrees) jrotation.add("closeness", closeness) } val jincludes = JsonArray() jroot.add("include", jincludes) sceneResource.includes.forEach { include -> jincludes.add(Resources.instance.sceneFileToPath(include)) } val jstages = JsonArray() jroot.add("stages", jstages) sceneResource.stageResources.forEach { stageName, stageResource -> jstages.add(saveStage(stageName, stageResource)) } BufferedWriter(OutputStreamWriter(FileOutputStream(file))).use { jroot.writeTo(it, Resources.instance.preferences.outputFormat.writerConfig) } } fun saveStage(stageName: String, stageResource: StageResource): JsonObject { val jstage = JsonObject() jstage.add("name", stageName) val jactors = JsonArray() jstage.add("actors", jactors) stageResource.actorResources.forEach { actorResource -> val costume = Resources.instance.costumes.find(actorResource.costumeName) val jactor = JsonObject() jactors.add(jactor) with(actorResource) { jactor.add("costume", costumeName) jactor.add("x", x) jactor.add("y", y) if (zOrder != costume?.zOrder) { // Only save zOrders which are NOT the default zOrder for the Costume. jactor.add("zOrder", zOrder) } textStyle?.let { textStyle -> jactor.add("text", text) if (textStyle.fontResource != costumeTextStyle?.fontResource) { jactor.add("font", Resources.instance.fontResources.findName(textStyle.fontResource)) } if (textStyle.halignment != costumeTextStyle?.halignment) { jactor.add("textHAlignment", textStyle.halignment.name) } if (textStyle.valignment != costumeTextStyle?.valignment) { jactor.add("textVAlignment", textStyle.valignment.name) } if (textStyle.color != costumeTextStyle?.color) { jactor.add("textColor", textStyle.color.toHashRGBA()) } if (textStyle.outlineColor != null && textStyle.outlineColor != costumeTextStyle?.outlineColor) { jactor.add("textOutlineColor", textStyle.outlineColor!!.toHashRGBA()) } } if (viewAlignmentX != ActorXAlignment.LEFT) { jactor.add("viewAlignmentX", viewAlignmentX.name) } if (viewAlignmentY != ActorYAlignment.BOTTOM) { jactor.add("viewAlignmentY", viewAlignmentY.name) } jactor.add("direction", direction.degrees) jactor.add("scaleX", scale.x) jactor.add("scaleY", scale.y) if (isSizable()) { jactor.add("sizeX", size.x) jactor.add("sizeY", size.y) jactor.add("alignmentX", sizeAlignment.x) jactor.add("alignmentY", sizeAlignment.y) } } JsonUtil.saveAttributes(jactor, actorResource.attributes) } return jstage } }
gpl-3.0
1daf072d9614c4cf2fd34f71c5e784c4
35.410569
119
0.586134
4.739153
false
false
false
false
luxons/seven-wonders
sw-engine/src/main/kotlin/org/luxons/sevenwonders/engine/boards/Military.kt
1
871
package org.luxons.sevenwonders.engine.boards import org.luxons.sevenwonders.model.Age internal class Military( private val lostPointsPerDefeat: Int, private val wonPointsPerVictoryPerAge: Map<Age, Int>, ) { var nbShields = 0 private set val totalPoints get() = victoryPoints - lostPointsPerDefeat * nbDefeatTokens var victoryPoints = 0 private set var nbDefeatTokens = 0 private set internal fun addShields(nbShields: Int) { this.nbShields += nbShields } internal fun victory(age: Age) { val wonPoints = wonPointsPerVictoryPerAge[age] ?: throw UnknownAgeException(age) victoryPoints += wonPoints } internal fun defeat() { nbDefeatTokens++ } internal class UnknownAgeException(unknownAge: Age) : IllegalArgumentException(unknownAge.toString()) }
mit
c85a2a4f81fe464a8e688460d7f7aacf
23.885714
105
0.687715
4.333333
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/social/profile/ChangeAboutMeModalExecutor.kt
1
3404
package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.social.profile import dev.kord.common.entity.TextInputStyle import io.github.netvl.ecoji.Ecoji import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.Json import net.perfectdreams.discordinteraktions.common.builder.message.modify.InteractionOrFollowupMessageModifyBuilder import net.perfectdreams.discordinteraktions.common.modals.components.ModalArguments import net.perfectdreams.discordinteraktions.common.modals.components.ModalComponents import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.GuildApplicationCommandContext import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.styled import net.perfectdreams.loritta.cinnamon.discord.interactions.modals.CinnamonModalExecutor import net.perfectdreams.loritta.cinnamon.discord.interactions.modals.CinnamonModalExecutorDeclaration import net.perfectdreams.loritta.cinnamon.discord.interactions.modals.ModalContext import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.social.declarations.ProfileCommand import net.perfectdreams.loritta.cinnamon.discord.utils.ComponentExecutorIds import net.perfectdreams.loritta.cinnamon.discord.utils.getOrCreateUserProfile import net.perfectdreams.loritta.cinnamon.emotes.Emotes class ChangeAboutMeModalExecutor(loritta: LorittaBot) : CinnamonModalExecutor(loritta) { companion object : CinnamonModalExecutorDeclaration(ComponentExecutorIds.CHANGE_ABOUT_ME_MODAL_SUBMIT_EXECUTOR) { object Options : ModalComponents() { val aboutMe = textInput("about_me", TextInputStyle.Paragraph) } override val options = Options } override suspend fun onSubmit(context: ModalContext, args: ModalArguments) { val newAboutMe = args[options.aboutMe] val data = loritta.decodeDataFromComponentOnDatabase<ChangeAboutMeModalData>(context.data) val userSettings = context.loritta.pudding.users.getOrCreateUserProfile(context.user) .getProfileSettings() userSettings.setAboutMe(newAboutMe) context.sendEphemeralMessage { styled( context.i18nContext.get(ProfileCommand.ABOUT_ME_I18N_PREFIX.SuccessfullyChanged(newAboutMe)), Emotes.Tada ) } val guild = context.interaKTionsModalContext.discordInteraction.guildId.value?.let { loritta.kord.getGuild(it) } val result = loritta.profileDesignManager.createProfile( loritta, context.i18nContext, context.locale, loritta.profileDesignManager.transformUserToProfileUserInfoData(context.user), loritta.profileDesignManager.transformUserToProfileUserInfoData(context.user), guild?.let { loritta.profileDesignManager.transformGuildToProfileGuildInfoData(it) } ) val message = ProfileExecutor.createMessage(loritta, context.i18nContext, context.user, context.user, result) loritta.rest.interaction.modifyInteractionResponse( loritta.interaKTions.applicationId, data.data!!.interactionToken, InteractionOrFollowupMessageModifyBuilder().apply { message() }.toInteractionMessageResponseModifyBuilder() .toRequest() ) } }
agpl-3.0
6b55880c05c72d296a72643ccdc750ba
48.347826
120
0.770858
5.165402
false
false
false
false
NoodleMage/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryGridHolder.kt
3
2163
package eu.kanade.tachiyomi.ui.library import android.view.View import com.bumptech.glide.load.engine.DiskCacheStrategy import eu.davidea.flexibleadapter.FlexibleAdapter import eu.kanade.tachiyomi.data.glide.GlideApp import eu.kanade.tachiyomi.source.LocalSource import kotlinx.android.synthetic.main.catalogue_grid_item.* /** * Class used to hold the displayed data of a manga in the library, like the cover or the title. * All the elements from the layout file "item_catalogue_grid" are available in this class. * * @param view the inflated view for this holder. * @param adapter the adapter handling this holder. * @param listener a listener to react to single tap and long tap events. * @constructor creates a new library holder. */ class LibraryGridHolder( private val view: View, private val adapter: FlexibleAdapter<*> ) : LibraryHolder(view, adapter) { /** * Method called from [LibraryCategoryAdapter.onBindViewHolder]. It updates the data for this * holder with the given manga. * * @param item the manga item to bind. */ override fun onSetValues(item: LibraryItem) { // Update the title of the manga. title.text = item.manga.title // Update the unread count and its visibility. with(unread_text) { visibility = if (item.manga.unread > 0) View.VISIBLE else View.GONE text = item.manga.unread.toString() } // Update the download count and its visibility. with(download_text) { visibility = if (item.downloadCount > 0) View.VISIBLE else View.GONE text = item.downloadCount.toString() } //set local visibility if its local manga local_text.visibility = if(item.manga.source == LocalSource.ID) View.VISIBLE else View.GONE // Update the cover. GlideApp.with(view.context).clear(thumbnail) GlideApp.with(view.context) .load(item.manga) .diskCacheStrategy(DiskCacheStrategy.RESOURCE) .centerCrop() .into(thumbnail) } }
apache-2.0
a993c9ab24227454f6335bb680fdbc59
35.947368
99
0.655571
4.487552
false
false
false
false
EmmanuelMess/Simple-Accounting
SimpleAccounting/app/src/main/java/com/emmanuelmess/simpleaccounting/activities/views/SpinnerNoUnwantedOnClick.kt
1
4384
package com.emmanuelmess.simpleaccounting.activities.views import android.view.View import android.widget.AdapterView import android.widget.AdapterView.OnItemSelectedListener import android.widget.Spinner import android.widget.SpinnerAdapter /** * Spinner Helper class that works around some common issues * with the stock Android Spinner * * A Spinner will normally call it's OnItemSelectedListener * when you use setSelection(...) in your initialization code. * This is usually unwanted behavior, and a common work-around * is to use spinner.post(...) with a Runnable to assign the * OnItemSelectedListener after layout. * * If you do not call setSelection(...) manually, the callback * may be called with the first item in the adapter you have * set. The common work-around for that is to count callbacks. * * While these workarounds usually *seem* to work, the callback * may still be called repeatedly for other reasons while the * selection hasn't actually changed. This will happen for * example, if the user has accessibility options enabled - * which is more common than you might think as several apps * use this for different purposes, like detecting which * notifications are active. * * Ideally, your OnItemSelectedListener callback should be * coded defensively so that no problem would occur even * if the callback was called repeatedly with the same values * without any user interaction, so no workarounds are needed. * * This class does that for you. It keeps track of the values * you have set with the setSelection(...) methods, and * proxies the OnItemSelectedListener callback so your callback * only gets called if the selected item's position differs * from the one you have set by code, or the first item if you * did not set it. * * This also means that if the user actually clicks the item * that was previously selected by code (or the first item * if you didn't set a selection by code), the callback will * not fire. * * To implement, replace current occurrences of: * * Spinner spinner = * (Spinner)findViewById(R.id.xxx); * * with: * * SpinnerHelper spinner = * new SpinnerHelper(findViewById(R.id.xxx)) * * SpinnerHelper proxies the (my) most used calls to Spinner * but not all of them. Should a method not be available, use: * * spinner.getSpinner().someMethod(...) * * Or just add the proxy method yourself :) * * (Quickly) Tested on devices from 2.3.6 through 4.2.2 * * @author Jorrit "Chainfire" Jongma * license WTFPL (do whatever you want with this, nobody cares) */ class SpinnerNoUnwantedOnClick(val spinner: Spinner) : OnItemSelectedListener { private var lastPosition = -1 private var proxiedItemSelectedListener: OnItemSelectedListener? = null var adapter: SpinnerAdapter get() = spinner.adapter set(adapter) { if (adapter.count > 0) { lastPosition = 0 } spinner.adapter = adapter } val count: Int get() = spinner.count val selectedItem: Any get() = spinner.selectedItem val selectedItemId: Long get() = spinner.selectedItemId val selectedItemPosition: Int get() = spinner.selectedItemPosition var isEnabled: Boolean get() = spinner.isEnabled set(enabled) { spinner.isEnabled = enabled } fun setSelection(position: Int) { lastPosition = Math.max(-1, position) spinner.setSelection(position) } fun setSelection(position: Int, animate: Boolean) { lastPosition = Math.max(-1, position) spinner.setSelection(position, animate) } fun setOnItemSelectedListener(listener: OnItemSelectedListener?) { proxiedItemSelectedListener = listener spinner.onItemSelectedListener = if (listener == null) null else this } override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) { if (position != lastPosition) { lastPosition = position if (proxiedItemSelectedListener != null) { proxiedItemSelectedListener!!.onItemSelected( parent, view, position, id ) } } } override fun onNothingSelected(parent: AdapterView<*>) { if (-1 != lastPosition) { lastPosition = -1 if (proxiedItemSelectedListener != null) { proxiedItemSelectedListener!!.onNothingSelected( parent ) } } } fun getItemAtPosition(position: Int): Any = spinner.getItemAtPosition(position) fun getItemIdAtPosition(position: Int): Long = spinner.getItemIdAtPosition(position) }
gpl-3.0
c3a242b554e4703cb429bf647e4305ed
31.007299
91
0.74042
4.171265
false
false
false
false
danrien/projectBlue
projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/playback/file/exoplayer/preparation/GivenUris/AndAnErrorOccursGettingNewRenderers/WhenPreparing.kt
2
1686
package com.lasthopesoftware.bluewater.client.playback.file.exoplayer.preparation.GivenUris.AndAnErrorOccursGettingNewRenderers import android.net.Uri import com.google.android.exoplayer2.LoadControl import com.google.android.exoplayer2.source.BaseMediaSource import com.google.android.exoplayer2.upstream.DefaultAllocator import com.lasthopesoftware.bluewater.client.browsing.items.media.files.ServiceFile import com.lasthopesoftware.bluewater.client.playback.file.exoplayer.preparation.ExoPlayerPlaybackPreparer import com.lasthopesoftware.bluewater.shared.promises.extensions.toFuture import com.namehillsoftware.handoff.promises.Promise import io.mockk.mockk import org.assertj.core.api.Assertions.assertThat import org.joda.time.Duration import org.junit.BeforeClass import org.junit.Test import org.mockito.Mockito import java.util.concurrent.ExecutionException import java.util.concurrent.TimeUnit class WhenPreparing { companion object { private var exception: Throwable? = null @BeforeClass @JvmStatic fun before() { val loadControl = Mockito.mock(LoadControl::class.java) Mockito.`when`(loadControl.allocator).thenReturn(DefaultAllocator(true, 1024)) val preparer = ExoPlayerPlaybackPreparer( mockk(relaxed = true), { mockk<BaseMediaSource>() }, loadControl, { Promise(Exception("Oops")) }, mockk(), mockk(), { Promise(mockk<Uri>()) } ) try { preparer.promisePreparedPlaybackFile(ServiceFile(1), Duration.ZERO).toFuture()[1, TimeUnit.SECONDS] } catch (ex: ExecutionException) { exception = ex.cause } } } @Test fun thenAnExceptionIsThrown() { assertThat(exception?.message).isEqualTo("Oops") } }
lgpl-3.0
419391be4ca6847d30e2b5364db166a5
31.423077
127
0.786477
3.957746
false
false
false
false
FurhatRobotics/example-skills
Quiz/src/main/kotlin/furhatos/app/quiz/flow/main/endGame.kt
1
2737
package furhatos.app.quiz.flow.main import furhatos.app.quiz.flow.Parent import furhatos.app.quiz.setting.playing import furhatos.app.quiz.setting.quiz import furhatos.flow.kotlin.State import furhatos.flow.kotlin.furhat import furhatos.flow.kotlin.state import furhatos.flow.kotlin.users // End of game, announcing results val EndGame: State = state(parent = Parent) { var skipNext = false onEntry { playing = false // If multiple players, we rank the players on points and congratulate the winner. A special case is when we have a tie. if (users.playing().count() > 1) { // Sort users by score users.playing().sortedByDescending { it.quiz.score }.forEachIndexed { index, user -> // The winner(s) if (index == 0) { val highestScore = user.quiz.score val usersWithHighestScore = users.playing().filter { it.quiz.score == highestScore } // Check if we have more than one user with the highest score and if so announce a tie if (usersWithHighestScore.count() > 1) { furhat.say("Wow, we have a tie! You each have $highestScore points", async = true) delay(500) usersWithHighestScore.forEach { furhat.attend(it) delay(700) } // If a tie, we skip the next user since we've already adressed them above skipNext = true } // A single winner exists else { furhat.attend(user) furhat.say("Congratulations! You won with ${user.quiz.score} points") } } // Every other subsequent player else { if (!skipNext) { skipNext = false furhat.attend(user) furhat.say("And you got ${user.quiz.score} points") } } delay(300) } } // Only one player, we simply announce the score else { furhat.say("You got ${users.current.quiz.score} points.") } furhat.say("Thanks for playing!") // Resetting user state variables users.playing().forEach { it.quiz.playing = false it.quiz.played = true it.quiz.lastScore = it.quiz.score } delay(1000) goto(Idle) } }
mit
022c6f9a7117498273f46fe0a5baefba
34.558442
128
0.496894
5.012821
false
false
false
false
ruuvi/Android_RuuvitagScanner
app/src/main/java/com/ruuvi/station/settings/ui/AppSettingsGatewayFragment.kt
1
4421
package com.ruuvi.station.settings.ui import android.graphics.Color import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.view.View import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import com.ruuvi.station.util.extensions.viewModel import com.ruuvi.station.R import com.ruuvi.station.settings.domain.GatewayTestResultType import com.ruuvi.station.util.extensions.makeWebLinks import com.ruuvi.station.util.extensions.setDebouncedOnClickListener import kotlinx.android.synthetic.main.fragment_app_settings_gateway.* import kotlinx.android.synthetic.main.fragment_app_settings_gateway.settingsInfoTextView import kotlinx.coroutines.flow.collect import kotlinx.coroutines.launch import org.kodein.di.Kodein import org.kodein.di.KodeinAware import org.kodein.di.android.support.closestKodein class AppSettingsGatewayFragment : Fragment(R.layout.fragment_app_settings_gateway) , KodeinAware { override val kodein: Kodein by closestKodein() private val viewModel: AppSettingsGatewayViewModel by viewModel() override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupViews() observeGatewayUrl() observeDeviceId() observeTestGatewayResult() } private fun setupViews() { gatewayUrlEditText.addTextChangedListener( object: TextWatcher { override fun afterTextChanged(s: Editable?) { viewModel.setGatewayUrl(s.toString()) } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {} }) deviceIdEditText.addTextChangedListener( object: TextWatcher { override fun afterTextChanged(s: Editable?) { viewModel.setDeviceId(s.toString()) } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {} }) settingsInfoTextView.makeWebLinks(requireActivity(), Pair(getString(R.string.settings_gateway_details_link), getString(R.string.settings_gateway_details_link_url))) gatewayTestButton.setDebouncedOnClickListener { viewModel.testGateway() gatewayTestResultTextView.visibility = View.VISIBLE } } fun observeGatewayUrl() { lifecycleScope.launch { viewModel.observeGatewayUrl.collect { gatewayUrlEditText.setText(it) } } } fun observeDeviceId() { lifecycleScope.launch { viewModel.observeDeviceId.collect { deviceIdEditText.setText(it) } } } fun observeTestGatewayResult() { lifecycleScope.launch { viewModel.observeTestGatewayResult.collect{ when (it.type) { GatewayTestResultType.NONE -> { gatewayTestResultTextView.text = "" gatewayTestResultTextView.setTextColor(Color.DKGRAY) } GatewayTestResultType.TESTING -> { gatewayTestResultTextView.text = getString(R.string.gateway_testing) gatewayTestResultTextView.setTextColor(Color.DKGRAY) } GatewayTestResultType.SUCCESS -> { gatewayTestResultTextView.text = getString(R.string.gateway_test_success, it.code) gatewayTestResultTextView.setTextColor(Color.GREEN) } GatewayTestResultType.FAIL -> { gatewayTestResultTextView.text = getString(R.string.gateway_test_fail, it.code) gatewayTestResultTextView.setTextColor(Color.RED) } GatewayTestResultType.EXCEPTION -> { gatewayTestResultTextView.text = getString(R.string.gateway_test_exception) gatewayTestResultTextView.setTextColor(Color.RED) } } } } } companion object { fun newInstance() = AppSettingsGatewayFragment() } }
mit
f7ca7322849a6e49e0b2a6bd00456262
37.789474
172
0.646686
5.345828
false
true
false
false
ngageoint/mage-android
mage/src/main/java/mil/nga/giat/mage/form/edit/dialog/DMSCoordinateTextWatcher.kt
1
4705
package mil.nga.giat.mage.form.edit.dialog import android.text.Editable import android.text.Spannable import android.text.TextWatcher import android.widget.EditText import mil.nga.giat.mage.coordinate.CoordinateType import mil.nga.giat.mage.coordinate.MutableDMSLocation class DMSCoordinateTextWatcher( private val editText: EditText, private val coordinateType: CoordinateType, val onSplitCoordinates: (Pair<String, String>) -> Unit ): TextWatcher { private var span: Any = Unit override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { editText.text.setSpan(span, start, start + count, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) } override fun afterTextChanged(s: Editable?) { val text = s?.toString() ?: return val start: Int = editText.text.getSpanStart(span) val end: Int = editText.text.getSpanEnd(span) val count = end - start val replacement = if (count > 0) { val replaced = text.subSequence(start, start + count) text.replaceRange(start until start + count, replaced).uppercase() } else "" if (replacement.isEmpty() || ("-" == text && start == 0 && count == 0)) { return } if ("." == replacement) { updateText() return } val coordinates = if (count > 1) splitCoordinates(text) else emptyList() if (coordinates.size == 2) { updateText() onSplitCoordinates(coordinates.zipWithNext().first()) } else { val dms = parseDMS(text, addDirection = count > 1) val selection = if (dms.lastIndex > end) { val nextDigitIndex = dms.substring(start + 1).indexOfFirst { it.isDigit() } if (nextDigitIndex != -1) { start + nextDigitIndex + 1 } else null } else null updateText(dms) selection?.let { editText.setSelection(it) } } } private fun updateText(text: String? = null) { editText.removeTextChangedListener(this) editText.text.clear() text?.let { editText.append(it) } editText.addTextChangedListener(this) } private fun parseDMS(text: String, addDirection: Boolean): String { if (text.isEmpty()) { return "" } val dms = MutableDMSLocation.parse(text, coordinateType, addDirection) val degrees = dms.degrees?.let { degrees -> "$degrees° " } ?: "" val minutes = dms.minutes?.let { minutes -> val padded = minutes.toString().padStart(2, '0') "${padded}\" " } ?: "" val seconds = dms.seconds?.let { seconds -> val padded = seconds.toString().padStart(2, '0') "${padded}\' " } ?: "" val direction = dms.direction ?: "" return "$degrees$minutes$seconds$direction" } private fun splitCoordinates(text: String): List<String> { val coordinates = mutableListOf<String>() val parsable = text.lines().joinToString().trim() // if there is a comma, split on that if (parsable.contains(',')) { return parsable.split(",").map { coordinate -> coordinate.trim() } } // Check if there are any direction letters val firstDirectionIndex = parsable.indexOfFirst { "NSEW".contains(it.uppercase()) } if (firstDirectionIndex != -1) { if (parsable.contains('-')) { // Split coordinates on dash return parsable.split("-").map { coordinate -> coordinate.trim() } } else { // No dash, split on the direction val lastDirectionIndex = parsable.indexOfLast { "NSEW".contains(it.uppercase()) } if (firstDirectionIndex == 0) { if (lastDirectionIndex != firstDirectionIndex) { return listOf( parsable.substring(0, lastDirectionIndex - 1), parsable.substring(lastDirectionIndex) ) } } else if (lastDirectionIndex == parsable.lastIndex) { if (lastDirectionIndex != firstDirectionIndex) { return listOf( parsable.substring(0, firstDirectionIndex + 1), parsable.substring(firstDirectionIndex + 1) ) } } } } // If there is one white space character split on that val parts = parsable.split(" ") if (parts.size == 2) { return parts.map { coordinate -> coordinate.trim() } } return coordinates } }
apache-2.0
81ce0eaa4b3efacdbd4820c341629ac2
31.006803
93
0.583759
4.580331
false
false
false
false
Dreamersoul/FastHub
app/src/main/java/com/fastaccess/ui/modules/repos/wiki/WikiPresenter.kt
1
3734
package com.fastaccess.ui.modules.repos.wiki import android.content.Intent import com.fastaccess.data.dao.wiki.WikiContentModel import com.fastaccess.data.dao.wiki.WikiSideBarModel import com.fastaccess.helper.BundleConstant import com.fastaccess.helper.Logger import com.fastaccess.helper.RxHelper import com.fastaccess.provider.rest.jsoup.JsoupProvider import com.fastaccess.ui.base.mvp.presenter.BasePresenter import io.reactivex.Observable import org.jsoup.Jsoup import org.jsoup.nodes.Document /** * Created by Kosh on 13 Jun 2017, 8:14 PM */ class WikiPresenter : BasePresenter<WikiMvp.View>(), WikiMvp.Presenter { @com.evernote.android.state.State var repoId: String? = null @com.evernote.android.state.State var login: String? = null override fun onActivityCreated(intent: Intent?) { if (intent != null) { val bundle = intent.extras repoId = bundle.getString(BundleConstant.ID) login = bundle.getString(BundleConstant.EXTRA) val page = bundle.getString(BundleConstant.EXTRA_TWO) if (!repoId.isNullOrEmpty() && !login.isNullOrEmpty()) { onSidebarClicked(WikiSideBarModel("Home", "$login/$repoId/wiki" + if (!page.isNullOrEmpty()) "/$page" else "")) } } } override fun onSidebarClicked(sidebar: WikiSideBarModel) { manageViewDisposable(RxHelper.getObservable(JsoupProvider.getWiki().getWiki(sidebar.link)) .flatMap { s -> RxHelper.getObservable(getWikiContent(s)) } .doOnSubscribe { sendToView { it.showProgress(0) } } .subscribe({ response -> sendToView { view -> view.onLoadContent(response) } }, { throwable -> onError(throwable) }, { sendToView({ it.hideProgress() }) })) } private fun getWikiContent(body: String?): Observable<WikiContentModel> { return Observable.fromPublisher { s -> val document: Document = Jsoup.parse(body, "") val wikiWrapper = document.select("#wiki-wrapper") if (wikiWrapper.isNotEmpty()) { val cloneUrl = wikiWrapper.select(".clone-url") val bottomRightBar = wikiWrapper.select(".wiki-custom-sidebar") if (cloneUrl.isNotEmpty()) { cloneUrl.remove() } if (bottomRightBar.isNotEmpty()) { bottomRightBar.remove() } val headerHtml = wikiWrapper.select(".gh-header .gh-header-meta") val revision = headerHtml.select("a.history") if (revision.isNotEmpty()) { revision.remove() } val header = "<div class='gh-header-meta'>${headerHtml.html()}</div>" val wikiContent = wikiWrapper.select(".wiki-content") val content = header + wikiContent.select(".markdown-body").html() val rightBarList = wikiContent.select(".wiki-pages").select("li") val sidebarList = arrayListOf<WikiSideBarModel>() if (rightBarList.isNotEmpty()) { rightBarList.onEach { val sidebarTitle = it.select("a").text() val sidebarLink = it.select("a").attr("href") sidebarList.add(WikiSideBarModel(sidebarTitle, sidebarLink)) } } Logger.d(header) s.onNext(WikiContentModel(content, "", sidebarList)) } else { s.onNext(WikiContentModel("<h2 align='center'>No Wiki</h4>", "", arrayListOf())) } s.onComplete() } } }
gpl-3.0
4ac3883d97120c595972c84513804d8c
44.54878
100
0.592662
4.849351
false
false
false
false
robinverduijn/gradle
subprojects/kotlin-dsl/src/test/kotlin/org/gradle/kotlin/dsl/resolver/ProjectRootOfTest.kt
1
3674
package org.gradle.kotlin.dsl.resolver import org.gradle.kotlin.dsl.fixtures.FolderBasedTest import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.MatcherAssert.assertThat import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized @RunWith(Parameterized::class) class ProjectRootOfTest(private val settingsFileName: String) : FolderBasedTest() { companion object { @Parameterized.Parameters(name = "{0}") @JvmStatic fun testCases() = listOf(arrayOf("settings.gradle"), arrayOf("settings.gradle.kts")) } @Test fun `given a script file under a nested project it should return the nested project root`() { withFolders { "root" { "nested-project-root" { // a nested project is detected by the presence of a settings file withFile(settingsFileName) "sub-project" { withFile("build.gradle.kts") } } } } assertThat( projectRootOf( scriptFile = file("root/nested-project-root/sub-project/build.gradle.kts"), importedProjectRoot = folder("root")), equalTo(folder("root/nested-project-root"))) } @Test fun `given a script file under a separate project it should return the separate project root`() { withFolders { "root" { } "separate-project-root" { withFile("build.gradle.kts") } } assertThat( projectRootOf( scriptFile = file("separate-project-root/build.gradle.kts"), importedProjectRoot = folder("root"), stopAt = root), equalTo(folder("separate-project-root"))) } @Test fun `given a script file under a separate nested project it should return the separate nested project root`() { withFolders { "root" { } "separate" { "nested-project-root" { // a nested project is detected by the presence of a settings file withFile(settingsFileName) "sub-project" { withFile("build.gradle.kts") } } } } assertThat( projectRootOf( scriptFile = file("separate/nested-project-root/sub-project/build.gradle.kts"), importedProjectRoot = folder("root")), equalTo(folder("separate/nested-project-root"))) } @Test fun `given a script file under the imported project it should return the imported project root`() { withFolders { "root" { "sub-project" { withFile("build.gradle.kts") } } } assertThat( projectRootOf( scriptFile = file("root/sub-project/build.gradle.kts"), importedProjectRoot = folder("root")), equalTo(folder("root"))) } @Test fun `given a script file in buildSrc it should return the buildSrc project root`() { withFolders { "root" { "buildSrc" { withFile("build.gradle.kts") } } } assertThat( projectRootOf( scriptFile = file("root/buildSrc/build.gradle.kts"), importedProjectRoot = folder("root")), equalTo(folder("root/buildSrc"))) } }
apache-2.0
6f120fc924e2d8279312b874bbf8f580
28.869919
115
0.529668
5.181946
false
true
false
false
HendraAnggrian/kota
kota/src/dialogs/ItemsAlerts.kt
1
1851
@file:JvmMultifileClass @file:JvmName("DialogsKt") @file:Suppress("NOTHING_TO_INLINE", "UNUSED") package kota import android.app.AlertDialog import android.app.Fragment import android.content.Context import android.content.DialogInterface import android.support.annotation.ArrayRes import android.support.annotation.StringRes @JvmOverloads inline fun Context.itemsAlert( items: Array<out CharSequence>, title: CharSequence? = null, noinline action: (dialog: DialogInterface, Int) -> Unit, noinline init: (AlertDialog.() -> Unit)? = null ): AlertDialog = AlertDialog.Builder(this) .setItems(items, DialogInterface.OnClickListener(action)) .apply { title?.let { setTitle(it) } } .create() .apply { init?.invoke(this) } @JvmOverloads inline fun Fragment.itemsAlert( items: Array<out CharSequence>, title: CharSequence? = null, noinline action: (dialog: DialogInterface, Int) -> Unit, noinline init: (AlertDialog.() -> Unit)? = null ): AlertDialog = activity.itemsAlert(items, title, action, init) @JvmOverloads inline fun Context.itemsAlert( @ArrayRes items: Int, @StringRes titleId: Int? = null, noinline action: (dialog: DialogInterface, Int) -> Unit, noinline init: (AlertDialog.() -> Unit)? = null ): AlertDialog = AlertDialog.Builder(this) .setItems(items, DialogInterface.OnClickListener(action)) .apply { titleId?.let { setTitle(it) } } .create() .apply { init?.invoke(this) } @JvmOverloads inline fun Fragment.itemsAlert( @ArrayRes items: Int, @StringRes titleId: Int? = null, noinline action: (dialog: DialogInterface, Int) -> Unit, noinline init: (AlertDialog.() -> Unit)? = null ): AlertDialog = activity.itemsAlert(items, titleId, action, init)
apache-2.0
e889521daf177a09f19322cca34172bd
34.615385
66
0.676931
4.334895
false
false
false
false
mrkirby153/KirBot
src/main/kotlin/me/mrkirby153/KirBot/command/executors/msc/CommandPing.kt
1
1422
package me.mrkirby153.KirBot.command.executors.msc import me.mrkirby153.KirBot.Bot import me.mrkirby153.KirBot.command.CommandCategory import me.mrkirby153.KirBot.command.annotations.Command import me.mrkirby153.KirBot.command.annotations.CommandDescription import me.mrkirby153.KirBot.command.args.CommandContext import me.mrkirby153.KirBot.utils.Context import me.mrkirby153.KirBot.utils.globalAdmin import me.mrkirby153.kcutils.Time import net.dv8tion.jda.api.sharding.ShardManager import javax.inject.Inject import kotlin.math.roundToLong class CommandPing @Inject constructor(private val shardManager: ShardManager){ @Command(name = "ping", category = CommandCategory.MISCELLANEOUS) @CommandDescription("Check the bot's ping") fun execute(context: Context, cmdContext: CommandContext) { val start = System.currentTimeMillis() context.channel.sendTyping().queue { val stop = System.currentTimeMillis() val adminMsg = "Ping: `${Time.format(1, stop - start)}`\nHeartbeat: `${Time.format(1, context.jda.gatewayPing)}` \nAverage across all shards (${shardManager.shards.size}): `${Time.format( 1, shardManager.averageGatewayPing.roundToLong())}`" val msg = "Pong! `${Time.format(1, stop - start)}`" context.channel.sendMessage(if(context.author.globalAdmin) adminMsg else msg).queue() } } }
mit
ff86ab38eb7f3987a7301055d1fb2f81
44.903226
121
0.729255
4.121739
false
false
false
false
HendraAnggrian/kota
kota/src/Bundles.kt
1
5102
@file:Suppress("NOTHING_TO_INLINE", "UNUSED") package kota import android.os.Bundle import android.os.Parcelable import java.io.Serializable inline fun bundleOf(key: String, value: Boolean): Bundle = Bundle().apply { putBoolean(key, value) } inline fun bundleOf(key: String, value: Byte): Bundle = Bundle().apply { putByte(key, value) } inline fun bundleOf(key: String, value: Char): Bundle = Bundle().apply { putChar(key, value) } inline fun bundleOf(key: String, value: Short): Bundle = Bundle().apply { putShort(key, value) } inline fun bundleOf(key: String, value: Int): Bundle = Bundle().apply { putInt(key, value) } inline fun bundleOf(key: String, value: Long): Bundle = Bundle().apply { putLong(key, value) } inline fun bundleOf(key: String, value: Float): Bundle = Bundle().apply { putFloat(key, value) } inline fun bundleOf(key: String, value: Double): Bundle = Bundle().apply { putDouble(key, value) } inline fun bundleOf(key: String, value: String): Bundle = Bundle().apply { putString(key, value) } inline fun bundleOf(key: String, value: CharSequence): Bundle = Bundle().apply { putCharSequence(key, value) } inline fun bundleOf(key: String, value: Parcelable): Bundle = Bundle().apply { putParcelable(key, value) } inline fun bundleOf(key: String, value: Serializable): Bundle = Bundle().apply { putSerializable(key, value) } inline fun bundleOf(key: String, value: BooleanArray): Bundle = Bundle().apply { putBooleanArray(key, value) } inline fun bundleOf(key: String, value: ByteArray): Bundle = Bundle().apply { putByteArray(key, value) } inline fun bundleOf(key: String, value: CharArray): Bundle = Bundle().apply { putCharArray(key, value) } inline fun bundleOf(key: String, value: DoubleArray): Bundle = Bundle().apply { putDoubleArray(key, value) } inline fun bundleOf(key: String, value: FloatArray): Bundle = Bundle().apply { putFloatArray(key, value) } inline fun bundleOf(key: String, value: IntArray): Bundle = Bundle().apply { putIntArray(key, value) } inline fun bundleOf(key: String, value: LongArray): Bundle = Bundle().apply { putLongArray(key, value) } inline fun bundleOf(key: String, value: ShortArray): Bundle = Bundle().apply { putShortArray(key, value) } inline fun bundleOf(key: String, value: Bundle): Bundle = Bundle().apply { putBundle(key, value) } inline fun bundleOf(key: String, value: Array<*>): Bundle { val bundle = Bundle() @Suppress("UNCHECKED_CAST") when { value.isArrayOf<Parcelable>() -> bundle.putParcelableArray(key, value as Array<out Parcelable>) value.isArrayOf<CharSequence>() -> bundle.putCharSequenceArray(key, value as Array<out CharSequence>) value.isArrayOf<String>() -> bundle.putStringArray(key, value as Array<out String>) else -> throw IllegalStateException("Unsupported bundle component (${value.javaClass})") } return bundle } inline fun bundleOf(vararg pairs: Pair<String, Any?>): Bundle = when { pairs.isEmpty() -> Bundle.EMPTY else -> { val bundle = Bundle() pairs.forEach { (key, value) -> when (value) { null -> bundle.putSerializable(key, null) is Boolean -> bundle.putBoolean(key, value) is Byte -> bundle.putByte(key, value) is Char -> bundle.putChar(key, value) is Short -> bundle.putShort(key, value) is Int -> bundle.putInt(key, value) is Long -> bundle.putLong(key, value) is Float -> bundle.putFloat(key, value) is Double -> bundle.putDouble(key, value) is String -> bundle.putString(key, value) is CharSequence -> bundle.putCharSequence(key, value) is Parcelable -> bundle.putParcelable(key, value) is Serializable -> bundle.putSerializable(key, value) is BooleanArray -> bundle.putBooleanArray(key, value) is ByteArray -> bundle.putByteArray(key, value) is CharArray -> bundle.putCharArray(key, value) is DoubleArray -> bundle.putDoubleArray(key, value) is FloatArray -> bundle.putFloatArray(key, value) is IntArray -> bundle.putIntArray(key, value) is LongArray -> bundle.putLongArray(key, value) is Array<*> -> @Suppress("UNCHECKED_CAST") when { value.isArrayOf<Parcelable>() -> bundle.putParcelableArray(key, value as Array<out Parcelable>) value.isArrayOf<CharSequence>() -> bundle.putCharSequenceArray(key, value as Array<out CharSequence>) value.isArrayOf<String>() -> bundle.putStringArray(key, value as Array<out String>) else -> throw IllegalStateException("Unsupported bundle component (${value.javaClass})") } is ShortArray -> bundle.putShortArray(key, value) is Bundle -> bundle.putBundle(key, value) else -> throw IllegalStateException("Unsupported bundle component (${value.javaClass})") } } bundle } }
apache-2.0
c55280eb3c0db837d93713cb2e097adc
62.7875
121
0.654645
4.421144
false
false
false
false
chrisbanes/tivi
common/ui/compose/src/main/java/app/tivi/common/compose/theme/Color.kt
1
1872
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.tivi.common.compose.theme import androidx.compose.material.Colors import androidx.compose.material.darkColors import androidx.compose.material.lightColors import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.compositeOver /** * Return the fully opaque color that results from compositing [onSurface] atop [surface] with the * given [alpha]. Useful for situations where semi-transparent colors are undesirable. */ fun Colors.compositedOnSurface(alpha: Float): Color { return onSurface.copy(alpha = alpha).compositeOver(surface) } private val Slate200 = Color(0xFF81A9B3) private val Slate600 = Color(0xFF4A6572) private val Slate800 = Color(0xFF232F34) private val Orange500 = Color(0xFFF9AA33) private val Orange700 = Color(0xFFC78522) val TiviLightColors = lightColors( primary = Slate800, onPrimary = Color.White, primaryVariant = Slate600, secondary = Orange700, secondaryVariant = Orange500, onSecondary = Color.Black ) val TiviDarkColors = darkColors( primary = Slate200, onPrimary = Color.Black, secondary = Orange500, onSecondary = Color.Black ).withBrandedSurface() fun Colors.withBrandedSurface() = copy( surface = primary.copy(alpha = 0.08f).compositeOver(this.surface) )
apache-2.0
c5478f52b33e788c23a67f59bcf4c6e6
31.275862
98
0.758013
3.949367
false
false
false
false
tobyt42/tube-status
src/main/java/uk/terhoeven/news/tube/mapper/ResponseMapper.kt
1
2090
package uk.terhoeven.news.tube.mapper import org.json.JSONArray import org.json.JSONObject import uk.terhoeven.news.tube.api.* import java.util.* class ResponseMapper { fun mapStatusResponse(apiResponse: JSONArray): StatusResponse { val statuses = ArrayList<LineStatus>() for (i in 0 until apiResponse.length()) { processStatuses(statuses, apiResponse.getJSONObject(i)) } return StatusResponse(statuses) } private fun processStatuses(statuses: MutableCollection<LineStatus>, lineJson: JSONObject) { val jsonStatuses = lineJson.getJSONArray("lineStatuses") for (i in 0 until jsonStatuses.length()) { val jsonStatus = jsonStatuses.getJSONObject(i) val validity = Validity(getValidityPeriods(jsonStatus.getJSONArray("validityPeriods"))) val severity = StatusSeverity.parse(jsonStatus.getString("statusSeverityDescription")) if (severity === StatusSeverity.GOOD_SERVICE) { val line = Line.parse(lineJson.getString("id")) val lineStatus = LineStatus(line, severity, validity) statuses.add(lineStatus) } else { val line = Line.parse(jsonStatus.getString("lineId")) val reason = jsonStatus.getString("reason") val disruptionJson = jsonStatus.getJSONObject("disruption") val disruption = Disruption(disruptionJson.getString("categoryDescription"), disruptionJson.getString("description")) val lineStatus = LineStatus(line, severity, validity, reason, disruption) statuses.add(lineStatus) } } } private fun getValidityPeriods(validityPeriods: JSONArray): List<ValidityPeriod> { val validities = ArrayList<ValidityPeriod>() for (i in 0 until validityPeriods.length()) { val period = validityPeriods.getJSONObject(i) validities.add(ValidityPeriod(period.getString("fromDate"), period.getString("toDate"))) } return validities } }
mit
15346415d3c3b4a410b966a75faed1b8
41.653061
133
0.657895
4.860465
false
false
false
false
paronos/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/ui/migration/SearchController.kt
3
3707
package eu.kanade.tachiyomi.ui.migration import android.app.Dialog import android.os.Bundle import com.afollestad.materialdialogs.MaterialDialog import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.data.preference.getOrDefault import eu.kanade.tachiyomi.ui.base.controller.DialogController import eu.kanade.tachiyomi.ui.catalogue.global_search.CatalogueSearchController import eu.kanade.tachiyomi.ui.catalogue.global_search.CatalogueSearchPresenter import uy.kohesive.injekt.injectLazy class SearchController( private var manga: Manga? = null ) : CatalogueSearchController(manga?.title) { private var newManga: Manga? = null override fun createPresenter(): CatalogueSearchPresenter { return SearchPresenter(initialQuery, manga!!) } override fun onSaveInstanceState(outState: Bundle) { outState.putSerializable(::manga.name, manga) outState.putSerializable(::newManga.name, newManga) super.onSaveInstanceState(outState) } override fun onRestoreInstanceState(savedInstanceState: Bundle) { super.onRestoreInstanceState(savedInstanceState) manga = savedInstanceState.getSerializable(::manga.name) as? Manga newManga = savedInstanceState.getSerializable(::newManga.name) as? Manga } fun migrateManga() { val target = targetController as? MigrationController ?: return val manga = manga ?: return val newManga = newManga ?: return router.popController(this) target.migrateManga(manga, newManga) } fun copyManga() { val target = targetController as? MigrationController ?: return val manga = manga ?: return val newManga = newManga ?: return router.popController(this) target.copyManga(manga, newManga) } override fun onMangaClick(manga: Manga) { newManga = manga val dialog = MigrationDialog() dialog.targetController = this dialog.showDialog(router) } override fun onMangaLongClick(manga: Manga) { // Call parent's default click listener super.onMangaClick(manga) } class MigrationDialog : DialogController() { private val preferences: PreferencesHelper by injectLazy() override fun onCreateDialog(savedViewState: Bundle?): Dialog { val prefValue = preferences.migrateFlags().getOrDefault() val preselected = MigrationFlags.getEnabledFlagsPositions(prefValue) return MaterialDialog.Builder(activity!!) .content(R.string.migration_dialog_what_to_include) .items(MigrationFlags.titles.map { resources?.getString(it) }) .alwaysCallMultiChoiceCallback() .itemsCallbackMultiChoice(preselected.toTypedArray(), { _, positions, _ -> // Save current settings for the next time val newValue = MigrationFlags.getFlagsFromPositions(positions) preferences.migrateFlags().set(newValue) true }) .positiveText(R.string.migrate) .negativeText(R.string.copy) .neutralText(android.R.string.cancel) .onPositive { _, _ -> (targetController as? SearchController)?.migrateManga() } .onNegative { _, _ -> (targetController as? SearchController)?.copyManga() } .build() } } }
apache-2.0
5cabae6dd216713554a020c1691d001d
35.712871
94
0.647694
5.326149
false
false
false
false
italoag/qksms
presentation/src/main/java/com/moez/QKSMS/feature/compose/editing/ComposeItem.kt
3
1845
/* * Copyright (C) 2019 Moez Bhatti <moez.bhatti@gmail.com> * * This file is part of QKSMS. * * QKSMS is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * QKSMS is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with QKSMS. If not, see <http://www.gnu.org/licenses/>. */ package com.moez.QKSMS.feature.compose.editing import com.moez.QKSMS.model.Contact import com.moez.QKSMS.model.ContactGroup import com.moez.QKSMS.model.Conversation import com.moez.QKSMS.model.PhoneNumber import io.realm.RealmList sealed class ComposeItem { abstract fun getContacts(): List<Contact> data class New(val value: Contact) : ComposeItem() { override fun getContacts(): List<Contact> = listOf(value) } data class Recent(val value: Conversation) : ComposeItem() { override fun getContacts(): List<Contact> = value.recipients.map { recipient -> recipient.contact ?: Contact(numbers = RealmList(PhoneNumber(address = recipient.address))) } } data class Starred(val value: Contact) : ComposeItem() { override fun getContacts(): List<Contact> = listOf(value) } data class Group(val value: ContactGroup) : ComposeItem() { override fun getContacts(): List<Contact> = value.contacts } data class Person(val value: Contact) : ComposeItem() { override fun getContacts(): List<Contact> = listOf(value) } }
gpl-3.0
f270816a31edd97b7a161fcddc64a09e
34.480769
103
0.707317
4.221968
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/anki/CollectionManager.kt
1
13511
/*************************************************************************************** * Copyright (c) 2022 Ankitects Pty Ltd <https://apps.ankiweb.net> * * * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 3 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with * * this program. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************************/ package com.ichi2.anki import android.annotation.SuppressLint import android.os.Build import androidx.annotation.VisibleForTesting import anki.backend.backendError import com.ichi2.libanki.Collection import com.ichi2.libanki.CollectionV16 import com.ichi2.libanki.Storage.collection import com.ichi2.libanki.importCollectionPackage import com.ichi2.utils.Threads import kotlinx.coroutines.* import net.ankiweb.rsdroid.Backend import net.ankiweb.rsdroid.BackendException import net.ankiweb.rsdroid.BackendFactory import net.ankiweb.rsdroid.Translations import timber.log.Timber import java.io.File object CollectionManager { /** * The currently active backend, which is created on demand via [ensureBackend], and * implicitly via [ensureOpen] and routines like [withCol]. * The backend is long-lived, and will generally only be closed when switching interface * languages or changing schema versions. A closed backend cannot be reused, and a new one * must be created. */ private var backend: Backend? = null /** * The current collection, which is opened on demand via [withCol]. If you need to * close and reopen the collection in an atomic operation, add a new method that * calls [withQueue], and then executes [ensureClosedInner] and [ensureOpenInner] inside it. * A closed collection can be detected via [withOpenColOrNull] or by checking [Collection.dbClosed]. */ private var collection: Collection? = null private var queue: CoroutineDispatcher = Dispatchers.IO.limitedParallelism(1) private val robolectric = "robolectric" == Build.FINGERPRINT @VisibleForTesting var emulateOpenFailure = false /** * Execute the provided block on a serial queue, to ensure concurrent access * does not happen. * It's important that the block is not suspendable - if it were, it would allow * multiple requests to be interleaved when a suspend point was hit. */ private suspend fun<T> withQueue(block: CollectionManager.() -> T): T { return withContext(queue) { this@CollectionManager.block() } } /** * Execute the provided block with the collection, opening if necessary. * * Parallel calls to this function are guaranteed to be serialized, so you can be * sure the collection won't be closed or modified by another thread. This guarantee * does not hold if legacy code calls [getColUnsafe]. */ suspend fun <T> withCol(block: Collection.() -> T): T { return withQueue { ensureOpenInner() block(collection!!) } } /** * Execute the provided block if the collection is already open. See [withCol] for more. * Since the block may return a null value, and a null value will also be returned in the * case of the collection being closed, if the calling code needs to distinguish between * these two cases, it should wrap the return value of the block in a class (eg Optional), * instead of returning a nullable object. */ suspend fun<T> withOpenColOrNull(block: Collection.() -> T): T? { return withQueue { if (collection != null && !collection!!.dbClosed) { block(collection!!) } else { null } } } /** * Return a handle to the backend, creating if necessary. This should only be used * for routines that don't depend on an open or closed collection, such as checking * the current progress state when importing a colpkg file. While the backend is * thread safe and can be accessed concurrently, if another thread closes the collection * and you call a routine that expects an open collection, it will result in an error. */ suspend fun getBackend(): Backend { return withQueue { ensureBackendInner() backend!! } } /** * Translations provided by the Rust backend/Anki desktop code. */ val TR: Translations get() { if (backend == null) { runBlocking { ensureBackend() } } // we bypass the lock here so that translations are fast - conflicts are unlikely, // as the backend is only ever changed on language preference change or schema switch return backend!!.tr } /** * Close the currently cached backend and discard it. Useful when enabling the V16 scheduler in the * dev preferences, or if the active language changes. Saves and closes the collection if open. */ suspend fun discardBackend() { withQueue { discardBackendInner() } } /** See [discardBackend]. This must only be run inside the queue. */ private fun discardBackendInner() { ensureClosedInner() if (backend != null) { backend!!.close() backend = null } } /** * Open the backend if it's not already open. */ private suspend fun ensureBackend() { withQueue { ensureBackendInner() } } /** See [ensureBackend]. This must only be run inside the queue. */ private fun ensureBackendInner() { if (backend == null) { backend = BackendFactory.getBackend(AnkiDroidApp.instance) } } /** * If the collection is open, close it. */ suspend fun ensureClosed(save: Boolean = true) { withQueue { ensureClosedInner(save = save) } } /** See [ensureClosed]. This must only be run inside the queue. */ private fun ensureClosedInner(save: Boolean = true) { if (collection == null) { return } try { collection!!.close(save = save) } catch (exc: Exception) { Timber.e("swallowing error on close: $exc") } collection = null } /** * Open the collection, if it's not already open. * * Automatically called by [withCol]. Can be called directly to ensure collection * is loaded at a certain point in time, or to ensure no errors occur. */ suspend fun ensureOpen() { withQueue { ensureOpenInner() } } /** See [ensureOpen]. This must only be run inside the queue. */ private fun ensureOpenInner() { ensureBackendInner() if (emulateOpenFailure) { throw BackendException.BackendDbException.BackendDbLockedException(backendError {}) } if (collection == null || collection!!.dbClosed) { val path = createCollectionPath() collection = collection(AnkiDroidApp.instance, path, server = false, log = true, backend) } } /** Ensures the AnkiDroid directory is created, then returns the path to the collection file * inside it. */ fun createCollectionPath(): String { val dir = CollectionHelper.getCurrentAnkiDroidDirectory(AnkiDroidApp.instance) CollectionHelper.initializeAnkiDroidDirectory(dir) return File(dir, "collection.anki2").absolutePath } /** * Like [withQueue], but can be used in a synchronous context. * * Note: Because [runBlocking] inside [runTest] will lead to * deadlocks, this will not block when run under Robolectric, * and there is no guarantee about concurrent access. */ private fun <T> blockForQueue(block: CollectionManager.() -> T): T { return if (robolectric) { block(this) } else { runBlocking { withQueue(block) } } } fun closeCollectionBlocking(save: Boolean = true) { runBlocking { ensureClosed(save = save) } } /** * Returns a reference to the open collection. This is not * safe, as code in other threads could open or close * the collection while the reference is held. [withCol] * is a better alternative. */ fun getColUnsafe(): Collection { return logUIHangs { blockForQueue { ensureOpenInner() collection!! } } } /** Execute [block]. If it takes more than 100ms of real time, Timber an error like: > Blocked main thread for 2424ms: com.ichi2.anki.DeckPicker.onCreateOptionsMenu(DeckPicker.kt:624) */ // using TimeManager breaks a sched test that makes assumptions about the time, so we // access the time directly @SuppressLint("DirectSystemCurrentTimeMillisUsage") private fun <T> logUIHangs(block: () -> T): T { val start = System.currentTimeMillis() return block().also { val elapsed = System.currentTimeMillis() - start if (Threads.isOnMainThread && elapsed > 100) { val stackTraceElements = Thread.currentThread().stackTrace // locate the probable calling file/line in the stack trace, by filtering // out our own code, and standard dalvik/java.lang stack frames val caller = stackTraceElements.filter { val klass = it.className for ( text in listOf( "CollectionManager", "dalvik", "java.lang", "CollectionHelper", "AnkiActivity" ) ) { if (text in klass) { return@filter false } } true }.first() Timber.e("blocked main thread for %dms:\n%s", elapsed, caller) } } } /** * True if the collection is open. Unsafe, as it has the potential to race. */ fun isOpenUnsafe(): Boolean { return logUIHangs { blockForQueue { if (emulateOpenFailure) { false } else { collection?.dbClosed == false } } } } /** Use [col] as collection in tests. This collection persists only up to the next (direct or indirect) call to `ensureClosed` */ fun setColForTests(col: Collection?) { blockForQueue { if (col == null) { ensureClosedInner() } collection = col } } /** * Execute block with the collection upgraded to the latest schema. * If it was previously using the legacy schema, the collection is downgraded * again after the block completes. */ private suspend fun <T> withNewSchema(block: CollectionV16.() -> T): T { return withCol { if (BackendFactory.defaultLegacySchema) { // Temporarily update to the latest schema. discardBackendInner() BackendFactory.defaultLegacySchema = false ensureOpenInner() try { (collection!! as CollectionV16).block() } finally { BackendFactory.defaultLegacySchema = true discardBackendInner() } } else { (this as CollectionV16).block() } } } /** Upgrade from v1 to v2 scheduler. * Caller must have confirmed schema modification already. */ suspend fun updateScheduler() { withNewSchema { sched.upgradeToV2() } } /** * Replace the collection with the provided colpkg file if it is valid. */ suspend fun importColpkg(colpkgPath: String) { withQueue { ensureClosedInner() ensureBackendInner() importCollectionPackage(backend!!, createCollectionPath(), colpkgPath) } } fun setTestDispatcher(dispatcher: CoroutineDispatcher) { // note: we avoid the call to .limitedParallelism() here, // as it does not seem to be compatible with the test scheduler queue = dispatcher } }
gpl-3.0
1f9566b344763bbff58086d47ea815e4
35.714674
104
0.578566
5.178612
false
false
false
false
budioktaviyan/reactive-concept-kotlin
app/src/main/kotlin/com/baculsoft/sample/kotlinreactive/observable/ObservableUI.kt
1
3207
package com.baculsoft.sample.kotlinreactive.observable import android.annotation.SuppressLint import android.support.v4.content.ContextCompat import android.view.Gravity import com.baculsoft.sample.kotlinreactive.R import org.jetbrains.anko.AnkoComponent import org.jetbrains.anko.AnkoContext import org.jetbrains.anko.alignParentBottom import org.jetbrains.anko.alignParentTop import org.jetbrains.anko.appcompat.v7.toolbar import org.jetbrains.anko.backgroundColor import org.jetbrains.anko.below import org.jetbrains.anko.bottomPadding import org.jetbrains.anko.button import org.jetbrains.anko.centerInParent import org.jetbrains.anko.design.appBarLayout import org.jetbrains.anko.design.coordinatorLayout import org.jetbrains.anko.dip import org.jetbrains.anko.matchParent import org.jetbrains.anko.relativeLayout import org.jetbrains.anko.textColor import org.jetbrains.anko.textView import org.jetbrains.anko.topPadding import org.jetbrains.anko.wrapContent class ObservableUI : AnkoComponent<ObservableActivity> { @SuppressLint("NewApi") override fun createView(ui: AnkoContext<ObservableActivity>) = with(ui) { coordinatorLayout { id = R.id.content_observable backgroundColor = ContextCompat.getColor(ctx, R.color.colorPrimary) relativeLayout { appBarLayout { id = R.id.abl_observable backgroundColor = ContextCompat.getColor(ctx, R.color.colorAccent) elevation = dip(4).toFloat() toolbar { id = R.id.toolbar_observable setTitleTextColor(ContextCompat.getColor(ctx, R.color.colorPrimary)) }.lparams { width = matchParent height = wrapContent } }.lparams { alignParentTop() width = matchParent height = wrapContent } textView { id = R.id.tv_observable text = ctx.resources.getString(R.string.text_observable) textColor = ContextCompat.getColor(ctx, R.color.colorPrimaryDark) textSize = 16f gravity = Gravity.CENTER }.lparams { below(R.id.abl_observable) centerInParent() width = matchParent height = wrapContent } button { id = R.id.btn_observable text = ctx.resources.getString(R.string.btn_subscribe) textColor = ContextCompat.getColor(ctx, R.color.colorPrimaryDark) textSize = 16f topPadding = dip(16) bottomPadding = dip(16) }.lparams { alignParentBottom() width = matchParent height = wrapContent marginEnd = dip(16) marginStart = dip(16) bottomPadding = dip(8) } } } } }
apache-2.0
e3c07a697a68f1ed2fee509e9591b24d
36.741176
92
0.58154
5.380872
false
false
false
false
strazzere/simplify
sdbg/src/main/java/org/cf/sdbg/command/BreakCommand.kt
2
3295
package org.cf.sdbg.command import org.cf.util.ClassNameUtils import picocli.CommandLine import picocli.CommandLine.ParentCommand sealed class BreakTarget data class BreakTargetMethod(val methodSignature: String) : BreakTarget() data class BreakTargetIndex(val index: Int) : BreakTarget() object BreakTargetInvalid : BreakTarget() @CommandLine.Command(name = "break", aliases = ["b"], mixinStandardHelpOptions = true, version = ["1.0"], description = ["Suspend program at specified function, instruction index, or index offset"]) class BreakCommand : DebuggerCommand() { @ParentCommand lateinit var parent: CliCommands @CommandLine.Parameters(index = "0", arity = "0..1", paramLabel = "TARGET", description = ["index-number | method | class->method | +offset | -offset"]) var target: String? = null private fun parseTarget(target: String?): BreakTarget { if (target == null) { return BreakTargetIndex(debugger.currentIndex) } val guessedType = ClassNameUtils.guessReferenceType(target) return when { target.startsWith('-') || target.startsWith('+') -> { val offset = target.toIntOrNull() ?: return BreakTargetInvalid BreakTargetIndex(debugger.currentIndex + offset) } guessedType == ClassNameUtils.ReferenceType.INTERNAL_METHOD_SIGNATURE -> BreakTargetMethod(target) guessedType == ClassNameUtils.ReferenceType.INTERNAL_METHOD_DESCRIPTOR -> { val className = debugger.executionGraph.method.className BreakTargetMethod("$className->$target") } target.toIntOrNull() != null -> BreakTargetIndex(index = target.toInt()) else -> BreakTargetInvalid } } private fun printInvalid(message: String) { parent.out.println("invalid target; $message") } override fun run() { when (val parsedTarget = parseTarget(target)) { is BreakTargetMethod -> { val method = debugger.classManager.getMethod(parsedTarget.methodSignature) if (method == null) { printInvalid("method not found") return } if (!method.hasImplementation()) { printInvalid("method has no implementation") } debugger.addBreakpoint(parsedTarget.methodSignature, 0) parent.out.println("breakpoint set for ${parsedTarget.methodSignature}") } is BreakTargetIndex -> { val method = debugger.currentMethod if (method.implementation.instructions.size < parsedTarget.index) { parent.out.println("instr size: ${method.implementation.instructions.size}") printInvalid("index out of range") return } debugger.addBreakpoint(debugger.currentMethodSignature, parsedTarget.index) parent.out.println("breakpoint set for ${debugger.currentMethodSignature} @ ${parsedTarget.index}") } is BreakTargetInvalid -> { printInvalid("unable to parse") return } } } }
mit
9053ef3f133756d7a62a73c004fc655d
42.933333
115
0.611836
5.323102
false
false
false
false
infinum/android_dbinspector
dbinspector/src/main/kotlin/com/infinum/dbinspector/ui/content/shared/drop/DropContentDialog.kt
1
2414
package com.infinum.dbinspector.ui.content.shared.drop import android.os.Bundle import android.view.View import androidx.annotation.StringRes import androidx.core.os.bundleOf import androidx.fragment.app.setFragmentResult import com.infinum.dbinspector.R import com.infinum.dbinspector.databinding.DbinspectorDialogDropContentBinding import com.infinum.dbinspector.ui.Presentation.Constants.Keys.DROP_CONTENT import com.infinum.dbinspector.ui.Presentation.Constants.Keys.DROP_MESSAGE import com.infinum.dbinspector.ui.Presentation.Constants.Keys.DROP_NAME import com.infinum.dbinspector.ui.shared.base.BaseBottomSheetDialogFragment import com.infinum.dbinspector.ui.shared.base.BaseViewModel import com.infinum.dbinspector.ui.shared.delegates.viewBinding internal class DropContentDialog : BaseBottomSheetDialogFragment<Any, Any>(R.layout.dbinspector_dialog_drop_content) { companion object { fun setMessage(@StringRes drop: Int, name: String): DropContentDialog { val fragment = DropContentDialog() fragment.arguments = Bundle().apply { putInt(DROP_MESSAGE, drop) putString(DROP_NAME, name) } return fragment } } override val binding: DbinspectorDialogDropContentBinding by viewBinding( DbinspectorDialogDropContentBinding::bind ) override val viewModel: BaseViewModel<Any, Any>? = null @StringRes private var drop: Int? = null private var name: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { drop = it.getInt(DROP_MESSAGE) name = it.getString(DROP_NAME) } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) with(binding) { toolbar.setNavigationOnClickListener { dismiss() } messageView.text = drop?.let { String.format(getString(it), name.orEmpty()) } dropButton.setOnClickListener { setFragmentResult( DROP_CONTENT, bundleOf( DROP_NAME to name ) ) dismiss() } } } override fun onState(state: Any) = Unit override fun onEvent(event: Any) = Unit }
apache-2.0
2d7ef074f8f35474f459050439beebf5
33
118
0.673985
4.896552
false
false
false
false
sksamuel/elasticsearch-river-neo4j
streamops-session/src/main/kotlin/com/octaldata/session/SubscriptionOps.kt
1
1205
package com.octaldata.session import com.octaldata.domain.topics.TopicName import com.sksamuel.tabby.results.success import kotlin.time.Duration interface SubscriptionOps { suspend fun getSubscriptions(topicName: TopicName): Result<List<String>> suspend fun deleteSubscription(topicName: TopicName, subscription: String): Result<Boolean> suspend fun expireSub(topicName: TopicName, time: Duration): Result<Boolean> suspend fun expireMessages(topicName: TopicName, subscription: String, time: Duration): Result<Boolean> suspend fun skipAllMessages(topicName: TopicName, subscription: String): Result<Boolean> } object NoopSubscriptionOps : SubscriptionOps { override suspend fun deleteSubscription(topicName: TopicName, subscription: String) = false.success() override suspend fun getSubscriptions(topicName: TopicName): Result<List<String>> = Result.success(emptyList()) override suspend fun expireMessages(topicName: TopicName, subscription: String, time: Duration) = false.success() override suspend fun expireSub(topicName: TopicName, time: Duration) = false.success() override suspend fun skipAllMessages(topicName: TopicName, subscription: String) = false.success() }
apache-2.0
1c28f533f6259130ba30b68c1ec852ac
56.428571
116
0.79917
4.762846
false
false
false
false
SergeySave/SpaceGame
core/src/com/sergey/spacegame/common/ecs/component/VisualComponent.kt
1
2165
package com.sergey.spacegame.common.ecs.component import com.badlogic.ashley.core.Component import com.badlogic.ashley.core.ComponentMapper import com.google.gson.JsonDeserializationContext import com.google.gson.JsonDeserializer import com.google.gson.JsonElement import com.google.gson.JsonObject import com.google.gson.JsonParseException import com.google.gson.JsonSerializationContext import com.google.gson.JsonSerializer import com.sergey.spacegame.common.SpaceGame import com.sergey.spacegame.common.data.VisualData import java.lang.reflect.Type /** * This component contains the visual data * * @author sergeys * * @constructor Create a new VisualComponent object * * @param regionName - the name of the texture region */ class VisualComponent(regionName: String) : ClonableComponent { /** * The texture region's name */ var regionName: String = regionName set(value) { visualData = SpaceGame.getInstance().context.createVisualData(value) field = value } /** * The visual data object used for client side rendering */ var visualData: VisualData? = SpaceGame.getInstance().context.createVisualData(regionName) private set override fun copy(): Component { return VisualComponent(regionName) } companion object MAP { @JvmField val MAPPER = ComponentMapper.getFor(VisualComponent::class.java)!! } class Adapter : JsonSerializer<VisualComponent>, JsonDeserializer<VisualComponent> { @Throws(JsonParseException::class) override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): VisualComponent { val obj = json.asJsonObject return VisualComponent(obj.get("image").asString) } override fun serialize(src: VisualComponent, typeOfSrc: Type, context: JsonSerializationContext): JsonElement { val obj = JsonObject() obj.addProperty("image", src.regionName) return obj } } }
mit
bce268c12762c86df18d10045eb82931
30.391304
119
0.676212
5.106132
false
false
false
false
Team-Antimatter-Mod/AntiMatterMod
src/main/java/antimattermod/core/Util/Gui/GuiHelper.kt
1
3443
package antimattermod.core.Util.Gui import net.minecraft.client.Minecraft import net.minecraft.client.gui.Gui import net.minecraft.client.gui.GuiButton import net.minecraft.client.gui.inventory.GuiContainer import net.minecraft.client.renderer.Tessellator import net.minecraft.inventory.Container import net.minecraft.inventory.IInventory import net.minecraft.inventory.Slot import net.minecraft.item.ItemStack import org.lwjgl.opengl.GL11 /** * Created by kojin15. */ object GuiHelper { fun drawTexturedClear(x: Int, y: Int, u: Int, v: Int, width: Int, height: Int, alpha: Double, zLevel: Float) { GL11.glEnable(GL11.GL_BLEND) GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA) GL11.glColor4d(2.0, 2.0, 2.0, alpha) val f = 0.00390625f val f1 = 0.00390625f val tessellator = Tessellator.instance tessellator.startDrawingQuads() tessellator.addVertexWithUV((x + 0).toDouble(), (y + height).toDouble(), zLevel.toDouble(), ((u + 0).toFloat() * f).toDouble(), ((v + height).toFloat() * f1).toDouble()) tessellator.addVertexWithUV((x + width).toDouble(), (y + height).toDouble(), zLevel.toDouble(), ((u + width).toFloat() * f).toDouble(), ((v + height).toFloat() * f1).toDouble()) tessellator.addVertexWithUV((x + width).toDouble(), (y + 0).toDouble(), zLevel.toDouble(), ((u + width).toFloat() * f).toDouble(), ((v + 0).toFloat() * f1).toDouble()) tessellator.addVertexWithUV((x + 0).toDouble(), (y + 0).toDouble(), zLevel.toDouble(), ((u + 0).toFloat() * f).toDouble(), ((v + 0).toFloat() * f1).toDouble()) tessellator.draw() GL11.glDisable(GL11.GL_BLEND) } /** * ボタンの描画 * @param button 描画するボタン * @param isPush 押されているかどうか */ fun drawTextureButton(button: TextureButton?, textureU: Int, textureV: Int, alpha: Double, isPush: Boolean) { if (button != null) { when (isPush) { false -> GuiHelper.drawTexturedClear(button.xPosition, button.yPosition, textureU, textureV, button.width, button.height, alpha, button.zTLevel) true -> GuiHelper.drawTexturedClear(button.xPosition, button.yPosition, textureU + button.width, textureV, button.width, button.height, alpha, button.zTLevel) } } } } /** * 描画を変更する時のボタン */ class TextureButton(id: Int, xPosition: Int, yPosition: Int, width: Int, height: Int) : GuiButton(id, xPosition, yPosition, width, height, null) { val zTLevel: Float = zLevel override fun drawButton(minecraft: Minecraft?, x: Int, y: Int) { } } /** * 何も描画しないボタン */ class ClearButton(id: Int, xPosition: Int, yPosition: Int, width: Int, height: Int) : GuiButton(id, xPosition, yPosition, width, height, null) { override fun drawButton(minecraft: Minecraft?, x: Int, y: Int) { } } class SlotBase(inventory: IInventory, slotIndex: Int, xDisplayPosition: Int, yDisplayPosition: Int, private val canIn: Boolean, private val canOut: Boolean) : Slot(inventory, slotIndex, xDisplayPosition, yDisplayPosition) { override fun putStack(p_75215_1_: ItemStack?) { if (canIn) super.putStack(p_75215_1_) } override fun decrStackSize(p_75209_1_: Int): ItemStack? { if (canOut) { return super.decrStackSize(p_75209_1_) } else return null } }
gpl-3.0
c1d2d10e419a67d172a3870e153b4566
37.551724
223
0.663585
3.49635
false
false
false
false
Kotlin/kotlinx.serialization
formats/json/commonMain/src/kotlinx/serialization/json/internal/TreeJsonEncoder.kt
1
9632
/* * Copyright 2017-2022 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ @file:OptIn(ExperimentalSerializationApi::class) package kotlinx.serialization.json.internal import kotlinx.serialization.* import kotlinx.serialization.descriptors.* import kotlinx.serialization.encoding.* import kotlinx.serialization.internal.* import kotlinx.serialization.json.* import kotlinx.serialization.modules.* import kotlin.collections.set import kotlin.jvm.* @InternalSerializationApi public fun <T> Json.writeJson(value: T, serializer: SerializationStrategy<T>): JsonElement { lateinit var result: JsonElement val encoder = JsonTreeEncoder(this) { result = it } encoder.encodeSerializableValue(serializer, value) return result } @ExperimentalSerializationApi private sealed class AbstractJsonTreeEncoder( final override val json: Json, private val nodeConsumer: (JsonElement) -> Unit ) : NamedValueEncoder(), JsonEncoder { final override val serializersModule: SerializersModule get() = json.serializersModule @JvmField protected val configuration = json.configuration private var polymorphicDiscriminator: String? = null override fun encodeJsonElement(element: JsonElement) { encodeSerializableValue(JsonElementSerializer, element) } override fun shouldEncodeElementDefault(descriptor: SerialDescriptor, index: Int): Boolean = configuration.encodeDefaults override fun composeName(parentName: String, childName: String): String = childName abstract fun putElement(key: String, element: JsonElement) abstract fun getCurrent(): JsonElement // has no tag when encoding a nullable element at root level override fun encodeNotNullMark() {} // has no tag when encoding a nullable element at root level override fun encodeNull() { val tag = currentTagOrNull ?: return nodeConsumer(JsonNull) encodeTaggedNull(tag) } override fun encodeTaggedNull(tag: String) = putElement(tag, JsonNull) override fun encodeTaggedInt(tag: String, value: Int) = putElement(tag, JsonPrimitive(value)) override fun encodeTaggedByte(tag: String, value: Byte) = putElement(tag, JsonPrimitive(value)) override fun encodeTaggedShort(tag: String, value: Short) = putElement(tag, JsonPrimitive(value)) override fun encodeTaggedLong(tag: String, value: Long) = putElement(tag, JsonPrimitive(value)) override fun encodeTaggedFloat(tag: String, value: Float) { // First encode value, then check, to have a prettier error message putElement(tag, JsonPrimitive(value)) if (!configuration.allowSpecialFloatingPointValues && !value.isFinite()) { throw InvalidFloatingPointEncoded(value, tag, getCurrent().toString()) } } override fun <T> encodeSerializableValue(serializer: SerializationStrategy<T>, value: T) { // Writing non-structured data (i.e. primitives) on top-level (e.g. without any tag) requires special output if (currentTagOrNull != null || !serializer.descriptor.carrierDescriptor(serializersModule).requiresTopLevelTag) { encodePolymorphically(serializer, value) { polymorphicDiscriminator = it } } else JsonPrimitiveEncoder(json, nodeConsumer).apply { encodeSerializableValue(serializer, value) endEncode(serializer.descriptor) } } override fun encodeTaggedDouble(tag: String, value: Double) { // First encode value, then check, to have a prettier error message putElement(tag, JsonPrimitive(value)) if (!configuration.allowSpecialFloatingPointValues && !value.isFinite()) { throw InvalidFloatingPointEncoded(value, tag, getCurrent().toString()) } } override fun encodeTaggedBoolean(tag: String, value: Boolean) = putElement(tag, JsonPrimitive(value)) override fun encodeTaggedChar(tag: String, value: Char) = putElement(tag, JsonPrimitive(value.toString())) override fun encodeTaggedString(tag: String, value: String) = putElement(tag, JsonPrimitive(value)) override fun encodeTaggedEnum( tag: String, enumDescriptor: SerialDescriptor, ordinal: Int ) = putElement(tag, JsonPrimitive(enumDescriptor.getElementName(ordinal))) override fun encodeTaggedValue(tag: String, value: Any) { putElement(tag, JsonPrimitive(value.toString())) } @SuppressAnimalSniffer // Long(Integer).toUnsignedString(long) override fun encodeTaggedInline(tag: String, inlineDescriptor: SerialDescriptor): Encoder = if (inlineDescriptor.isUnsignedNumber) object : AbstractEncoder() { override val serializersModule: SerializersModule = json.serializersModule fun putUnquotedString(s: String) = putElement(tag, JsonLiteral(s, isString = false)) override fun encodeInt(value: Int) = putUnquotedString(value.toUInt().toString()) override fun encodeLong(value: Long) = putUnquotedString(value.toULong().toString()) override fun encodeByte(value: Byte) = putUnquotedString(value.toUByte().toString()) override fun encodeShort(value: Short) = putUnquotedString(value.toUShort().toString()) } else super.encodeTaggedInline(tag, inlineDescriptor) override fun beginStructure(descriptor: SerialDescriptor): CompositeEncoder { val consumer = if (currentTagOrNull == null) nodeConsumer else { node -> putElement(currentTag, node) } val encoder = when (descriptor.kind) { StructureKind.LIST, is PolymorphicKind -> JsonTreeListEncoder(json, consumer) StructureKind.MAP -> json.selectMapMode( descriptor, { JsonTreeMapEncoder(json, consumer) }, { JsonTreeListEncoder(json, consumer) } ) else -> JsonTreeEncoder(json, consumer) } if (polymorphicDiscriminator != null) { encoder.putElement(polymorphicDiscriminator!!, JsonPrimitive(descriptor.serialName)) polymorphicDiscriminator = null } return encoder } override fun endEncode(descriptor: SerialDescriptor) { nodeConsumer(getCurrent()) } } private val SerialDescriptor.requiresTopLevelTag: Boolean get() = kind is PrimitiveKind || kind === SerialKind.ENUM internal const val PRIMITIVE_TAG = "primitive" // also used in JsonPrimitiveInput private class JsonPrimitiveEncoder( json: Json, nodeConsumer: (JsonElement) -> Unit ) : AbstractJsonTreeEncoder(json, nodeConsumer) { private var content: JsonElement? = null init { pushTag(PRIMITIVE_TAG) } override fun putElement(key: String, element: JsonElement) { require(key === PRIMITIVE_TAG) { "This output can only consume primitives with '$PRIMITIVE_TAG' tag" } require(content == null) { "Primitive element was already recorded. Does call to .encodeXxx happen more than once?" } content = element } override fun getCurrent(): JsonElement = requireNotNull(content) { "Primitive element has not been recorded. Is call to .encodeXxx is missing in serializer?" } } private open class JsonTreeEncoder( json: Json, nodeConsumer: (JsonElement) -> Unit ) : AbstractJsonTreeEncoder(json, nodeConsumer) { protected val content: MutableMap<String, JsonElement> = linkedMapOf() override fun putElement(key: String, element: JsonElement) { content[key] = element } override fun <T : Any> encodeNullableSerializableElement( descriptor: SerialDescriptor, index: Int, serializer: SerializationStrategy<T>, value: T? ) { if (value != null || configuration.explicitNulls) { super.encodeNullableSerializableElement(descriptor, index, serializer, value) } } override fun getCurrent(): JsonElement = JsonObject(content) } private class JsonTreeMapEncoder(json: Json, nodeConsumer: (JsonElement) -> Unit) : JsonTreeEncoder(json, nodeConsumer) { private lateinit var tag: String private var isKey = true override fun putElement(key: String, element: JsonElement) { if (isKey) { // writing key tag = when (element) { is JsonPrimitive -> element.content is JsonObject -> throw InvalidKeyKindException(JsonObjectSerializer.descriptor) is JsonArray -> throw InvalidKeyKindException(JsonArraySerializer.descriptor) } isKey = false } else { content[tag] = element isKey = true } } override fun getCurrent(): JsonElement { return JsonObject(content) } } private class JsonTreeListEncoder(json: Json, nodeConsumer: (JsonElement) -> Unit) : AbstractJsonTreeEncoder(json, nodeConsumer) { private val array: ArrayList<JsonElement> = arrayListOf() override fun elementName(descriptor: SerialDescriptor, index: Int): String = index.toString() override fun putElement(key: String, element: JsonElement) { val idx = key.toInt() array.add(idx, element) } override fun getCurrent(): JsonElement = JsonArray(array) } @OptIn(ExperimentalSerializationApi::class) internal inline fun <reified T : JsonElement> cast(value: JsonElement, descriptor: SerialDescriptor): T { if (value !is T) { throw JsonDecodingException( -1, "Expected ${T::class} as the serialized body of ${descriptor.serialName}, but had ${value::class}" ) } return value }
apache-2.0
b732e4d69cdedaa09379d8a6b17a2ff2
39.133333
126
0.696117
4.980352
false
false
false
false
tommykw/TV
app/src/main/kotlin/com/github/tommykw/tv/activity/PlaybackOverlayActivity.kt
1
6971
package com.github.tommykw.tv.activity import android.app.Activity import android.graphics.Bitmap import android.media.MediaMetadata import android.media.MediaPlayer import android.media.session.MediaSession import android.media.session.PlaybackState import android.net.Uri import android.os.Bundle import android.view.KeyEvent import android.widget.VideoView import com.bumptech.glide.Glide import com.bumptech.glide.request.animation.GlideAnimation import com.bumptech.glide.request.target.SimpleTarget import com.github.tommykw.tv.fragment.PlaybackOverlayFragment import com.github.tommykw.tv.R import com.github.tommykw.tv.model.Movie class PlaybackOverlayActivity : BaseActivity(), PlaybackOverlayFragment.OnPlayPauseClickedListener { private val mVideoView by lazy { findViewById(R.id.videoView) as VideoView } private var mPlaybackState = LeanbackPlaybackState.IDLE private var mSession = MediaSession(this, "LeanbackSampleApp") public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.playback_controls) loadViews() setupCallbacks() mSession.apply { setCallback(MediaSessionCallback()) setFlags(MediaSession.FLAG_HANDLES_MEDIA_BUTTONS or MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS) isActive = true } } public override fun onDestroy() { super.onDestroy() mVideoView.suspend() } override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean { val playbackOverlayFragment = fragmentManager.findFragmentById(R.id.playback_controls_fragment) as PlaybackOverlayFragment when (keyCode) { KeyEvent.KEYCODE_MEDIA_PLAY -> { playbackOverlayFragment.togglePlayback(false) return true } KeyEvent.KEYCODE_MEDIA_PAUSE -> { playbackOverlayFragment.togglePlayback(false) return true } KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE -> { if (mPlaybackState == LeanbackPlaybackState.PLAYING) { playbackOverlayFragment.togglePlayback(false) } else { playbackOverlayFragment.togglePlayback(true) } return true } else -> return super.onKeyUp(keyCode, event) } } override fun onFragmentPlayPause(movie: Movie, position: Int, playPause: Boolean?) { mVideoView.setVideoPath(movie.videoUrl) if (position == 0 || mPlaybackState == LeanbackPlaybackState.IDLE) { setupCallbacks() mPlaybackState = LeanbackPlaybackState.IDLE } if (playPause!! && mPlaybackState != LeanbackPlaybackState.PLAYING) { mPlaybackState = LeanbackPlaybackState.PLAYING if (position > 0) { mVideoView.seekTo(position) mVideoView.start() } } else { mPlaybackState = LeanbackPlaybackState.PAUSED mVideoView.pause() } updatePlaybackState(position) updateMetadata(movie) } private fun updatePlaybackState(position: Int) { val stateBuilder = PlaybackState.Builder() .setActions(availableActions) var state = PlaybackState.STATE_PLAYING if (mPlaybackState == LeanbackPlaybackState.PAUSED) { state = PlaybackState.STATE_PAUSED } stateBuilder.setState(state, position.toLong(), 1.0f) mSession.setPlaybackState(stateBuilder.build()) } private val availableActions: Long get() { var actions = PlaybackState.ACTION_PLAY or PlaybackState.ACTION_PLAY_FROM_MEDIA_ID or PlaybackState.ACTION_PLAY_FROM_SEARCH if (mPlaybackState == LeanbackPlaybackState.PLAYING) { actions = actions or PlaybackState.ACTION_PAUSE } return actions } private fun updateMetadata(movie: Movie) { val metadataBuilder = MediaMetadata.Builder() val title = movie.title!!.replace("_", " -") metadataBuilder.putString(MediaMetadata.METADATA_KEY_DISPLAY_TITLE, title) metadataBuilder.putString(MediaMetadata.METADATA_KEY_DISPLAY_SUBTITLE, movie.description) metadataBuilder.putString(MediaMetadata.METADATA_KEY_DISPLAY_ICON_URI, movie.cardImageUrl) // And at minimum the title and artist for legacy support metadataBuilder.putString(MediaMetadata.METADATA_KEY_TITLE, title) metadataBuilder.putString(MediaMetadata.METADATA_KEY_ARTIST, movie.studio) Glide.with(this) .load(Uri.parse(movie.cardImageUrl)) .asBitmap() .into(object : SimpleTarget<Bitmap>(500, 500) { override fun onResourceReady(resource: Bitmap?, glideAnimation: GlideAnimation<in Bitmap>?) { metadataBuilder.putBitmap(MediaMetadata.METADATA_KEY_ART, resource) mSession.setMetadata(metadataBuilder.build()) } }) } private fun loadViews() { mVideoView.isFocusable = false mVideoView.isFocusableInTouchMode = false } private fun setupCallbacks() { mVideoView.setOnErrorListener { mp, what, extra -> var msg = "" if (extra == MediaPlayer.MEDIA_ERROR_TIMED_OUT) { msg = getString(R.string.video_error_media_load_timeout) } else if (what == MediaPlayer.MEDIA_ERROR_SERVER_DIED) { msg = getString(R.string.video_error_server_inaccessible) } else { msg = getString(R.string.video_error_unknown_error) } mVideoView.stopPlayback() mPlaybackState = LeanbackPlaybackState.IDLE false } mVideoView.setOnPreparedListener { if (mPlaybackState == LeanbackPlaybackState.PLAYING) { mVideoView.start() } } mVideoView.setOnCompletionListener { mPlaybackState = LeanbackPlaybackState.IDLE } } public override fun onResume() { super.onResume() mSession.isActive = true } public override fun onPause() { super.onPause() if (mVideoView.isPlaying) { if (!requestVisibleBehind(true)) { stopPlayback() } } else { requestVisibleBehind(false) } } override fun onStop() { super.onStop() mSession.release() } override fun onVisibleBehindCanceled() { super.onVisibleBehindCanceled() } private fun stopPlayback() { mVideoView.stopPlayback() } enum class LeanbackPlaybackState { PLAYING, PAUSED, BUFFERING, IDLE } private inner class MediaSessionCallback : MediaSession.Callback() }
apache-2.0
34856f6a10d6728f65582ae5355218f4
33.171569
130
0.63506
5.261132
false
false
false
false
Ruben-Sten/TeXiFy-IDEA
src/nl/hannahsten/texifyidea/inspections/bibtex/BibtexDuplicateBibliographyInspection.kt
1
5249
package nl.hannahsten.texifyidea.inspections.bibtex import com.intellij.codeInspection.InspectionManager import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemHighlightType import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiFile import nl.hannahsten.texifyidea.index.LatexIncludesIndex import nl.hannahsten.texifyidea.inspections.InsightGroup import nl.hannahsten.texifyidea.inspections.TexifyInspectionBase import nl.hannahsten.texifyidea.lang.LatexPackage import nl.hannahsten.texifyidea.psi.LatexCommands import nl.hannahsten.texifyidea.util.* import nl.hannahsten.texifyidea.util.files.document /** * @author Sten Wessel */ open class BibtexDuplicateBibliographyInspection : TexifyInspectionBase() { // Manual override to match short name in plugin.xml override fun getShortName() = InsightGroup.BIBTEX.prefix + inspectionId override val inspectionGroup = InsightGroup.LATEX override val inspectionId = "DuplicateBibliography" override fun getDisplayName() = "Same bibliography is included multiple times" override fun inspectFile(file: PsiFile, manager: InspectionManager, isOntheFly: Boolean): List<ProblemDescriptor> { // Chapterbib allows multiple bibliographies if (file.includedPackages().any { it == LatexPackage.CHAPTERBIB }) { return emptyList() } val descriptors = descriptorList() // Map each bibliography file to all the commands which include it val groupedIncludes = mutableMapOf<String, MutableList<LatexCommands>>() LatexIncludesIndex.getItemsInFileSet(file).asSequence() .filter { it.name == "\\bibliography" || it.name == "\\addbibresource" } .forEach { command -> for (fileName in command.getIncludedFiles(false).map { it.name }) { groupedIncludes.getOrPut(fileName) { mutableListOf() }.add(command) } } groupedIncludes.asSequence() .filter { (_, commands) -> commands.size > 1 } .forEach { (fileName, commands) -> for (command in commands.distinct()) { if (command.containingFile != file) continue val parameterIndex = command.requiredParameter(0)?.indexOf(fileName) ?: break if (parameterIndex < 0) break descriptors.add( manager.createProblemDescriptor( command, TextRange(parameterIndex, parameterIndex + fileName.length).shiftRight(command.commandToken.textLength + 1), "Bibliography file '$fileName' is included multiple times", ProblemHighlightType.GENERIC_ERROR_OR_WARNING, isOntheFly, RemoveOtherCommandsFix(fileName, commands) ) ) } } return descriptors } /** * @author Sten Wessel */ class RemoveOtherCommandsFix(private val bibName: String, private val commandsToFix: List<LatexCommands>) : LocalQuickFix { override fun getFamilyName(): String { return "Remove other includes of $bibName" } override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val currentCommand = descriptor.psiElement as LatexCommands val documentManager = PsiDocumentManager.getInstance(project) // For all commands to be fixed, remove the matching bibName // Handle commands by descending offset, to make sure the replaceString calls work correctly for (command in commandsToFix.sortedByDescending { it.textOffset }) { val document = command.containingFile.document() ?: continue val param = command.parameterList.first() // If we handle the current command, find the first occurrence of bibName and leave it intact val firstBibIndex = if (command == currentCommand) { param.text.trimRange(1, 1).splitToSequence(',').indexOfFirst { it.trim() == bibName } } else -1 val replacement = param.text.trimRange(1, 1).splitToSequence(',') // Parameter should stay if it is at firstBibIndex or some other bibliography file .filterIndexed { i, it -> i <= firstBibIndex || it.trim() != bibName } .joinToString(",", prefix = "{", postfix = "}") // When no arguments are left, just delete the command if (replacement.trimRange(1, 1).isBlank()) { command.delete() } else { document.replaceString(param.textRange, replacement) } documentManager.doPostponedOperationsAndUnblockDocument(document) documentManager.commitDocument(document) } } } }
mit
9e23be41d050f525b9b5675a5d05f670
42.380165
136
0.630025
5.542767
false
false
false
false
debop/debop4k
debop4k-data-mybatis/src/test/kotlin/debop4k/data/mybatis/kotlin/cache/EhCacheActorRepository.kt
1
3349
/* * Copyright (c) 2016. Sunghyouk Bae <sunghyouk.bae@gmail.com> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package debop4k.data.mybatis.kotlin.cache import debop4k.core.uninitialized import debop4k.data.mybatis.kotlin.mappers.KotlinActorMapper import debop4k.data.mybatis.kotlin.models.KotlinActor import lombok.NonNull import org.mybatis.spring.SqlSessionTemplate import org.springframework.cache.annotation.CacheConfig import org.springframework.cache.annotation.CacheEvict import org.springframework.cache.annotation.CachePut import org.springframework.cache.annotation.Cacheable import org.springframework.stereotype.Repository import org.springframework.transaction.annotation.Transactional import javax.inject.Inject /** * EhCacheActorRepository * @author sunghyouk.bae@gmail.com */ @Repository @Transactional @CacheConfig(cacheNames = arrayOf("kotlin-actors")) open class EhCacheActorRepository { @Inject val actorMapper: KotlinActorMapper = uninitialized() @Inject val sqlTemplate: SqlSessionTemplate = uninitialized() /** * KotlinActor id 값으로 Actor를 조회 * `@Cacheable` 은 먼저 Cache 에서 해당 Actor가 있는지 조회하고, 없다면 DB에서 읽어와서 캐시에 저장한 후 반환한다. * 캐시에 데이터가 존재한다면 캐시의 KotlinActor 를 반환하고, DB를 읽지 않는다 * @param id Actor의 identifier * * * @return 조회된 KotlinActor (없으면 NULL 반환) */ @Transactional(readOnly = true) @Cacheable(key = "#id") open fun findById(id: Int): KotlinActor { return this.actorMapper.findById(id) } @Transactional(readOnly = true) @Cacheable(key = "'firstname=' + #firstname") open fun findByFirstname(@NonNull firstname: String): KotlinActor { return this.actorMapper.findByFirstname(firstname) } @Transactional(readOnly = true) @Cacheable(key = "'firstname=' + #firstname") open fun findByFirstnameWithSqlSessionTemplate(@NonNull firstname: String): KotlinActor { return sqlTemplate.selectOne<KotlinActor>("selectActorByFirstname", firstname) } @Transactional(readOnly = true) open fun findAll(): List<KotlinActor> { return actorMapper.findAll() } /** * DB에 새로운 KotlinActor 를 추가하고, Cache에 미리 저장해둔다 * @param actor DB에 추가할 KotlinActor 정보 * * * @return 저장된 KotlinActor 정보 (발급된 Id 값이 있다) */ @CachePut(key = "#actor.id") open fun insertActor(actor: KotlinActor): KotlinActor { sqlTemplate.insert("insertActor", actor) return actor } /** * 캐시에서 해당 정보를 삭제하고, DB에서 데이터를 삭제한다. * @param id 삭제할 KotlinActor 의 identifier */ @CacheEvict(key = "#id") open fun deleteById(id: Int?) { actorMapper.deleteById(id) } }
apache-2.0
143070b076c57a645cd800b0294afbf6
30.367347
91
0.739993
3.7339
false
false
false
false
timusus/Shuttle
app/src/main/java/com/simplecity/amp_library/ui/screens/songs/menu/SongMenuPresenter.kt
1
5193
package com.simplecity.amp_library.ui.screens.songs.menu import android.content.Context import com.simplecity.amp_library.data.Repository import com.simplecity.amp_library.data.Repository.AlbumArtistsRepository import com.simplecity.amp_library.model.Playlist import com.simplecity.amp_library.model.Song import com.simplecity.amp_library.playback.MediaManager import com.simplecity.amp_library.ui.common.Presenter import com.simplecity.amp_library.ui.screens.drawer.NavigationEventRelay import com.simplecity.amp_library.ui.screens.drawer.NavigationEventRelay.NavigationEvent import com.simplecity.amp_library.ui.screens.songs.menu.SongMenuContract.View import com.simplecity.amp_library.utils.LogUtils import com.simplecity.amp_library.utils.RingtoneManager import com.simplecity.amp_library.utils.playlists.PlaylistManager import io.reactivex.Observable import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import javax.inject.Inject open class SongMenuPresenter @Inject constructor( private val context: Context, private val mediaManager: MediaManager, private val playlistManager: PlaylistManager, private val blacklistRepository: Repository.BlacklistRepository, private val ringtoneManager: RingtoneManager, private val albumArtistsRepository: AlbumArtistsRepository, private val albumsRepository: Repository.AlbumsRepository, private val navigationEventRelay: NavigationEventRelay ) : Presenter<View>(), SongMenuContract.Presenter { override fun createPlaylist(songs: List<Song>) { view?.presentCreatePlaylistDialog(songs) } override fun addToPlaylist(playlist: Playlist, songs: List<Song>) { playlistManager.addToPlaylist(playlist, songs) { numSongs -> view?.onSongsAddedToPlaylist(playlist, numSongs) } } override fun addToQueue(songs: List<Song>) { mediaManager.addToQueue(songs) { numSongs -> view?.onSongsAddedToQueue(numSongs) } } override fun playNext(songs: List<Song>) { mediaManager.playNext(songs) { numSongs -> view?.onSongsAddedToQueue(numSongs) } } override fun blacklist(songs: List<Song>) { blacklistRepository.addAllSongs(songs) } override fun delete(songs: List<Song>) { view?.presentDeleteDialog(songs) } override fun songInfo(song: Song) { view?.presentSongInfoDialog(song) } override fun setRingtone(song: Song) { if (RingtoneManager.requiresDialog(context)) { view?.presentRingtonePermissionDialog() } else { ringtoneManager.setRingtone(song) { view?.showRingtoneSetMessage() } } } override fun share(song: Song) { view?.shareSong(song) } override fun editTags(song: Song) { view?.presentTagEditorDialog(song) } override fun goToArtist(song: Song) { addDisposable(albumArtistsRepository.getAlbumArtists() .first(emptyList()) .flatMapObservable { Observable.fromIterable(it) } .filter { albumArtist -> albumArtist.name == song.albumArtist.name && albumArtist.albums.containsAll(song.albumArtist.albums) } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { albumArtist -> navigationEventRelay.sendEvent(NavigationEvent(NavigationEvent.Type.GO_TO_ARTIST, albumArtist, true)) }, { error -> LogUtils.logException(TAG, "Failed to retrieve album artist", error) } )) } override fun goToAlbum(song: Song) { addDisposable(albumsRepository.getAlbums() .first(emptyList()) .flatMapObservable { Observable.fromIterable(it) } .filter { album -> album.id == song.albumId } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { album -> navigationEventRelay.sendEvent(NavigationEvent(NavigationEvent.Type.GO_TO_ALBUM, album, true)) }, { error -> LogUtils.logException(TAG, "Failed to retrieve album", error) } )) } override fun goToGenre(song: Song) { addDisposable(song.getGenre(context) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { genre -> navigationEventRelay.sendEvent(NavigationEvent(NavigationEvent.Type.GO_TO_GENRE, genre, true)) }, { error -> LogUtils.logException(TAG, "Failed to retrieve genre", error) } )) } override fun <T> transform(src: Single<List<T>>, dst: (List<T>) -> Unit) { addDisposable( src .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe( { items -> dst(items) }, { error -> LogUtils.logException(TAG, "Failed to transform src single", error) } ) ) } companion object { const val TAG = "SongMenuPresenter" } }
gpl-3.0
0cb4ddc72ecfde6ed14e497005116f07
37.761194
139
0.674177
4.669964
false
false
false
false
QuickBlox/quickblox-android-sdk
sample-conference-kotlin/app/src/main/java/com/quickblox/sample/conference/kotlin/presentation/screens/call/CustomLinearLayout.kt
1
5972
package com.quickblox.sample.conference.kotlin.presentation.screens.call import android.content.Context import android.util.AttributeSet import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import android.widget.LinearLayout import com.quickblox.sample.conference.kotlin.R import com.quickblox.sample.conference.kotlin.databinding.CustomCoverstionLayoutBinding import com.quickblox.sample.conference.kotlin.domain.call.entities.CallEntity import java.util.* /* * Created by Injoit in 2021-09-30. * Copyright © 2021 Quickblox. All rights reserved. */ class CustomLinearLayout : LinearLayout, ConversationItem.ConversationItemListener { private lateinit var binding: CustomCoverstionLayoutBinding private var callEntities: SortedSet<CallEntity>? = null private var conversationItemListener: ConversationItemListener? = null constructor(context: Context) : super(context) { init(context) } constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) { init(context) } constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { init(context) } private fun init(context: Context) { val rootView: View = inflate(context, R.layout.custom_coverstion_layout, this) binding = CustomCoverstionLayoutBinding.bind(rootView) this.orientation = VERTICAL } fun setCallEntities(callEntities: SortedSet<CallEntity>) { this.callEntities = callEntities } fun setClickListener(conversationItemListener: ConversationItemListener) { this.conversationItemListener = conversationItemListener } fun updateViews(height: Int, width: Int) { removeAllViews() when (callEntities?.size) { 1 -> { val callEntity = callEntities?.first() val view = ConversationItem(context) callEntity?.let { view.setView(it) } view.setClickListener(this) view.layoutParams = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) this.addView(view) } 2 -> { callEntities?.forEach { callEntity -> val view = ConversationItem(context) view.setView(callEntity) view.setClickListener(this) view.layoutParams = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, height / 2) this.addView(view) } } 3 -> { callEntities?.let { callEntities -> val listCallEntities = callEntities.toList() this.addView(expandableLayout(width, height / 2, listCallEntities.get(0), listCallEntities.get(1))) val view = ConversationItem(context) listCallEntities.get(2)?.let { view.setView(it) } view.setClickListener(this) view.layoutParams = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, height / 2) this.addView(view) } } else -> { callEntities?.let { callEntities -> val listCallEntities = callEntities.toList() val displayScheme = calcViewTable(callEntities.size) var triple = displayScheme.first var dual = displayScheme.second val countRows = triple + dual var tmpIndex = 0 for (index in 0 .. listCallEntities.size step 3) { if (triple-- > 0) { this.addView(expandableLayout(width, height / countRows, listCallEntities[index], listCallEntities[index + 1], listCallEntities[index + 2])) } else { break } tmpIndex = index + 3 } for (index in tmpIndex .. listCallEntities.size step 2) { if (dual-- > 0) { this.addView(expandableLayout(width, height / countRows, listCallEntities[index], listCallEntities[index + 1])) } } } } } } private fun expandableLayout(width: Int, height: Int, vararg entities: CallEntity?): LinearLayout { val expandableLayout = LinearLayout(context) expandableLayout.layoutParams = LayoutParams(width, height) expandableLayout.orientation = HORIZONTAL expandableLayout.removeAllViews() entities.forEach { callEntity -> callEntity?.let { val view = ConversationItem(context) view.setView(it) view.setClickListener(this) view.layoutParams = FrameLayout.LayoutParams(width / entities.size, ViewGroup.LayoutParams.MATCH_PARENT) expandableLayout.addView(view) } } return expandableLayout } private fun calcViewTable(opponentsQuantity: Int): Pair<Int, Int> { var rowsThreeUsers = 0 var rowsTwoUsers = 0 when (opponentsQuantity % 3) { 0 -> rowsThreeUsers = opponentsQuantity / 3 1 -> { rowsTwoUsers = 2 rowsThreeUsers = (opponentsQuantity - 2) / 3 } 2 -> { rowsTwoUsers = 1 rowsThreeUsers = (opponentsQuantity - 1) / 3 } } return Pair(rowsThreeUsers, rowsTwoUsers) } override fun onItemClick(callEntity: CallEntity) { conversationItemListener?.onItemClick(callEntity) } interface ConversationItemListener { fun onItemClick(callEntity: CallEntity) } }
bsd-3-clause
b611e31ad3346b76d0d338d2179443e2
38.549669
168
0.593703
5.379279
false
false
false
false
LachlanMcKee/gsonpath
compiler/base/src/main/java/gsonpath/util/SunTreesProvider.kt
1
1429
package gsonpath.util import com.sun.source.util.Trees import javax.annotation.processing.ProcessingEnvironment /** * Typically the 'com.sun.source.util.Trees' class is not allowed when making an annotation processor incremental. * A work around (found here: https://github.com/JakeWharton/butterknife/commit/3f675f4e23e59f645f5cecddde9f3b9fb1925cf8#diff-141a2db288c994f07eba0c49a2869e9bR155) * was implemented to still allow Trees to be used. */ class SunTreesProvider(private val env: ProcessingEnvironment) { private val lazyTrees: Trees by lazy { try { Trees.instance(env) } catch (ignored: IllegalArgumentException) { try { // Get original ProcessingEnvironment from Gradle-wrapped one or KAPT-wrapped one. env.javaClass.declaredFields .first { field -> field.name == "delegate" || field.name == "processingEnv" } .let { field -> field.isAccessible = true val javacEnv = field.get(env) as ProcessingEnvironment Trees.instance(javacEnv) } } catch (throwable: Throwable) { throw IllegalStateException("Unable to create Trees", throwable) } } } fun getTrees(): Trees = lazyTrees }
mit
63c389d93ded4b66822acb2b3df30069
41.058824
163
0.597621
4.731788
false
false
false
false
arturbosch/detekt
detekt-tooling/src/main/kotlin/io/github/detekt/tooling/dsl/ExtensionsSpecBuilder.kt
1
1280
package io.github.detekt.tooling.dsl import io.github.detekt.tooling.api.spec.ExtensionId import io.github.detekt.tooling.api.spec.ExtensionsSpec import io.github.detekt.tooling.internal.PluginsHolder import java.nio.file.Path @ProcessingModelDsl class ExtensionsSpecBuilder : Builder<ExtensionsSpec> { var disableDefaultRuleSets: Boolean = false var plugins: ExtensionsSpec.Plugins? = null var disabledExtensions: MutableSet<ExtensionId> = mutableSetOf() override fun build(): ExtensionsSpec = ExtensionsModel( disableDefaultRuleSets, plugins, disabledExtensions ) fun disableExtension(id: ExtensionId) { disabledExtensions.add(id) } fun fromPaths(paths: () -> Collection<Path>) { require(plugins == null) { "Plugin source already specified." } plugins = PluginsHolder(paths(), null) } fun fromClassloader(classLoader: () -> ClassLoader) { require(plugins == null) { "Plugin source already specified." } plugins = PluginsHolder(null, classLoader()) } } private data class ExtensionsModel( override val disableDefaultRuleSets: Boolean, override val plugins: ExtensionsSpec.Plugins?, override val disabledExtensions: Set<ExtensionId> ) : ExtensionsSpec
apache-2.0
806f66550551c08e8f01b1900fde9704
31
71
0.722656
4.620939
false
false
false
false
rsiebert/TVHClient
app/src/main/java/org/tvheadend/tvhclient/ui/features/settings/SettingsUserInterfaceFragment.kt
1
5239
package org.tvheadend.tvhclient.ui.features.settings import android.os.Bundle import android.view.View import androidx.lifecycle.ViewModelProvider import androidx.preference.EditTextPreference import androidx.preference.Preference import androidx.preference.PreferenceFragmentCompat import androidx.preference.SwitchPreference import org.tvheadend.tvhclient.R import org.tvheadend.tvhclient.ui.common.interfaces.ToolbarInterface import org.tvheadend.tvhclient.util.extensions.sendSnackbarMessage import timber.log.Timber class SettingsUserInterfaceFragment : PreferenceFragmentCompat(), Preference.OnPreferenceChangeListener, Preference.OnPreferenceClickListener { private var programArtworkEnabledPreference: SwitchPreference? = null private var castMiniControllerPreference: SwitchPreference? = null private var multipleChannelTagsPreference: SwitchPreference? = null private var hoursOfEpgDataPreference: EditTextPreference? = null private var daysOfEpgDataPreference: EditTextPreference? = null lateinit var settingsViewModel: SettingsViewModel override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) settingsViewModel = ViewModelProvider(activity as SettingsActivity)[SettingsViewModel::class.java] (activity as ToolbarInterface).let { it.setTitle(getString(R.string.pref_user_interface)) it.setSubtitle("") } programArtworkEnabledPreference = findPreference("program_artwork_enabled") programArtworkEnabledPreference?.onPreferenceClickListener = this castMiniControllerPreference = findPreference("casting_minicontroller_enabled") castMiniControllerPreference?.onPreferenceClickListener = this multipleChannelTagsPreference = findPreference("multiple_channel_tags_enabled") multipleChannelTagsPreference?.onPreferenceClickListener = this hoursOfEpgDataPreference = findPreference("hours_of_epg_data_per_screen") hoursOfEpgDataPreference?.onPreferenceChangeListener = this daysOfEpgDataPreference = findPreference("days_of_epg_data") daysOfEpgDataPreference?.onPreferenceChangeListener = this } override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { addPreferencesFromResource(R.xml.preferences_ui) } override fun onPreferenceClick(preference: Preference): Boolean { when (preference.key) { "multiple_channel_tags_enabled" -> handlePreferenceMultipleChannelTagsSelected() "program_artwork_enabled" -> handlePreferenceShowArtworkSelected() "casting" -> handlePreferenceCastingSelected() } return true } private fun handlePreferenceMultipleChannelTagsSelected() { if (!settingsViewModel.isUnlocked) { context?.sendSnackbarMessage(R.string.feature_not_available_in_free_version) multipleChannelTagsPreference?.isChecked = false } } private fun handlePreferenceShowArtworkSelected() { if (!settingsViewModel.isUnlocked) { context?.sendSnackbarMessage(R.string.feature_not_available_in_free_version) programArtworkEnabledPreference?.isChecked = false } } private fun handlePreferenceCastingSelected() { if (settingsViewModel.currentServerStatus.htspVersion < 16) { context?.sendSnackbarMessage(R.string.feature_not_supported_by_server) castMiniControllerPreference?.isChecked = false } else if (!settingsViewModel.isUnlocked) { context?.sendSnackbarMessage(R.string.feature_not_available_in_free_version) castMiniControllerPreference?.isChecked = false } } override fun onPreferenceChange(preference: Preference?, newValue: Any?): Boolean { if (preference == null) return false Timber.d("Preference ${preference.key} changed, checking if it is valid") when (preference.key) { "hours_of_epg_data_per_screen" -> try { val value = Integer.valueOf(newValue as String) if (value < 1 || value > 24) { context?.sendSnackbarMessage("The value must be an integer between 1 and 24") return false } return true } catch (ex: NumberFormatException) { context?.sendSnackbarMessage("The value must be an integer between 1 and 24") return false } "days_of_epg_data" -> try { val value = Integer.valueOf(newValue as String) if (value < 1 || value > 14) { context?.sendSnackbarMessage("The value must be an integer between 1 and 14") return false } return true } catch (ex: NumberFormatException) { context?.sendSnackbarMessage("The value must be an integer between 1 and 14") return false } else -> return true } } }
gpl-3.0
f70b90537a1f0dfff2d45b1e289ce403
43.777778
143
0.67761
5.801772
false
false
false
false
d9n/intellij-rust
src/main/kotlin/org/rust/ide/intentions/UnwrapSingleExprIntention.kt
1
1264
package org.rust.ide.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.rust.lang.core.psi.RsBlockExpr import org.rust.lang.core.psi.RsExpr import org.rust.lang.core.psi.ext.getNextNonCommentSibling import org.rust.lang.core.psi.ext.parentOfType class UnwrapSingleExprIntention : RsElementBaseIntentionAction<RsBlockExpr>() { override fun getText() = "Remove braces from single expression" override fun getFamilyName() = text override fun findApplicableContext(project: Project, editor: Editor, element: PsiElement): RsBlockExpr? { val blockExpr = element.parentOfType<RsBlockExpr>() ?: return null val block = blockExpr.block return if (block.expr != null && block.lbrace.getNextNonCommentSibling() == block.expr) blockExpr else null } override fun invoke(project: Project, editor: Editor, ctx: RsBlockExpr) { val blockBody = ctx.block.expr ?: return val relativeCaretPosition = editor.caretModel.offset - blockBody.textOffset val offset = (ctx.replace(blockBody) as RsExpr).textOffset editor.caretModel.moveToOffset(offset + relativeCaretPosition) } }
mit
a2940bd0be21cc812c1ad2950352a08b
38.5
109
0.734177
4.546763
false
false
false
false
REBOOTERS/AndroidAnimationExercise
imitate/src/main/java/com/engineer/imitate/ui/list/adapter/ImageAdapter.kt
1
1670
package com.engineer.imitate.ui.list.adapter import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.bumptech.glide.request.RequestOptions import com.engineer.imitate.R import com.engineer.imitate.Routes import com.engineer.imitate.util.dp2px class ImageAdapter(private var datas: List<String>) : RecyclerView.Adapter<ImageAdapter.MyHolder>() { private lateinit var mContext: Context private var option: RequestOptions = RequestOptions.circleCropTransform() private fun dp2dx(context: Context, value: Int): Float { return context.dp2px(value.toFloat()) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyHolder { mContext = parent.context val view = LayoutInflater.from(mContext) .inflate(R.layout.h_image_item, parent, false) return MyHolder(view) } override fun getItemCount(): Int { return datas.size } override fun onBindViewHolder(holder: MyHolder, position: Int) { // Glide.with(mContext).load(datas[position]) // .apply(option) // .into(holder.imageView) val index = position % Routes.IMAGES.size val res = Routes.IMAGES[index] Glide.with(mContext).load(res).into(holder.imageView) } class MyHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { var imageView: ImageView = itemView.findViewById(com.engineer.imitate.R.id.image) } }
apache-2.0
c4038f343954d863db72cb8178fe31ff
30.528302
89
0.716168
4.238579
false
false
false
false
mctoyama/PixelClient
src/main/kotlin/org/pixelndice/table/pixelclient/Current.kt
1
645
package org.pixelndice.table.pixelclient import org.pixelndice.table.pixelclient.ds.Account import org.pixelndice.table.pixelclient.ds.Campaign import org.pixelndice.table.pixelclient.ds.resource.Board var gameTag: String = "" @Synchronized get @Synchronized set var currentCampaign: Campaign = Campaign() @Synchronized get @Synchronized set val myAccount: Account = Account() @Synchronized get fun isGm(): Boolean { return myAccount.id == currentCampaign.gm.id } var currentBoard: Board? = null @Synchronized get @Synchronized set var playerBoard: Board? = null @Synchronized get @Synchronized set
bsd-2-clause
7d181fd86e2441db84a31102710cfdfb
22.071429
57
0.748837
4.10828
false
false
false
false
mctoyama/PixelClient
src/main/kotlin/org/pixelndice/table/pixelclient/connection/lobby/client/State03LobbyAuthNotOk.kt
1
1850
package org.pixelndice.table.pixelclient.connection.lobby.client import org.apache.logging.log4j.LogManager import org.pixelndice.table.pixelclient.ApplicationBus import org.pixelndice.table.pixelclient.ds.RPGGameSystem import org.pixelndice.table.pixelprotocol.ChannelCanceledException import org.pixelndice.table.pixelprotocol.Protobuf private val logger = LogManager.getLogger(State03LobbyAuthNotOk::class.java) /** * Process the negation of a lobby auth * @author Marcelo Costa Toyama */ class State03LobbyAuthNotOk : State { init { logger.debug("State03LobbyAuthNotOk constructor") } /** * Process the context */ override fun process(ctx: Context) { var packet = ctx.channel.packet if( packet != null ){ if( packet.payloadCase == Protobuf.Packet.PayloadCase.LOBBYAUTHNOK){ val game = packet.lobbyAuthNOk.game ctx.state = StateStop() ApplicationBus.post(ApplicationBus.LobbyAuthNOk(game.gm.name, game.campaign, RPGGameSystem.fromProtobuf(game.rpgGameSystem))) logger.debug("Lobby Autho Not Ok!") }else{ packet = ctx.channel.packet val message = "Expecting Lobby auth nok, instead received: $packet. IP: ${ctx.channel.address}" logger.error(message) val error = Protobuf.EndWithError.newBuilder() error.reason = message val resp = Protobuf.Packet.newBuilder() resp.endWithError = error.build() try { ctx.channel.packet = resp.build() } catch (e: ChannelCanceledException) { logger.trace("Channel in invalid state. It will be recycled in the next cycle.") } } } } }
bsd-2-clause
d163d5db5aa652241e727d826334b748
29.344262
141
0.628108
4.579208
false
false
false
false
cicakhq/potato
contrib/rqjava/src/com/dhsdevelopments/rqjava/Main.kt
1
690
package com.dhsdevelopments.rqjava class Main { companion object { @JvmStatic fun main(args: Array<String>): Unit { val conn = PotatoConnection("localhost", "/", "elias", "foo") conn.connect() conn.subscribeChannel("4e8ff1e0e1c7d80e8e4e5cea510147db", { msg -> println("From: ${msg.fromName} (${msg.from}), text: ${msg.text}") }) conn.registerCmd("as") { cmd -> println("cmd=${cmd.cmd}, args=${cmd.args}, channel=${cmd.channel}, domain=${cmd.domain}, user=${cmd.user}") conn.sendMessage(cmd.user, cmd.channel, "HTML injection by command handler", cmd.args) } } } }
apache-2.0
880c3a0ffaad52484212cc2e0a4494d7
39.588235
147
0.571014
3.631579
false
false
false
false
ffc-nectec/FFC
ffc/src/main/kotlin/ffc/app/health/diagnosis/Diseases.kt
1
4975
/* * Copyright (c) 2018 NECTEC * National Electronics and Computer Technology Center, Thailand * * 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 ffc.app.health.diagnosis import android.content.Context import ffc.android.assetAs import ffc.android.connectivityManager import ffc.api.ApiErrorException import ffc.api.FfcCentral import ffc.app.isConnected import ffc.app.util.RepoCallback import ffc.entity.gson.parseTo import ffc.entity.gson.toJson import ffc.entity.healthcare.Disease import ffc.entity.healthcare.Icd10 import org.jetbrains.anko.doAsync import retrofit2.Call import retrofit2.dsl.enqueue import retrofit2.http.GET import retrofit2.http.Query import java.io.File import java.io.IOException internal interface Diseases { fun all(res: RepoCallback<List<Disease>>.() -> Unit) fun disease(id: String, res: RepoCallback<Disease>.() -> Unit) } internal fun diseases(context: Context): Diseases = MockDiseases(context) private class ApiDisease(context: Context) : Diseases { private val localFile = File(context.filesDir, "diseases.json") private var loading = false private var tmpCallback: RepoCallback<List<Disease>>? = null private val api = FfcCentral().service<DiseaseApi>() init { if (context.connectivityManager.isConnected) { loading = true loadDisease(mutableListOf(), 1, 5000) { tmpCallback?.onFound?.invoke(it) doAsync { try { localFile.createNewFile() } catch (ignore: IOException) { //file already created } localFile.writeText(it.toJson()) } } } if (localFile.exists()) { diseases = localFile.readText().parseTo() } } fun loadDisease(disease: MutableList<Disease>, currentPage: Int, perPage: Int, onFinish: (List<Disease>) -> Unit) { api.get(currentPage, perPage).enqueue { always { tmpCallback?.always?.invoke() loading = false } onSuccess { disease.addAll(body()!!) if (currentPage == page?.last) { onFinish(disease) } else { loadDisease(disease, page!!.next, page!!.perPage, onFinish) } } onError { tmpCallback?.onFail!!.invoke(ApiErrorException(this)) } onFailure { tmpCallback?.onFail!!.invoke(it) } } } override fun all(res: RepoCallback<List<Disease>>.() -> Unit) { val callback = RepoCallback<List<Disease>>().apply(res) if (loading) { tmpCallback = callback } else { callback.always?.invoke() if (diseases.isNotEmpty()) { callback.onFound!!.invoke(diseases) } else { callback.onNotFound!!.invoke() } } } override fun disease(id: String, res: RepoCallback<Disease>.() -> Unit) { val callback = RepoCallback<Disease>().apply(res) val disease = diseases.firstOrNull { it.id == id } if (disease != null) { callback.onFound!!.invoke(disease) } else { callback.onNotFound!!.invoke() } } companion object { var diseases = listOf<Disease>() } } private class MockDiseases(val context: Context) : Diseases { init { if (diseases.isEmpty()) { diseases = context.assetAs<List<Icd10>>("lookups/Disease.json") } } override fun all(res: RepoCallback<List<Disease>>.() -> Unit) { val callback = RepoCallback<List<Disease>>().apply(res) callback.onFound!!.invoke(diseases) } override fun disease(id: String, res: RepoCallback<Disease>.() -> Unit) { val callback = RepoCallback<Disease>().apply(res) val disease = diseases.firstOrNull { it.id == id } if (disease != null) { callback.onFound!!.invoke(disease) } else { callback.onNotFound!!.invoke() } } companion object { internal var diseases: List<Disease> = listOf() } } interface DiseaseApi { @GET("diseases") fun get(@Query("page") page: Int = 1, @Query("per_page") perPage: Int = 10000): Call<List<Disease>> }
apache-2.0
8fe954449def27979a428678ede20906
30.289308
119
0.598392
4.547532
false
false
false
false
stripe/stripe-android
example/src/main/java/com/stripe/example/activity/ConfirmSepaDebitActivity.kt
1
3808
package com.stripe.example.activity import android.os.Bundle import android.view.View import androidx.lifecycle.Observer import com.stripe.android.model.Address import com.stripe.android.model.MandateDataParams import com.stripe.android.model.PaymentMethod import com.stripe.android.model.PaymentMethodCreateParams import com.stripe.android.payments.paymentlauncher.PaymentResult import com.stripe.example.R import com.stripe.example.databinding.CreateSepaDebitActivityBinding /** * An example integration for confirming a Payment Intent using a SEPA Debit Payment Method. * * See [SEPA Direct Debit payments](https://stripe.com/docs/payments/sepa-debit) for more * details. */ class ConfirmSepaDebitActivity : StripeIntentActivity() { private val viewBinding: CreateSepaDebitActivityBinding by lazy { CreateSepaDebitActivityBinding.inflate(layoutInflater) } private val snackbarController: SnackbarController by lazy { SnackbarController(viewBinding.coordinator) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(viewBinding.root) setTitle(R.string.launch_confirm_pm_sepa_debit) viewModel.inProgress.observe(this, { enableUi(!it) }) viewModel.status.observe(this, Observer(viewBinding.status::setText)) viewBinding.ibanInput.setText(TEST_ACCOUNT_NUMBER) viewBinding.confirmButton.setOnClickListener { val params = createPaymentMethodParams(viewBinding.ibanInput.text.toString()) .takeIf { EXISTING_PAYMENT_METHOD_ID == null } createAndConfirmPaymentIntent( "nl", params, existingPaymentMethodId = EXISTING_PAYMENT_METHOD_ID, mandateDataParams = mandateData ) } } private fun enableUi(enabled: Boolean) { viewBinding.progressBar.visibility = if (enabled) View.INVISIBLE else View.VISIBLE viewBinding.confirmButton.isEnabled = enabled } override fun onConfirmSuccess() { super.onConfirmSuccess() snackbarController.show("Confirmation succeeded.") } override fun onConfirmCanceled() { super.onConfirmCanceled() snackbarController.show("Confirmation canceled.") } override fun onConfirmError(failedResult: PaymentResult.Failed) { super.onConfirmError(failedResult) snackbarController.show("Error during confirmation: ${failedResult.throwable.message}") } private fun createPaymentMethodParams(iban: String): PaymentMethodCreateParams { return PaymentMethodCreateParams.create( PaymentMethodCreateParams.SepaDebit(iban), PaymentMethod.BillingDetails.Builder() .setAddress( Address.Builder() .setCity("San Francisco") .setCountry("US") .setLine1("123 Market St") .setLine2("#345") .setPostalCode("94107") .setState("CA") .build() ) .setEmail("jenny@example.com") .setName("Jenny Rosen") .setPhone("(555) 555-5555") .build() ) } private companion object { private const val TEST_ACCOUNT_NUMBER = "DE89370400440532013000" // set to an existing payment method id to use in integration private val EXISTING_PAYMENT_METHOD_ID: String? = null private val mandateData = MandateDataParams( MandateDataParams.Type.Online( ipAddress = "127.0.0.1", userAgent = "agent" ) ) } }
mit
e17da4661da903ceab22362622d3507d
34.924528
95
0.645483
5.125168
false
false
false
false
AndroidX/androidx
wear/watchface/watchface-complications-data/src/main/java/androidx/wear/watchface/complications/data/Image.kt
3
11450
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.wear.watchface.complications.data import android.graphics.drawable.Icon import android.os.Build import androidx.annotation.RequiresApi import androidx.annotation.RestrictTo internal const val PLACEHOLDER_IMAGE_RESOURCE_ID = -1 internal fun createPlaceholderIcon(): Icon = Icon.createWithResource("", PLACEHOLDER_IMAGE_RESOURCE_ID) /** * A simple, monochromatic image that can be tinted by the watch face. * * A monochromatic image doesn't have to be black and white, it can have a single color associated * with the provider / brand with the expectation that the watch face may recolor it (typically * using a SRC_IN filter). * * An ambient alternative is provided that may be shown instead of the regular image while the * watch is not active. * * @property [image] The image itself * @property [ambientImage] The image to be shown when the device is in ambient mode to save power * or avoid burn in */ public class MonochromaticImage internal constructor( public val image: Icon, public val ambientImage: Icon? ) { /** * Builder for [MonochromaticImage]. * * @param [image] the [Icon] representing the image */ public class Builder(private var image: Icon) { private var ambientImage: Icon? = null /** * Sets a different image for when the device is ambient mode to save power and prevent * burn in. If no ambient variant is provided, the watch face may not show anything while * in ambient mode. */ public fun setAmbientImage(ambientImage: Icon?): Builder = apply { this.ambientImage = ambientImage } /** Constructs the [MonochromaticImage]. */ public fun build(): MonochromaticImage = MonochromaticImage(image, ambientImage) } /** Adds a [MonochromaticImage] to a builder for [WireComplicationData]. */ internal fun addToWireComplicationData(builder: WireComplicationDataBuilder) = builder.apply { setIcon(image) setBurnInProtectionIcon(ambientImage) } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as MonochromaticImage if (!if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { IconHelperP.equals(image, other.image) } else { IconHelperBeforeP.equals(image, other.image) } ) return false if (!if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { IconHelperP.equals(ambientImage, other.ambientImage) } else { IconHelperBeforeP.equals(ambientImage, other.ambientImage) } ) return false return true } override fun hashCode(): Int { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { var result = IconHelperP.hashCode(image) result = 31 * result + IconHelperP.hashCode(ambientImage) result } else { var result = IconHelperBeforeP.hashCode(image) result = 31 * result + IconHelperBeforeP.hashCode(ambientImage) result } } override fun toString(): String { return "MonochromaticImage(image=$image, ambientImage=$ambientImage)" } /** @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) fun isPlaceholder() = image.isPlaceholder() /** @hide */ public companion object { /** * For use when the real data isn't available yet, this [MonochromaticImage] should be * rendered as a placeholder. It is suggested that it should be rendered with a light grey * box. * * Note a placeholder may only be used in the context of * [NoDataComplicationData.placeholder]. */ @JvmField public val PLACEHOLDER: MonochromaticImage = MonochromaticImage(createPlaceholderIcon(), null) } } /** * The type of image being provided. * * This is used to guide rendering on the watch face. */ public enum class SmallImageType { /** * Type for images that have a transparent background and are expected to be drawn * entirely within the space available, such as a launcher image. Watch faces may add padding * when drawing these images, but should never crop these images. Icons must not be recolored. */ ICON, /** * Type for images which are photos that are expected to fill the space available. Images * of this style may be cropped to fit the shape of the complication - in particular, the image * may be cropped to a circle. Photos must not be recolored. */ PHOTO } /** * An image that is expected to cover a small fraction of a watch face occupied by a single * complication. A SmallImage must not be tinted. * * An ambient alternative is provided that may be shown instead of the regular image while the * watch is not active. * * @property [image] The image itself * @property [type] The style of the image provided, to guide how it should be displayed * @property [ambientImage] The image to be shown when the device is in ambient mode to save power * or avoid burn in */ public class SmallImage internal constructor( public val image: Icon, public val type: SmallImageType, public val ambientImage: Icon? ) { /** * Builder for [SmallImage]. * * @param [image] The [Icon] representing the image * @param [type] The style of the image provided, to guide how it should be displayed */ public class Builder(private val image: Icon, private val type: SmallImageType) { private var ambientImage: Icon? = null /** * Sets a different image for when the device is ambient mode to save power and prevent * burn in. If no ambient variant is provided, the watch face may not show anything while * in ambient mode. */ public fun setAmbientImage(ambientImage: Icon?): Builder = apply { this.ambientImage = ambientImage } /** Builds a [SmallImage]. */ public fun build(): SmallImage = SmallImage(image, type, ambientImage) } /** Adds a [SmallImage] to a builder for [WireComplicationData]. */ internal fun addToWireComplicationData(builder: WireComplicationDataBuilder) = builder.apply { setSmallImage(image) setSmallImageStyle( when (this@SmallImage.type) { SmallImageType.ICON -> WireComplicationData.IMAGE_STYLE_ICON SmallImageType.PHOTO -> WireComplicationData.IMAGE_STYLE_PHOTO } ) setBurnInProtectionSmallImage(ambientImage) } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as SmallImage if (type != other.type) return false if (!if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { IconHelperP.equals(image, other.image) } else { IconHelperBeforeP.equals(image, other.image) } ) return false if (!if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { IconHelperP.equals(ambientImage, other.ambientImage) } else { IconHelperBeforeP.equals(ambientImage, other.ambientImage) } ) return false return true } override fun hashCode(): Int { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { var result = IconHelperP.hashCode(image) result = 31 * result + type.hashCode() result = 31 * result + IconHelperP.hashCode(ambientImage) result } else { var result = IconHelperBeforeP.hashCode(image) result = 31 * result + type.hashCode() result = 31 * result + IconHelperBeforeP.hashCode(ambientImage) result } } override fun toString(): String { return "SmallImage(image=$image, type=$type, ambientImage=$ambientImage)" } /** @hide */ public companion object { /** * For use when the real data isn't available yet, this [SmallImage] should be rendered * as a placeholder. It is suggested that it should be rendered with a light grey box. * * Note a placeholder may only be used in the context of * [NoDataComplicationData.placeholder]. */ @JvmField public val PLACEHOLDER: SmallImage = SmallImage(createPlaceholderIcon(), SmallImageType.ICON, null) } /** @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) fun isPlaceholder() = image.isPlaceholder() } /** @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) fun Icon.isPlaceholder() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { IconHelperP.isPlaceholder(this) } else { false } @RequiresApi(Build.VERSION_CODES.P) internal class IconHelperP { companion object { fun isPlaceholder(icon: Icon): Boolean { return icon.type == Icon.TYPE_RESOURCE && icon.resId == PLACEHOLDER_IMAGE_RESOURCE_ID } fun equals(a: Icon?, b: Icon?): Boolean { if (a == null) { return b == null } if (b == null) { return false } if (a.type != b.type) return false when (a.type) { Icon.TYPE_RESOURCE -> { if (a.resId != b.resId) return false if (a.resPackage != b.resPackage) return false } Icon.TYPE_URI -> { if (a.uri.toString() != b.uri.toString()) return false } else -> { if (a != b) return false } } return true } fun hashCode(a: Icon?): Int { if (a == null) return 0 when (a.type) { Icon.TYPE_RESOURCE -> { var result = a.type.hashCode() result = 31 * result + a.resId.hashCode() result = 31 * result + a.resPackage.hashCode() return result } Icon.TYPE_URI -> { var result = a.type.hashCode() result = 31 * result + a.uri.toString().hashCode() return result } else -> return a.hashCode() } } } } internal class IconHelperBeforeP { companion object { fun equals(a: Icon?, b: Icon?): Boolean = (a == b) fun hashCode(a: Icon?): Int = a?.hashCode() ?: 0 } }
apache-2.0
e66b3be3e654e9212361d46ec745feb9
33.487952
99
0.6131
4.747098
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/ide/intentions/NestUseStatementsIntention.kt
2
7071
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiComment import com.intellij.psi.PsiElement import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.* /** * Nest imports 1 depth * * ``` * use a::b::foo; * use a::b::bar; * ``` * * to this: * * ``` * use a::{ * b::foo, * b::bar * } * ``` */ class NestUseStatementsIntention : RsElementBaseIntentionAction<NestUseStatementsIntention.Context>() { override fun getText() = "Nest use statements" override fun getFamilyName() = text interface Context { val useSpecks: List<RsUseSpeck> val root: PsiElement val firstOldElement: PsiElement fun createElement(path: String, project: Project): PsiElement val oldElements: List<PsiElement> val cursorOffset: Int val basePath: String } override fun findApplicableContext(project: Project, editor: Editor, element: PsiElement): Context? { val useItemOnCursor = element.ancestorStrict<RsUseItem>() ?: return null val useGroupOnCursor = element.ancestorStrict<RsUseGroup>() val useSpeckOnCursor = element.ancestorStrict<RsUseSpeck>() ?: return null return if (useGroupOnCursor != null) { PathInGroup.create(useGroupOnCursor, useSpeckOnCursor) } else { PathInUseItem.create(useItemOnCursor, useSpeckOnCursor) } } override fun invoke(project: Project, editor: Editor, ctx: Context) { val path = makeGroupedPath(ctx.basePath, ctx.useSpecks) val inserted = ctx.root.addAfter(ctx.createElement(path, project), ctx.firstOldElement) for (prevElement in ctx.oldElements) { val existingComment = prevElement.childrenWithLeaves.firstOrNull() as? PsiComment if (existingComment != null) { ctx.root.addBefore(existingComment, inserted) } prevElement.delete() } val nextUseSpeckExists = inserted.rightSiblings.filterIsInstance<RsUseSpeck>().count() > 0 if (nextUseSpeckExists) { ctx.root.addAfter(RsPsiFactory(project).createComma(), inserted) } editor.caretModel.moveToOffset(inserted!!.startOffset + ctx.cursorOffset) } private fun makeGroupedPath(basePath: String, useSpecks: List<RsUseSpeck>): String { val useSpecksInGroup = useSpecks.flatMap { useSpeck -> if (useSpeck.path?.text == basePath) { // Remove first group useSpeck.useGroup?.let { useGroup -> return@flatMap useGroup.useSpeckList.map { it.text } } useSpeck.alias?.let { alias -> return@flatMap listOf("self ${alias.text}") } } listOf(deleteBasePath(useSpeck.text, basePath)) } return useSpecksInGroup.joinToString(",\n", "$basePath::{\n", "\n}") } private fun deleteBasePath(fullPath: String, basePath: String): String { return when { fullPath == basePath -> "self" fullPath.startsWith(basePath) -> fullPath.removePrefix("$basePath::") else -> fullPath } } class PathInUseItem( private val useItem: RsUseItem, useItems: List<RsUseItem>, override val basePath: String ) : Context { companion object { fun create(useItemOnCursor: RsUseItem, useSpeck: RsUseSpeck): PathInUseItem? { val useItemList = mutableListOf<RsUseItem>() val basePath = useSpeck.path?.let(::getBasePathFromPath) ?: return null val visibility = useItemOnCursor.visibility useItemList += useItemOnCursor.leftSiblings.filterIsInstance<RsUseItem>() .filter { it.useSpeck?.path?.let(::getBasePathFromPath) == basePath && it.visibility == visibility } useItemList.add(useItemOnCursor) useItemList += useItemOnCursor.rightSiblings.filterIsInstance<RsUseItem>() .filter { it.useSpeck?.path?.let(::getBasePathFromPath) == basePath && it.visibility == visibility } if (useItemList.size == 1) return null return PathInUseItem(useItemOnCursor, useItemList, basePath) } } override fun createElement(path: String, project: Project): PsiElement { return RsPsiFactory(project).createUseItem(path, useItem.vis?.text ?: "") } override val useSpecks: List<RsUseSpeck> = useItems.mapNotNull { it.useSpeck } override val oldElements: List<PsiElement> = useItems override val firstOldElement: PsiElement = useItems.first() override val root: PsiElement = useItem.parent override val cursorOffset: Int = "use ".length } class PathInGroup( useGroup: RsUseGroup, override val useSpecks: List<RsUseSpeck>, override val basePath: String ) : Context { companion object { fun create(useGroup: RsUseGroup, useSpeckOnCursor: RsUseSpeck): PathInGroup? { val useSpeckList = mutableListOf<RsUseSpeck>() val basePath = useSpeckOnCursor.path?.let(::getBasePathFromPath) ?: return null useSpeckList += useSpeckOnCursor.leftSiblings.filterIsInstance<RsUseSpeck>() .filter { it.path?.let(::getBasePathFromPath) == basePath } useSpeckList.add(useSpeckOnCursor) useSpeckList += useSpeckOnCursor.rightSiblings.filterIsInstance<RsUseSpeck>() .filter { it.path?.let(::getBasePathFromPath) == basePath } if (useSpeckList.size == 1) return null return PathInGroup(useGroup, useSpeckList, basePath) } } override fun createElement(path: String, project: Project): PsiElement { return RsPsiFactory(project).createUseSpeck(path) } override val oldElements: List<PsiElement> = useSpecks.flatMap { val nextComma = if (it.nextSibling.elementType == RsElementTypes.COMMA) { it.nextSibling } else { null } listOf(it, nextComma) }.filterNotNull() override val firstOldElement: PsiElement = useSpecks.first() override val root = useGroup override val cursorOffset: Int = 0 } } /** * Get base path. * If the path starts with :: contains it * * ex) a::b::c -> a * ex) ::a::b::c -> ::a */ fun getBasePathFromPath(path: RsPath): String { val basePath = path.basePath() val basePathColoncolon = basePath.coloncolon return if (basePathColoncolon != null) { "::${basePath.referenceName.orEmpty()}" } else { basePath.referenceName.orEmpty() } }
mit
3bcf33ea72173d9456334e9a1be1fd23
34.179104
120
0.618724
4.99012
false
false
false
false
Senspark/ee-x
src/android/ads/src/main/java/com/ee/internal/BannerAdHelper.kt
1
2688
package com.ee.internal import android.graphics.Point import androidx.annotation.AnyThread import com.ee.IBannerAd import com.ee.IMessageBridge import com.ee.Utils import kotlinx.serialization.Serializable /** * Created by Zinge on 10/12/17. */ class BannerAdHelper(private val _bridge: IMessageBridge, private val _view: IBannerAd, private val _helper: MessageHelper) { @Serializable @Suppress("unused") private class GetPositionResponse( val x: Int, val y: Int ) @Serializable private class SetPositionRequest( val x: Int, val y: Int ) @Serializable @Suppress("unused") private class GetSizeResponse( val width: Int, val height: Int ) @Serializable private class SetSizeRequest( val width: Int, val height: Int ) @AnyThread fun registerHandlers() { _bridge.registerHandler(_helper.isLoaded) { Utils.toString(_view.isLoaded) } _bridge.registerHandler(_helper.load) { _view.load() "" } _bridge.registerHandler(_helper.getPosition) { val position = _view.position val response = GetPositionResponse(position.x, position.y) response.serialize() } _bridge.registerHandler(_helper.setPosition) { message -> val request = deserialize<SetPositionRequest>(message) _view.position = Point(request.x, request.y) "" } _bridge.registerHandler(_helper.getSize) { val size = _view.size val response = GetSizeResponse(size.x, size.y) response.serialize() } _bridge.registerHandler(_helper.setSize) { message -> val request = deserialize<SetSizeRequest>(message) _view.size = Point(request.width, request.height) "" } _bridge.registerHandler(_helper.isVisible) { Utils.toString(_view.isVisible) } _bridge.registerHandler(_helper.setVisible) { message -> _view.isVisible = Utils.toBoolean(message) "" } } @AnyThread fun deregisterHandlers() { _bridge.deregisterHandler(_helper.isLoaded) _bridge.deregisterHandler(_helper.load) _bridge.deregisterHandler(_helper.getPosition) _bridge.deregisterHandler(_helper.setPosition) _bridge.deregisterHandler(_helper.getSize) _bridge.deregisterHandler(_helper.setSize) _bridge.deregisterHandler(_helper.isVisible) _bridge.deregisterHandler(_helper.setVisible) } }
mit
f74c14d1473da1cad2b333852b60ec78
28.549451
70
0.607887
4.674783
false
false
false
false
foreverigor/TumCampusApp
app/src/main/java/de/tum/in/tumcampusapp/component/ui/transportation/model/efa/Departure.kt
1
1233
package de.tum.`in`.tumcampusapp.component.ui.transportation.model.efa import de.tum.`in`.tumcampusapp.component.ui.transportation.api.MvvDeparture import org.joda.time.DateTime import org.joda.time.Minutes data class Departure( val servingLine: String = "", val direction: String = "", val symbol: String = "", val countDown: Int = -1, val departureTime: DateTime = DateTime() ) { /** * Calculates the countDown with the real departure time and the current time * * @return The calculated countDown in minutes */ val calculatedCountDown: Int get() = Minutes.minutesBetween(DateTime.now(), departureTime).minutes val formattedDirection: String get() = direction .replace(",", ", ") .replace("\\s+".toRegex(), " ") companion object { fun create(mvvDeparture: MvvDeparture): Departure { return Departure( mvvDeparture.servingLine.name, mvvDeparture.servingLine.direction, mvvDeparture.servingLine.symbol, mvvDeparture.countdown, mvvDeparture.dateTime ) } } }
gpl-3.0
9aa7ec8a59d8729109fd81dbd40639aa
28.357143
81
0.595296
4.991903
false
false
false
false
ryan652/EasyCrypt
appKotlin/src/main/java/com/pvryan/easycryptsample/main/MainAdapter.kt
1
2817
/* * Copyright 2018 Priyank Vasa * 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.pvryan.easycryptsample.main import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.pvryan.easycryptsample.R import com.pvryan.easycryptsample.data.models.Card import com.pvryan.easycryptsample.extensions.gone import com.pvryan.easycryptsample.extensions.show import com.transitionseverywhere.Rotate import com.transitionseverywhere.TransitionManager import kotlinx.android.synthetic.main.card_view_main.view.* class MainAdapter(private val mDataset: ArrayList<Card>) : RecyclerView.Adapter<MainAdapter.ViewHolder>() { override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bindItems(mDataset[position]) holder.itemView.buttonExpandCollapse.setOnClickListener { TransitionManager.beginDelayedTransition(it.parent as ViewGroup, Rotate()) with(holder.itemView.tvDesc) { if (visibility == View.VISIBLE) { it.rotation = 0f gone(true) } else { it.rotation = 180f show(true) } } } } override fun getItemCount() = mDataset.size override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val v = LayoutInflater.from(parent.context).inflate(R.layout.card_view_main, parent, false) return ViewHolder(v) } class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { fun bindItems(card: Card) { itemView.tvTitle.text = card.title itemView.tvDesc.text = card.desc itemView.buttonAction1.text = card.actionText1 itemView.buttonAction2.text = card.actionText2 if (card.action1 == null) { itemView.buttonAction1.visibility = View.GONE } else { itemView.buttonAction1.setOnClickListener(card.action1) } if (card.action2 == null) { itemView.buttonAction2.visibility = View.GONE } else { itemView.buttonAction2.setOnClickListener(card.action2) } } } }
apache-2.0
69c350934a32aae955a428eb4a0ff597
36.56
107
0.670572
4.595432
false
false
false
false
androidx/androidx
benchmark/benchmark-macro/src/main/java/androidx/benchmark/macro/perfetto/AudioUnderrunQuery.kt
3
2574
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.benchmark.macro.perfetto internal object AudioUnderrunQuery { private fun getFullQuery() = """ SELECT track.name, counter.value, counter.ts FROM track JOIN counter ON track.id = counter.track_id WHERE track.type = 'process_counter_track' AND track.name LIKE 'nRdy%' """.trimIndent() data class SubMetrics( val totalMs: Int, val zeroMs: Int ) fun getSubMetrics( perfettoTraceProcessor: PerfettoTraceProcessor ): SubMetrics { val queryResult = perfettoTraceProcessor.rawQuery(getFullQuery()) var trackName: String? = null var lastTs: Long? = null var totalNs: Long = 0 var zeroNs: Long = 0 queryResult .asSequence() .forEach { lineVals -> if (lineVals.size != EXPECTED_COLUMN_COUNT) throw IllegalStateException("query failed") if (trackName == null) { trackName = lineVals[VAL_NAME] as String? } else if (trackName!! != lineVals[VAL_NAME]) { throw RuntimeException("There could be only one AudioTrack per measure") } if (lastTs == null) { lastTs = lineVals[VAL_TS] as Long } else { val frameNs = lineVals[VAL_TS] as Long - lastTs!! lastTs = lineVals[VAL_TS] as Long totalNs += frameNs val frameCounter = (lineVals[VAL_VALUE] as Double).toInt() if (frameCounter == 0) zeroNs += frameNs } } return SubMetrics((totalNs / 1_000_000).toInt(), (zeroNs / 1_000_000).toInt()) } private const val VAL_NAME = "name" private const val VAL_VALUE = "value" private const val VAL_TS = "ts" private const val EXPECTED_COLUMN_COUNT = 3 }
apache-2.0
127afaedbfe8cfcbcb41015d663ede5f
32.441558
92
0.590909
4.588235
false
false
false
false
androidx/androidx
room/room-compiler-processing/src/main/java/androidx/room/compiler/processing/ksp/KSTypeReferenceExt.kt
3
2508
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.compiler.processing.ksp import com.google.devtools.ksp.symbol.KSAnnotation import com.google.devtools.ksp.symbol.KSNode import com.google.devtools.ksp.symbol.KSReferenceElement import com.google.devtools.ksp.symbol.KSType import com.google.devtools.ksp.symbol.KSTypeReference import com.google.devtools.ksp.symbol.KSVisitor import com.google.devtools.ksp.symbol.Location import com.google.devtools.ksp.symbol.Modifier import com.google.devtools.ksp.symbol.NonExistLocation import com.google.devtools.ksp.symbol.Origin /** * Creates a new TypeReference from [this] where the resolved type [replacement] but everything * else is the same (e.g. location). */ internal fun KSTypeReference.swapResolvedType(replacement: KSType): KSTypeReference { return DelegatingTypeReference( original = this, resolved = replacement ) } /** * Creates a [NonExistLocation] type reference for [this]. */ internal fun KSType.createTypeReference(): KSTypeReference { return NoLocationTypeReference(this) } private class DelegatingTypeReference( val original: KSTypeReference, val resolved: KSType ) : KSTypeReference by original { override fun resolve() = resolved } private class NoLocationTypeReference( val resolved: KSType ) : KSTypeReference { override val annotations: Sequence<KSAnnotation> get() = emptySequence() override val element: KSReferenceElement? get() = null override val location: Location get() = NonExistLocation override val modifiers: Set<Modifier> get() = emptySet() override val origin: Origin get() = Origin.SYNTHETIC override val parent: KSNode? get() = null override fun <D, R> accept(visitor: KSVisitor<D, R>, data: D): R { return visitor.visitTypeReference(this, data) } override fun resolve(): KSType = resolved }
apache-2.0
3e282e2fb7075bba118ff590b40a11b1
32.013158
95
0.738038
4.324138
false
false
false
false
androidx/androidx
glance/glance-appwidget/src/androidMain/kotlin/androidx/glance/appwidget/action/StartServiceAction.kt
3
3661
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.glance.appwidget.action import android.app.Service import android.content.ComponentName import android.content.Intent import androidx.glance.action.Action internal sealed interface StartServiceAction : Action { val isForegroundService: Boolean } internal class StartServiceComponentAction( val componentName: ComponentName, override val isForegroundService: Boolean ) : StartServiceAction internal class StartServiceClassAction( val serviceClass: Class<out Service>, override val isForegroundService: Boolean ) : StartServiceAction internal class StartServiceIntentAction( val intent: Intent, override val isForegroundService: Boolean ) : StartServiceAction /** * Creates an [Action] that launches a [Service] from the given [Intent] when triggered. The * intent should specify a component with [Intent.setClass] or [Intent.setComponent]. * * @param intent the intent used to launch the activity * @param isForegroundService set to true when the provided [Service] runs in foreground. This flag * is only used for device versions after [android.os.Build.VERSION_CODES.O] that requires * foreground service to be launched differently */ fun actionStartService(intent: Intent, isForegroundService: Boolean = false): Action = StartServiceIntentAction(intent, isForegroundService) /** * Creates an [Action] that launches the [Service] specified by the given [ComponentName]. * * @param componentName component of the Service to launch * @param isForegroundService set to true when the provided [Service] runs in foreground. This flag * is only used for device versions after [android.os.Build.VERSION_CODES.O] that requires * foreground service to be launched differently */ fun actionStartService( componentName: ComponentName, isForegroundService: Boolean = false ): Action = StartServiceComponentAction(componentName, isForegroundService) /** * Creates an [Action] that launches the specified [Service] when triggered. * * @param service class of the Service to launch * @param isForegroundService set to true when the provided [Service] runs in foreground. This flag * is only used for device versions after [android.os.Build.VERSION_CODES.O] that requires * foreground service to be launched differently */ fun <T : Service> actionStartService( service: Class<T>, isForegroundService: Boolean = false ): Action = StartServiceClassAction(service, isForegroundService) /** * Creates an [Action] that launches the specified [Service] when triggered. * * @param isForegroundService set to true when the provided [Service] runs in foreground. This flag * is only used for device versions after [android.os.Build.VERSION_CODES.O] that requires * foreground service to be launched differently. */ @Suppress("MissingNullability") /* Shouldn't need to specify @NonNull. b/199284086 */ inline fun <reified T : Service> actionStartService( isForegroundService: Boolean = false ): Action = actionStartService(T::class.java, isForegroundService)
apache-2.0
7f0138c89372e5f3772f697804b30835
38.365591
99
0.771374
4.640051
false
false
false
false
jean79/yested
src/main/kotlin/net/yested/bootstrap/alerts.kt
2
1244
package net.yested.bootstrap import net.yested.HTMLComponent import net.yested.Anchor import net.yested.with import net.yested.isTrue import org.w3c.dom.events.Event /** * Created by jean on 25.12.2014. * */ enum class AlertStyle(val code:String) { SUCCESS("success"), INFO("info"), WARNING("warning"), DANGER("danger") } class Alert(style: AlertStyle, dismissible: Boolean = false) : HTMLComponent("div") { init { clazz = "alert alert-${style.code} ${dismissible.isTrue("alert-dismissible", "")}" if (dismissible) { tag("button") { clazz = "close"; "type".."button"; "data-dismiss".."alert"; "aria-label".."Close" span { "aria-hidden".."true" +"&times;" } } } } override fun a(clazz: String?, target: String?, href: String?, onclick: ((Event) -> Unit)?, init: Anchor.() -> Unit) { super.a(clazz = clazz?:"alert-link", target = target, href = href, onclick = onclick, init = init) } } fun HTMLComponent.alert(style: AlertStyle, dismissible: Boolean = false, init:Alert.() -> Unit) = +(Alert(style = style, dismissible = dismissible) with { init() } )
mit
04fa7d9a5ded3fd0d1c26f34281a9656
27.930233
122
0.580386
3.804281
false
false
false
false
dropbox/Store
store/src/main/java/com/dropbox/android/external/store4/MemoryPolicy.kt
1
4154
package com.dropbox.android.external.store4 import kotlin.time.Duration import kotlin.time.ExperimentalTime fun interface Weigher<in K : Any, in V : Any> { /** * Returns the weight of a cache entry. There is no unit for entry weights; rather they are simply * relative to each other. * * @return the weight of the entry; must be non-negative */ fun weigh(key: K, value: V): Int } internal object OneWeigher : Weigher<Any, Any> { override fun weigh(key: Any, value: Any): Int = 1 } /** * MemoryPolicy holds all required info to create MemoryCache * * * This class is used, in order to define the appropriate parameters for the Memory [com.dropbox.android.external.cache3.Cache] * to be built. * * * MemoryPolicy is used by a [Store] * and defines the in-memory cache behavior. */ @ExperimentalTime class MemoryPolicy<in Key : Any, in Value : Any> internal constructor( val expireAfterWrite: Duration, val expireAfterAccess: Duration, val maxSize: Long, val maxWeight: Long, val weigher: Weigher<Key, Value> ) { val isDefaultWritePolicy: Boolean = expireAfterWrite == DEFAULT_DURATION_POLICY val hasWritePolicy: Boolean = expireAfterWrite != DEFAULT_DURATION_POLICY val hasAccessPolicy: Boolean = expireAfterAccess != DEFAULT_DURATION_POLICY val hasMaxSize: Boolean = maxSize != DEFAULT_SIZE_POLICY val hasMaxWeight: Boolean = maxWeight != DEFAULT_SIZE_POLICY class MemoryPolicyBuilder<Key : Any, Value : Any> { private var expireAfterWrite = DEFAULT_DURATION_POLICY private var expireAfterAccess = DEFAULT_DURATION_POLICY private var maxSize: Long = DEFAULT_SIZE_POLICY private var maxWeight: Long = DEFAULT_SIZE_POLICY private var weigher: Weigher<Key, Value> = OneWeigher fun setExpireAfterWrite(expireAfterWrite: Duration): MemoryPolicyBuilder<Key, Value> = apply { check(expireAfterAccess == DEFAULT_DURATION_POLICY) { "Cannot set expireAfterWrite with expireAfterAccess already set" } this.expireAfterWrite = expireAfterWrite } fun setExpireAfterAccess(expireAfterAccess: Duration): MemoryPolicyBuilder<Key, Value> = apply { check(expireAfterWrite == DEFAULT_DURATION_POLICY) { "Cannot set expireAfterAccess with expireAfterWrite already set" } this.expireAfterAccess = expireAfterAccess } /** * Sets the maximum number of items ([maxSize]) kept in the cache. * * When [maxSize] is 0, entries will be discarded immediately and no values will be cached. * * If not set, cache size will be unlimited. */ fun setMaxSize(maxSize: Long): MemoryPolicyBuilder<Key, Value> = apply { check(maxWeight == DEFAULT_SIZE_POLICY && weigher == OneWeigher) { "Cannot setMaxSize when maxWeight or weigher are already set" } check(maxSize >= 0) { "maxSize cannot be negative" } this.maxSize = maxSize } fun setWeigherAndMaxWeight( weigher: Weigher<Key, Value>, maxWeight: Long ): MemoryPolicyBuilder<Key, Value> = apply { check(maxSize == DEFAULT_SIZE_POLICY) { "Cannot setWeigherAndMaxWeight when maxSize already set" } check(maxWeight >= 0) { "maxWeight cannot be negative" } this.weigher = weigher this.maxWeight = maxWeight } fun build() = MemoryPolicy<Key, Value>( expireAfterWrite = expireAfterWrite, expireAfterAccess = expireAfterAccess, maxSize = maxSize, maxWeight = maxWeight, weigher = weigher ) } companion object { val DEFAULT_DURATION_POLICY: Duration = Duration.INFINITE const val DEFAULT_SIZE_POLICY: Long = -1 fun <Key : Any, Value : Any> builder(): MemoryPolicyBuilder<Key, Value> = MemoryPolicyBuilder() } }
apache-2.0
b2375e6ec7301461885c5e92930946b2
34.810345
127
0.633847
4.921801
false
false
false
false
EventFahrplan/EventFahrplan
database/src/main/java/info/metadude/android/eventfahrplan/database/models/Alarm.kt
1
692
package info.metadude.android.eventfahrplan.database.models import info.metadude.android.eventfahrplan.database.contract.FahrplanContract.AlarmsTable.Defaults.ALARM_TIME_IN_MIN_DEFAULT import info.metadude.android.eventfahrplan.database.contract.FahrplanContract.AlarmsTable.Defaults.DEFAULT_VALUE_ID data class Alarm( val id: Int = DEFAULT_VALUE_ID, val alarmTimeInMin: Int = ALARM_TIME_IN_MIN_DEFAULT, val day: Int = -1, val displayTime: Long = -1, // will be stored as signed integer val sessionId: String = "", val time: Long = -1, // will be stored as signed integer val timeText: String = "", val title: String = "" )
apache-2.0
40355f2744ce503113a98ac3436cfef8
39.705882
124
0.703757
3.931818
false
false
false
false
jeremymailen/kotlinter-gradle
src/test/kotlin/org/jmailen/gradle/kotlinter/functional/WithGradleTest.kt
1
2290
package org.jmailen.gradle.kotlinter.functional import org.apache.commons.io.FileUtils import org.gradle.internal.classpath.DefaultClassPath import org.gradle.testkit.runner.BuildResult import org.gradle.testkit.runner.GradleRunner import org.gradle.testkit.runner.internal.PluginUnderTestMetadataReading import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import java.io.File import java.nio.file.Files abstract class WithGradleTest { lateinit var testProjectDir: File /** * Not using JUnit's @TempDir, due do https://github.com/gradle/gradle/issues/12535 */ @BeforeEach internal fun setUpTempdir() { testProjectDir = Files.createTempDirectory(this::class.java.simpleName).toFile() } @AfterEach internal fun cleanUpTempdir() { FileUtils.forceDeleteOnExit(testProjectDir) } protected fun build(vararg args: String): BuildResult = gradleRunnerFor(*args).build() protected fun buildAndFail(vararg args: String): BuildResult = gradleRunnerFor(*args).buildAndFail() protected abstract fun gradleRunnerFor(vararg args: String): GradleRunner abstract class Android : WithGradleTest() { override fun gradleRunnerFor(vararg args: String): GradleRunner { return defaultRunner(*args) .withPluginClasspath() } } abstract class Kotlin : WithGradleTest() { override fun gradleRunnerFor(vararg args: String): GradleRunner { val classpath = DefaultClassPath.of(PluginUnderTestMetadataReading.readImplementationClasspath()).asFiles val androidDependencies = listOf( ".*/com\\.android\\..*/.*".toRegex(), ".*/androidx\\..*/.*".toRegex(), ".*/com\\.google\\..*/.*".toRegex(), ) val noAndroid = classpath.filterNot { dependency -> androidDependencies.any { it.matches(dependency.path) } } return defaultRunner(*args) .withPluginClasspath(noAndroid) } } } private fun WithGradleTest.defaultRunner(vararg args: String) = GradleRunner.create() .withProjectDir(testProjectDir) .withArguments(args.toList() + listOf("--stacktrace", "--configuration-cache")) .forwardOutput()
apache-2.0
8a2b40865c7c21d9212d0759f2ef380b
34.230769
121
0.686026
4.989107
false
true
false
false
andstatus/andstatus
app/src/androidTest/kotlin/org/andstatus/app/net/http/OAuthClientKeysTest.kt
1
2578
/* * Copyright (c) 2013 yvolk (Yuri Volkov), http://yurivolkov.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.andstatus.app.net.http import org.andstatus.app.account.AccountConnectionData import org.andstatus.app.context.MyContextHolder import org.andstatus.app.context.TestSuite import org.andstatus.app.origin.OriginType import org.andstatus.app.util.TriState import org.andstatus.app.util.UrlUtils import org.junit.Assert import org.junit.Before import org.junit.Test class OAuthClientKeysTest { @Before fun setUp() { TestSuite.forget() TestSuite.initialize(this) } @Test fun testKeysSave() { val connectionData: HttpConnectionData = HttpConnectionData.Companion.fromAccountConnectionData( AccountConnectionData.Companion.fromMyAccount( MyContextHolder.myContextHolder.getNow().accounts.getFirstPreferablySucceededForOrigin( MyContextHolder.myContextHolder.getNow().origins.firstOfType(OriginType.PUMPIO)), TriState.UNKNOWN) ) val consumerKey = "testConsumerKey" + System.nanoTime().toString() val consumerSecret = "testConsumerSecret" + System.nanoTime().toString() connectionData.originUrl = UrlUtils.fromString("https://example.com") val keys1: OAuthClientKeys = OAuthClientKeys.Companion.fromConnectionData(connectionData) keys1.clear() Assert.assertEquals("Keys are cleared", false, keys1.areKeysPresent()) keys1.setConsumerKeyAndSecret(consumerKey, consumerSecret) val keys2: OAuthClientKeys = OAuthClientKeys.Companion.fromConnectionData(connectionData) Assert.assertEquals("Keys are loaded", true, keys2.areKeysPresent()) Assert.assertEquals(consumerKey, keys2.getConsumerKey()) Assert.assertEquals(consumerSecret, keys2.getConsumerSecret()) keys2.clear() val keys3: OAuthClientKeys = OAuthClientKeys.Companion.fromConnectionData(connectionData) Assert.assertEquals("Keys are cleared", false, keys3.areKeysPresent()) } }
apache-2.0
1642ba90d41f29e293cb044904294c20
45.035714
150
0.742048
4.579041
false
true
false
false
fredyw/leetcode
src/main/kotlin/leetcode/Problem1604.kt
1
1255
package leetcode /** * https://leetcode.com/problems/alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/ */ class Problem1604 { fun alertNames(keyName: Array<String>, keyTime: Array<String>): List<String> { val map = mutableMapOf<String, MutableList<String>>() for (i in keyName.indices) { val times = map[keyName[i]] ?: mutableListOf() times += keyTime[i] map[keyName[i]] = times } val answer = mutableListOf<String>() for ((key, value) in map) { var i = 0 value.sort() while (i < value.size - 2) { val t = difference(value[i], value[i + 1]) + difference(value[i + 1], value[i + 2]) if (t <= 60) { answer += key break } i++ } } answer.sort() return answer } private fun difference(from: String, to: String): Int { val (fromHour, fromMinute) = from.split(":") val (toHour, toMinute) = to.split(":") val minute = toMinute.toInt() - fromMinute.toInt() val hour = (toHour.toInt() - fromHour.toInt()) * 60 return minute + hour } }
mit
4405496a79afd8399ca4e60d9aa9c6ec
32.026316
100
0.50757
3.958991
false
false
false
false