repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
smmribeiro/intellij-community
jvm/jvm-analysis-kotlin-tests/testSrc/com/intellij/codeInspection/tests/kotlin/KotlinJUnit5MalformedParameterizedTest.kt
1
3006
// 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.codeInspection.tests.kotlin import com.intellij.execution.junit.codeInsight.JUnit5MalformedParameterizedInspection import com.intellij.execution.junit.codeInsight.JUnit5TestFrameworkSetupUtil import com.intellij.jvm.analysis.KotlinJvmAnalysisTestUtil import com.intellij.openapi.application.PathManager import com.intellij.pom.java.LanguageLevel import com.intellij.testFramework.TestDataPath import com.intellij.testFramework.builders.JavaModuleFixtureBuilder import com.intellij.testFramework.fixtures.JavaCodeInsightFixtureTestCase import java.io.File private const val inspectionPath = "/codeInspection/junit5malformed" @TestDataPath("\$CONTENT_ROOT/testData$inspectionPath") class KotlinJUnit5MalformedParameterizedTest : JavaCodeInsightFixtureTestCase() { override fun getBasePath() = KotlinJvmAnalysisTestUtil.TEST_DATA_PROJECT_RELATIVE_BASE_PATH + inspectionPath override fun getTestDataPath(): String = PathManager.getCommunityHomePath().replace(File.separatorChar, '/') + basePath override fun tuneFixture(moduleBuilder: JavaModuleFixtureBuilder<*>) { moduleBuilder.setLanguageLevel(LanguageLevel.JDK_1_8) } override fun setUp() { super.setUp() myFixture.enableInspections(inspection) myFixture.addFileToProject("kotlin/jvm/JvmStatic.kt", "package kotlin.jvm public annotation class JvmStatic") myFixture.addClass(""" package java.util.stream; public interface Stream {} """.trimIndent()) JUnit5TestFrameworkSetupUtil.setupJUnit5Library(myFixture) } override fun tearDown() { try { myFixture.disableInspections(inspection) } finally { super.tearDown() } } companion object { private val inspection = JUnit5MalformedParameterizedInspection() } fun `test CantResolveTarget`() { myFixture.testHighlighting("CantResolveTarget.kt") } fun `test CantResolveTarget highlighting`() { myFixture.testHighlighting("CantResolveTarget.kt") } fun `test StaticMethodSourceTest quickFixes`() { val quickfixes = myFixture.getAllQuickFixes("StaticMethodSource.kt") quickfixes.forEach { myFixture.launchAction(it) } myFixture.checkResultByFile("StaticMethodSource.after.kt") } fun `test SuspiciousCombination quickFixes`() { myFixture.testHighlighting("SuspiciousCombination.kt") } fun `test NoSourcesProvided quickFixes`() { myFixture.testHighlighting("NoSourcesProvided.kt") } fun `test ExactlyOneType quickFixes`() { myFixture.testHighlighting("ExactlyOneType.kt") } fun `test NoParams quickFixes`() { myFixture.testHighlighting("NoParams.kt") } fun `test ReturnType quickFixes`() { myFixture.testHighlighting("ReturnType.kt") } fun `test EnumResolve quickFixes`() { myFixture.testHighlighting("EnumResolve.kt") } }
apache-2.0
f7e67f9313b51b16faea60dd0a15a7a1
32.411111
158
0.765136
4.82504
false
true
false
false
LouisCAD/Splitties
modules/lifecycle-coroutines/src/androidTest/kotlin/splitties/lifecycle/coroutines/LifecycleTest.kt
1
5254
/* * Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license. */ package splitties.lifecycle.coroutines import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LifecycleRegistry import kotlinx.coroutines.* import kotlinx.coroutines.test.* import splitties.experimental.ExperimentalSplittiesApi import kotlin.coroutines.resume import kotlin.coroutines.suspendCoroutine import kotlin.test.AfterTest import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertSame import kotlin.test.assertTrue @Suppress("DEPRECATION") @ExperimentalSplittiesApi class LifecycleTest { @OptIn(ExperimentalCoroutinesApi::class) private val mainDispatcherSurrogate = newSingleThreadContext("main thread surrogate") @BeforeTest @OptIn(ExperimentalCoroutinesApi::class) fun setUp() { Dispatchers.setMain(mainDispatcherSurrogate) } @Test fun test_lifecycle_default_scope_uses_default_job() = runBlocking { val lifecycle = TestLifecycleOwner().lifecycle lifecycle.markState(Lifecycle.State.CREATED) val lifecycleJob = lifecycle.job val lifecycleScopeJob = lifecycle.coroutineScope.coroutineContext[Job] assertSame(lifecycleJob, lifecycleScopeJob) lifecycle.markState(Lifecycle.State.DESTROYED) } @Test fun test_lifecycle_job_is_cached() = runBlocking { val lifecycle = TestLifecycleOwner().lifecycle lifecycle.markState(Lifecycle.State.CREATED) assertSame(lifecycle.job, lifecycle.job) lifecycle.markState(Lifecycle.State.DESTROYED) } @Test fun test_lifecycle_on_destroy_cancels_job() = runBlocking { val lifecycle = TestLifecycleOwner().lifecycle lifecycle.markState(Lifecycle.State.CREATED) val job = lifecycle.job assertTrue(job.isActive) assertFalse(job.isCancelled) lifecycle.markState(Lifecycle.State.STARTED) lifecycle.markState(Lifecycle.State.RESUMED) assertTrue(job.isActive) assertFalse(job.isCancelled) lifecycle.markState(Lifecycle.State.DESTROYED) suspendCoroutine<Unit> { c -> job.invokeOnCompletion { c.resume(Unit) } } assertTrue(job.isCancelled) assertFalse(job.isActive) } @Test fun test_already_destroyed_lifecycle_makes_cancelled_job() = runBlocking { val lifecycle = TestLifecycleOwner().lifecycle lifecycle.markState(Lifecycle.State.CREATED) lifecycle.markState(Lifecycle.State.DESTROYED) val job = lifecycle.job assertFalse(job.isActive) assertTrue(job.isCancelled) } @Test fun test_lifecycle_owner_scope_is_lifecycle_scope() = runBlocking { val lifecycleOwner = TestLifecycleOwner() val lifecycle = lifecycleOwner.lifecycle assertSame(lifecycle.coroutineScope, lifecycleOwner.lifecycleScope) } @Test fun test_scope_is_not_active_after_destroy() = runBlocking { var count = 0 val lifecycle = TestLifecycleOwner().lifecycle lifecycle.markState(Lifecycle.State.CREATED) lifecycle.markState(Lifecycle.State.STARTED) val scope = lifecycle.createScope(Lifecycle.State.STARTED) assertEquals(1, ++count) val testJob = scope.launch { try { assertEquals(2, ++count) delay(Long.MAX_VALUE) assertTrue(false, "Should never be reached") } catch (e: CancellationException) { assertEquals(3, ++count) throw e } finally { assertEquals(4, ++count) } } lifecycle.markState(Lifecycle.State.CREATED) testJob.join() assertEquals(5, ++count) assertFalse(scope.isActive) lifecycle.markState(Lifecycle.State.DESTROYED) } @Test fun test_observer_is_called_after_destroy() = runBlocking { val lifecycle = TestLifecycleOwner().lifecycle lifecycle.markState(Lifecycle.State.CREATED) val activeWhile = Lifecycle.State.INITIALIZED val job = with(lifecycle) { Job().also { job -> addObserver(object : LifecycleEventObserver { override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) { if (currentState < activeWhile) { removeObserver(this) job.cancel() } } }) } } assertTrue(job.isActive) assertFalse(job.isCancelled) lifecycle.markState(Lifecycle.State.DESTROYED) job.join() assertFalse(job.isActive) assertTrue(job.isCancelled) } @AfterTest fun closeTestMainDispatcher() { mainDispatcherSurrogate.close() } private class TestLifecycleOwner : LifecycleOwner { private val lifecycle = LifecycleRegistry(this) override fun getLifecycle() = lifecycle } }
apache-2.0
8e5a7ac1c934531a0d3ac68720b0031f
33.565789
109
0.664256
5.027751
false
true
false
false
smmribeiro/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/gradle/GradleModuleTransformer.kt
2
8999
package com.jetbrains.packagesearch.intellij.plugin.gradle import com.intellij.openapi.application.runReadAction import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleUtilCore import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.pom.Navigatable import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiManager import com.intellij.psi.util.PsiUtil import com.jetbrains.packagesearch.intellij.plugin.extensibility.BuildSystemType import com.jetbrains.packagesearch.intellij.plugin.extensibility.ModuleTransformer import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModule import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageVersion import com.jetbrains.packagesearch.intellij.plugin.util.logDebug import org.jetbrains.plugins.gradle.model.ExternalProject import org.jetbrains.plugins.gradle.service.project.data.ExternalProjectDataCache import org.jetbrains.plugins.gradle.settings.GradleExtensionsSettings import org.jetbrains.plugins.gradle.util.GradleConstants internal class GradleModuleTransformer : ModuleTransformer { companion object { fun findDependencyElement(file: PsiFile, groupId: String, artifactId: String): PsiElement? { val isKotlinDependencyInKts = file.language::class.qualifiedName == "org.jetbrains.kotlin.idea.KotlinLanguage" && groupId == "org.jetbrains.kotlin" && artifactId.startsWith("kotlin-") val textToSearchFor = if (isKotlinDependencyInKts) { "kotlin(\"${artifactId.removePrefix("kotlin-")}\")" } else { "$groupId:$artifactId" } return file.firstElementContainingExactly(textToSearchFor) } } override fun transformModules(project: Project, nativeModules: List<Module>): List<ProjectModule> = nativeModules.filter { it.isNotGradleSourceSetModule() } .mapNotNull { nativeModule -> val externalProject = findExternalProjectOrNull(project, nativeModule, recursiveSearch = false) ?: return@mapNotNull null val buildFile = externalProject.buildFile ?: return@mapNotNull null val buildVirtualFile = LocalFileSystem.getInstance().findFileByPath(buildFile.absolutePath) ?: return@mapNotNull null val buildSystemType = if (isKotlinDsl(project, buildVirtualFile)) { BuildSystemType.GRADLE_KOTLIN } else { BuildSystemType.GRADLE_GROOVY } val scopes: List<String> = GradleExtensionsSettings.getInstance(project) .getExtensionsFor(nativeModule)?.configurations?.keys?.toList() ?: emptyList() ProjectModule( name = externalProject.name, nativeModule = nativeModule, parent = null, buildFile = buildVirtualFile, buildSystemType = buildSystemType, moduleType = GradleProjectModuleType, navigatableDependency = createNavigatableDependencyCallback(project, buildVirtualFile), availableScopes = scopes ) } .flatMap { getAllSubmodules(project, it) } .distinctBy { it.buildFile } private fun isKotlinDsl( project: Project, buildVirtualFile: VirtualFile ) = runCatching { PsiManager.getInstance(project).findFile(buildVirtualFile) } .getOrNull() ?.language ?.displayName ?.contains("kotlin", ignoreCase = true) == true private fun Module.isNotGradleSourceSetModule(): Boolean { if (!ExternalSystemApiUtil.isExternalSystemAwareModule(GradleConstants.SYSTEM_ID, this)) return false return ExternalSystemApiUtil.getExternalModuleType(this) != GradleConstants.GRADLE_SOURCE_SET_MODULE_TYPE_KEY } private fun getAllSubmodules(project: Project, rootModule: ProjectModule): List<ProjectModule> { val externalRootProject = findExternalProjectOrNull(project, rootModule.nativeModule) ?: return emptyList() val modules = mutableListOf(rootModule) externalRootProject.addChildrenToListRecursive(modules, rootModule, project) return modules } private fun findExternalProjectOrNull( project: Project, module: Module, recursiveSearch: Boolean = true ): ExternalProject? { if (!ExternalSystemApiUtil.isExternalSystemAwareModule(GradleConstants.SYSTEM_ID, module)) { return null } val externalProjectId = ExternalSystemApiUtil.getExternalProjectId(module) if (externalProjectId == null) { logDebug(this::class.qualifiedName) { "Module has no external project ID, project=${project.projectFilePath}, module=${module.moduleFilePath}" } return null } val rootProjectPath = ExternalSystemApiUtil.getExternalRootProjectPath(module) if (rootProjectPath == null) { logDebug(this::class.qualifiedName) { "Root external project was not yet imported, project=${project.projectFilePath}, module=${module.moduleFilePath}" } return null } val externalProjectDataCache = ExternalProjectDataCache.getInstance(project) val externalProject = externalProjectDataCache.getRootExternalProject(rootProjectPath) if (externalProject == null) { logDebug(this::class.qualifiedName) { "External project is not yet cached, project=${project.projectFilePath}, module=${module.moduleFilePath}" } return null } return externalProject.findProjectWithId(externalProjectId, recursiveSearch) } private fun ExternalProject.findProjectWithId( externalProjectId: String, recursiveSearch: Boolean ): ExternalProject? { if (externalProjectId == this.id) return this if (!recursiveSearch) return null val childExternalProjects = childProjects.values if (childExternalProjects.isEmpty()) return null for (childExternalProject in childExternalProjects) { if (childExternalProject.id == externalProjectId) return childExternalProject val recursiveExternalProject = childExternalProject.findProjectWithId(externalProjectId, recursiveSearch) if (recursiveExternalProject != null) return recursiveExternalProject } return null } private fun ExternalProject.addChildrenToListRecursive( modules: MutableList<ProjectModule>, currentModule: ProjectModule, project: Project ) { val localFileSystem = LocalFileSystem.getInstance() for (externalProject in childProjects.values) { val projectBuildFile = externalProject.buildFile?.absolutePath?.let(localFileSystem::findFileByPath) ?: continue val nativeModule = ModuleUtilCore.findModuleForFile(projectBuildFile, project) ?: continue val projectModule = ProjectModule( name = externalProject.name, nativeModule = nativeModule, parent = currentModule, buildFile = projectBuildFile, buildSystemType = BuildSystemType.GRADLE_GROOVY, moduleType = GradleProjectModuleType, navigatableDependency = createNavigatableDependencyCallback(project, projectBuildFile), availableScopes = emptyList() ) modules += projectModule externalProject.addChildrenToListRecursive(modules, projectModule, project) } } private fun createNavigatableDependencyCallback(project: Project, file: VirtualFile) = { groupId: String, artifactId: String, _: PackageVersion -> runReadAction { PsiManager.getInstance(project).findFile(file)?.let { psiFile -> val dependencyElement = findDependencyElement(psiFile, groupId, artifactId) ?: return@let null return@let dependencyElement as Navigatable } } } } private fun PsiFile.firstElementContainingExactly(value: String): PsiElement? { val index = text.indexOf(value) if (index < 0) return null if (text.length > value.length && text[index + value.length] != ':') return null val element = getElementAtOffsetOrNull(index) return element } private fun PsiFile.getElementAtOffsetOrNull(index: Int) = PsiUtil.getElementAtOffset(this, index).takeIf { it != this }
apache-2.0
457f7d222116c1571232fb3dd7b59e93
43.995
133
0.675408
5.742821
false
false
false
false
kpi-ua/ecampus-client-android
app/src/main/java/com/goldenpiedevs/schedule/app/ui/fragment/keeper/FragmentKeeperImplementation.kt
1
2243
package com.goldenpiedevs.schedule.app.ui.fragment.keeper import android.os.Bundle import com.goldenpiedevs.schedule.app.R import com.goldenpiedevs.schedule.app.core.dao.note.DaoNotePhoto import com.goldenpiedevs.schedule.app.core.dao.timetable.DaoTeacherModel import com.goldenpiedevs.schedule.app.ui.base.BasePresenterImpl import com.goldenpiedevs.schedule.app.ui.lesson.note.photo.PhotoPreviewFragment import com.goldenpiedevs.schedule.app.ui.timetable.TimeTableFragment class FragmentKeeperImplementation : BasePresenterImpl<FragmentKeeperView>(), FragmentKeeperPresenter { lateinit var supportFragmentManager: androidx.fragment.app.FragmentManager override fun setFragmentManager(fragmentManager: androidx.fragment.app.FragmentManager) { supportFragmentManager = fragmentManager } override fun showFragmentForBundle(bundle: Bundle?, savedInstanceState: Bundle?) { bundle?.let { when { it.containsKey(TimeTableFragment.TEACHER_ID) -> { view.setTitle(DaoTeacherModel.getTeacher(it.getInt(TimeTableFragment.TEACHER_ID))!!.teacherName) if (savedInstanceState == null) showTeacherTimeTableFragment(it.getInt(TimeTableFragment.TEACHER_ID)) } it.containsKey(PhotoPreviewFragment.PHOTO_DATA) -> { view.setTitle(it.getParcelable<DaoNotePhoto>(PhotoPreviewFragment.PHOTO_DATA)!!.name) if (savedInstanceState == null) showPhotoPreviewFragment(it.getParcelable(PhotoPreviewFragment.PHOTO_DATA)!!) view.makeFullScreen() } } } } private fun showTeacherTimeTableFragment(id: Int) { supportFragmentManager.beginTransaction() .replace(R.id.container, TimeTableFragment.getInstance(id)) .addToBackStack(null) .commit() } private fun showPhotoPreviewFragment(daoNotePhoto: DaoNotePhoto) { supportFragmentManager.beginTransaction() .replace(R.id.container, PhotoPreviewFragment.getInstance(daoNotePhoto)) .addToBackStack(null) .commit() } }
apache-2.0
f742c9b4d48cf445fda139e5a56fde3f
41.339623
116
0.68346
5.017897
false
false
false
false
smmribeiro/intellij-community
platform/platform-util-io/src/com/intellij/execution/process/LocalPtyOptions.kt
9
3089
// 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.execution.process import com.intellij.openapi.util.registry.Registry class LocalPtyOptions private constructor(val consoleMode: Boolean, val useCygwinLaunch: Boolean, val initialColumns: Int, val initialRows: Int, val useWinConPty: Boolean) { override fun toString(): String { return "consoleMode=$consoleMode, useCygwinLaunch=$useCygwinLaunch, initialColumns=$initialColumns, initialRows=$initialRows, useWinConPty=$useWinConPty" } fun builder(): Builder { return Builder(consoleMode, useCygwinLaunch, initialColumns, initialRows, useWinConPty) } companion object { @JvmField val DEFAULT = LocalPtyOptions(false, false, -1, -1, false) @JvmStatic fun shouldUseWinConPty() : Boolean = Registry.`is`("terminal.use.conpty.on.windows", false) } class Builder internal constructor(private var consoleMode: Boolean, private var useCygwinLaunch: Boolean, private var initialColumns: Int, private var initialRows: Int, private var useWinConPty: Boolean) { /** * @param consoleMode `true` means that started process output will be shown using `ConsoleViewImpl`: * 1. TTY echo is disabled (like `stty -echo`) to use manual input text buffer provided by `ConsoleViewImpl`. * 2. Separate process `stderr` will be available. For example, `stderr` and `stdout` are merged in a terminal. * * `false` means that started process output will be shown using `TerminalExecutionConsole` that is based on a terminal emulator. */ fun consoleMode(consoleMode: Boolean) = apply { this.consoleMode = consoleMode } fun consoleMode() = consoleMode fun useCygwinLaunch(useCygwinLaunch: Boolean) = apply { this.useCygwinLaunch = useCygwinLaunch } fun useCygwinLaunch() = useCygwinLaunch fun initialColumns(initialColumns: Int) = apply { this.initialColumns = initialColumns } fun initialColumns() = initialColumns fun initialRows(initialRows: Int) = apply { this.initialRows = initialRows } fun initialRows() = initialRows fun useWinConPty(useWinConPty: Boolean) = apply { this.useWinConPty = useWinConPty } fun useWinConPty() = useWinConPty fun build() = LocalPtyOptions(consoleMode, useCygwinLaunch, initialColumns, initialRows, useWinConPty) fun set(options: LocalPtyOptions) = apply { consoleMode = options.consoleMode useCygwinLaunch = options.useCygwinLaunch initialColumns = options.initialColumns initialRows = options.initialRows useWinConPty = options.useWinConPty } override fun toString(): String { return build().toString() } } }
apache-2.0
cbfbc4da91c235a052e77e454571931e
45.818182
158
0.666559
4.266575
false
false
false
false
insogroup/utils
src/main/kotlin/com/github/insanusmokrassar/utils/IOC/strategies/ProtectedCallingIOCStrategy.kt
1
3920
package com.github.insanusmokrassar.utils.IOC.strategies import com.github.insanusmokrassar.iobjectk.interfaces.IObject import com.github.insanusmokrassar.iobjectk.interfaces.has import com.github.insanusmokrassar.utils.ClassExtractor.exceptions.ClassExtractException import com.github.insanusmokrassar.utils.ClassExtractor.extract import com.github.insanusmokrassar.utils.ClassExtractor.getClass import com.github.insanusmokrassar.utils.IOC.IOC import com.github.insanusmokrassar.utils.IOC.exceptions.ResolveStrategyException import com.github.insanusmokrassar.utils.IOC.interfaces.IOCStrategy import java.util.ArrayList class ProtectedCallingIOCStrategy : IOCStrategy { protected var e: Throwable? = null protected var targetIOCStrategy: IOCStrategy? = null protected var requiredAnnotations: MutableList<String>? = null /** * @param params * Await: * <pre> * { * "targetStrategy" : "package.for.target.strategy", * "targetStrategyParams" : SOME PARAMS OBJECT AS OBJECT, STRING, ARRAY AND OTHER,//not required * "requiredAnnotations" : [ * "Annotation1", * "Annotation2" * ... * ] * } * </pre> */ @Throws(ClassExtractException::class) constructor(params: IObject<Any>) { var strategyParams: Any = arrayOfNulls<Any>(0) val targetIOCStrategyClassPath = params.get<String>(TARGET_IOC_STRATEGY_FIELD) if (params.has(TARGET_IOC_STRATEGY_PARAMS_FIELD)) { strategyParams = params.get(TARGET_IOC_STRATEGY_PARAMS_FIELD) } targetIOCStrategy = extract<IOCStrategy>(targetIOCStrategyClassPath, strategyParams) val requiredAnnotationsInJSON = params.get<List<Any>>(REQUIRED_ANNOTATIONS_FIELD) requiredAnnotations = ArrayList<String>() for (currentObject in requiredAnnotationsInJSON) { requiredAnnotations!!.add(currentObject.toString()) } } /** * Called class, which call IOC.resolve must have required annotations * @param args Args for using in target strategy * * * @return instance which will getted from target strategy * * * @throws ResolveStrategyException */ @Throws(ResolveStrategyException::class) override fun <T> getInstance(vararg args: Any): T { val iocClass = IOC::class.java.canonicalName val stackTraceElements = Thread.currentThread().stackTrace var targetClassName: String? = null try { for (i in stackTraceElements.indices) { if (stackTraceElements[i].className == iocClass) { targetClassName = stackTraceElements[i + 1].className break } } val targetClass = getClass<Any>(targetClassName!!) val tempReqAnnotations = ArrayList(requiredAnnotations!!) targetClass.annotations.forEach { if (tempReqAnnotations.contains(it.toString())) { tempReqAnnotations.remove(it.toString()) } } if (tempReqAnnotations.isEmpty()) { return targetIOCStrategy!!.getInstance(*args) } throw ResolveStrategyException("Target class haven't required rules: $tempReqAnnotations") } catch (e: ClassExtractException) { throw ResolveStrategyException("Can't get class of called object: $targetClassName", e) } catch (e: IndexOutOfBoundsException) { throw ResolveStrategyException("Can't get StackTraceElement of called class: $stackTraceElements", e) } } companion object { val TARGET_IOC_STRATEGY_FIELD = "targetStrategy" val TARGET_IOC_STRATEGY_PARAMS_FIELD = "targetStrategyParams" val REQUIRED_ANNOTATIONS_FIELD = "requiredAnnotations" } }
mit
cf46012e17fe16ddb103c957772e9b1d
39.412371
113
0.658418
4.672229
false
false
false
false
fkorotkov/k8s-kotlin-dsl
DSLs/kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/kubernetes/authorization/v1/ClassBuilders.kt
1
3974
// GENERATE package com.fkorotkov.kubernetes.authorization.v1 import io.fabric8.kubernetes.api.model.authorization.v1.LocalSubjectAccessReview as v1_LocalSubjectAccessReview import io.fabric8.kubernetes.api.model.authorization.v1.NonResourceAttributes as v1_NonResourceAttributes import io.fabric8.kubernetes.api.model.authorization.v1.NonResourceRule as v1_NonResourceRule import io.fabric8.kubernetes.api.model.authorization.v1.ResourceAttributes as v1_ResourceAttributes import io.fabric8.kubernetes.api.model.authorization.v1.ResourceRule as v1_ResourceRule import io.fabric8.kubernetes.api.model.authorization.v1.SelfSubjectAccessReview as v1_SelfSubjectAccessReview import io.fabric8.kubernetes.api.model.authorization.v1.SelfSubjectAccessReviewSpec as v1_SelfSubjectAccessReviewSpec import io.fabric8.kubernetes.api.model.authorization.v1.SelfSubjectRulesReview as v1_SelfSubjectRulesReview import io.fabric8.kubernetes.api.model.authorization.v1.SelfSubjectRulesReviewSpec as v1_SelfSubjectRulesReviewSpec import io.fabric8.kubernetes.api.model.authorization.v1.SubjectAccessReview as v1_SubjectAccessReview import io.fabric8.kubernetes.api.model.authorization.v1.SubjectAccessReviewSpec as v1_SubjectAccessReviewSpec import io.fabric8.kubernetes.api.model.authorization.v1.SubjectAccessReviewStatus as v1_SubjectAccessReviewStatus import io.fabric8.kubernetes.api.model.authorization.v1.SubjectRulesReviewStatus as v1_SubjectRulesReviewStatus fun newLocalSubjectAccessReview(block : v1_LocalSubjectAccessReview.() -> Unit = {}): v1_LocalSubjectAccessReview { val instance = v1_LocalSubjectAccessReview() instance.block() return instance } fun newNonResourceAttributes(block : v1_NonResourceAttributes.() -> Unit = {}): v1_NonResourceAttributes { val instance = v1_NonResourceAttributes() instance.block() return instance } fun newNonResourceRule(block : v1_NonResourceRule.() -> Unit = {}): v1_NonResourceRule { val instance = v1_NonResourceRule() instance.block() return instance } fun newResourceAttributes(block : v1_ResourceAttributes.() -> Unit = {}): v1_ResourceAttributes { val instance = v1_ResourceAttributes() instance.block() return instance } fun newResourceRule(block : v1_ResourceRule.() -> Unit = {}): v1_ResourceRule { val instance = v1_ResourceRule() instance.block() return instance } fun newSelfSubjectAccessReview(block : v1_SelfSubjectAccessReview.() -> Unit = {}): v1_SelfSubjectAccessReview { val instance = v1_SelfSubjectAccessReview() instance.block() return instance } fun newSelfSubjectAccessReviewSpec(block : v1_SelfSubjectAccessReviewSpec.() -> Unit = {}): v1_SelfSubjectAccessReviewSpec { val instance = v1_SelfSubjectAccessReviewSpec() instance.block() return instance } fun newSelfSubjectRulesReview(block : v1_SelfSubjectRulesReview.() -> Unit = {}): v1_SelfSubjectRulesReview { val instance = v1_SelfSubjectRulesReview() instance.block() return instance } fun newSelfSubjectRulesReviewSpec(block : v1_SelfSubjectRulesReviewSpec.() -> Unit = {}): v1_SelfSubjectRulesReviewSpec { val instance = v1_SelfSubjectRulesReviewSpec() instance.block() return instance } fun newSubjectAccessReview(block : v1_SubjectAccessReview.() -> Unit = {}): v1_SubjectAccessReview { val instance = v1_SubjectAccessReview() instance.block() return instance } fun newSubjectAccessReviewSpec(block : v1_SubjectAccessReviewSpec.() -> Unit = {}): v1_SubjectAccessReviewSpec { val instance = v1_SubjectAccessReviewSpec() instance.block() return instance } fun newSubjectAccessReviewStatus(block : v1_SubjectAccessReviewStatus.() -> Unit = {}): v1_SubjectAccessReviewStatus { val instance = v1_SubjectAccessReviewStatus() instance.block() return instance } fun newSubjectRulesReviewStatus(block : v1_SubjectRulesReviewStatus.() -> Unit = {}): v1_SubjectRulesReviewStatus { val instance = v1_SubjectRulesReviewStatus() instance.block() return instance }
mit
3b677fe3da030a75dadb2349c75017e9
35.796296
124
0.797433
4.105372
false
false
false
false
alilotfi/VirusTotalClient
app/src/main/kotlin/ir/alilo/virustotalclient/features/settings/SettingsAdapter.kt
1
1261
package ir.alilo.virustotalclient.features.settings import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import ir.alilo.virustotalclient.R import ir.alilo.virustotalclient.ui.click class SettingsAdapter(val settings: List<SettingItem>) : RecyclerView.Adapter<SettingsAdapter.BasicViewHolder>() { override fun getItemCount() = settings.size override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BasicViewHolder { val inflater = LayoutInflater.from(parent.context) val view = inflater.inflate(R.layout.item_setting, parent, false) return BasicViewHolder(view) } override fun onBindViewHolder(holder: BasicViewHolder?, position: Int) { holder?.bind(settings[position]) } inner class BasicViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val title: TextView by lazy { itemView.findViewById(R.id.item_setting_title) as TextView } fun bind(item: SettingItem) { val ctx = itemView.context title.text = ctx.getString(item.getTitleId()) itemView.click { settings[adapterPosition](ctx) } } } }
apache-2.0
ec5564cce28e3413c852dec446a0de67
37.212121
98
0.725615
4.424561
false
false
false
false
alexstyl/Memento-Namedays
android_mobile/src/main/java/com/alexstyl/specialdates/dailyreminder/NotificationConstants.kt
3
640
package com.alexstyl.specialdates.dailyreminder import com.alexstyl.specialdates.BuildConfig object NotificationConstants { const val CHANNEL_ID_CONTACTS = BuildConfig.APPLICATION_ID + ".channel.contacts" const val CHANNEL_ID_NAMEDAYS = BuildConfig.APPLICATION_ID + ".channel.namedays" const val CHANNEL_ID_BANKHOLIDAY = BuildConfig.APPLICATION_ID + ".channel.bankholiday" const val NOTIFICATION_ID_CONTACTS_SUMMARY: Int = 4001 const val NOTIFICATION_ID_NAMEDAYS = 4002 const val NOTIFICATION_ID_BANK_HOLIDAY = 4003 const val DAILY_REMINDER_GROUP_ID = BuildConfig.APPLICATION_ID + ".group.daily_reminder" }
mit
ae3a271aa382d5a89b29eee69ecba0bc
39
92
0.770313
3.975155
false
true
false
false
batagliao/onebible.android
app/src/main/java/com/claraboia/bibleandroid/views/BooksSelectDisplay.kt
1
3994
package com.claraboia.bibleandroid.views import android.content.Context import android.os.Parcel import android.os.Parcelable import android.support.v4.view.LayoutInflaterCompat import android.util.AttributeSet import android.view.LayoutInflater import android.view.View import android.widget.RelativeLayout import com.claraboia.bibleandroid.R import com.claraboia.bibleandroid.bibleApplication import com.claraboia.bibleandroid.helpers.CheatSheet import com.claraboia.bibleandroid.infrastructure.Event import com.claraboia.bibleandroid.infrastructure.EventArg import kotlinx.android.synthetic.main.layout_books_selectdisplay.view.* /** * Created by lucasbatagliao on 12/10/16. */ class BooksSelectDisplay : RelativeLayout, View.OnClickListener { enum class BookLayoutDisplayType{ GRID, LIST } class ChangeDisplayTypeEventArgs(val displayType : BookLayoutDisplayType) : EventArg(){ } val onChangeDisplayType : Event<ChangeDisplayTypeEventArgs> = Event() var currentDisplayType : BookLayoutDisplayType = BookLayoutDisplayType.GRID constructor(context: Context?) : super(context) { initLayout(context) } constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) { initLayout(context) } constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { initLayout(context) } constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) { initLayout(context) } fun initLayout(context: Context?) { val inflater = context?.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater inflater.inflate(R.layout.layout_books_selectdisplay, this) } override fun onFinishInflate() { super.onFinishInflate() //setup views CheatSheet.setup(btnViewAsGrid) CheatSheet.setup(btnViewAsList) btnViewAsGrid.setOnClickListener(this) btnViewAsList.setOnClickListener(this) currentDisplayType = context.bibleApplication.preferences.bookSelectionDisplayType setButtons() } private fun setButtons(){ if(currentDisplayType == BookLayoutDisplayType.GRID){ btnViewAsGrid.isSelected = true btnViewAsList.isSelected = false }else{ btnViewAsGrid.isSelected = false btnViewAsList.isSelected = true } } override fun onSaveInstanceState(): Parcelable { val parc = super.onSaveInstanceState() val ss = SavedState(parc) ss.displayType = currentDisplayType return ss } override fun onRestoreInstanceState(parc: Parcelable?) { val state = parc as SavedState super.onRestoreInstanceState(state) currentDisplayType = state.displayType setButtons() } override fun onClick(v: View?) { when(v?.id){ R.id.btnViewAsGrid -> { if(!btnViewAsGrid.isSelected) { currentDisplayType = BookLayoutDisplayType.GRID onChangeDisplayType.invoke(ChangeDisplayTypeEventArgs(currentDisplayType)) } } R.id.btnViewAsList -> { if(!btnViewAsList.isSelected) { currentDisplayType = BookLayoutDisplayType.LIST onChangeDisplayType.invoke(ChangeDisplayTypeEventArgs(currentDisplayType)) } } } context.bibleApplication.preferences.bookSelectionDisplayType = currentDisplayType setButtons() } private class SavedState(source: Parcelable) : BaseSavedState(source) { var displayType = BookLayoutDisplayType.GRID override fun writeToParcel(out: Parcel?, flags: Int) { super.writeToParcel(out, flags) out?.writeString(displayType.name) } } }
apache-2.0
79030bfd4feed885e65a810443ae4284
31.217742
146
0.684276
4.955335
false
false
false
false
flicus/vertx-telegram-bot-api
kotlin/src/main/kotlin/kt/schors/vertx/telegram/bot/api/types/MessageEntity.kt
1
523
package kt.schors.vertx.telegram.bot.api.types import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.annotation.JsonProperty data class MessageEntity @JsonCreator constructor( @JsonProperty("type") var type: String? = null, @JsonProperty("offset") var offset: Int? = null, @JsonProperty("length") var length: Int? = null, @JsonProperty("url") var url: String? = null, @JsonProperty("user") var user: User? = null )
mit
73aa887827385ce4eb0ebe05d7d16329
28.111111
52
0.648184
4.184
false
false
false
false
agrawalsuneet/FourFoldLoader
app/src/main/java/com/agrawalsuneet/fourfold/MainActivity.kt
1
2011
package com.agrawalsuneet.fourfold import android.os.Bundle import android.support.v4.content.ContextCompat import android.support.v7.app.AppCompatActivity import android.widget.Button import android.widget.LinearLayout import com.agrawalsuneet.fourfoldloader.loaders.FourFoldLoader class MainActivity : AppCompatActivity() { private lateinit var button: Button private lateinit var fourFoldLoaderXML: FourFoldLoader private lateinit var fourfoldLoader: FourFoldLoader private lateinit var container: LinearLayout override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) container = findViewById(R.id.container) as LinearLayout supportActionBar!!.title = "FourFoldLoader" //initControls(); //initFourfoldLoader(); } private fun initControls() { /*button = findViewById(R.id.button) as Button button.setOnClickListener { if (fourFoldLoaderXML.isLoading) { fourFoldLoaderXML.stopLoading() } else { fourFoldLoaderXML.startLoading() } if (fourfoldLoader.isLoading) { fourfoldLoader.stopLoading() } else { fourfoldLoader.startLoading() } }*/ } private fun initFourfoldLoader() { fourFoldLoaderXML = findViewById(R.id.main_fourfoldloader) as FourFoldLoader fourfoldLoader = FourFoldLoader(this, 200, ContextCompat.getColor(baseContext, R.color.green), ContextCompat.getColor(baseContext, R.color.red), ContextCompat.getColor(baseContext, R.color.blue), ContextCompat.getColor(baseContext, R.color.colorAccent), true) .apply { animationDuration = 200 disappearAnimationDuration = 100 } container.addView(fourfoldLoader) } }
apache-2.0
7fee580f1d5afc17c4864bf4d05bd23f
29.938462
84
0.650423
5.065491
false
false
false
false
techdev-solutions/janitor
pocket-api/src/test/kotlin/de/techdev/pocket/api/PocketTest.kt
1
3736
package de.techdev.pocket.api import de.techdev.pocket.Components import de.techdev.pocket.ModifyTemplate import de.techdev.pocket.RetrieveTemplate import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.MockWebServer import org.junit.Rule import org.junit.Test import org.junit.rules.ExternalResource import org.mockito.Mockito.`when` import org.mockito.Mockito.mock import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertNull class PocketTest { var server = MockWebServer() @Rule @JvmField val resource = object : ExternalResource() { override fun before() = server.start() override fun after() = server.shutdown() } @Test fun `given a bad request, PocketException is thrown`() { server.enqueue(error(400, "Missing API Key")) assertFailsWith<PocketException> { pocket().retrieveOperations().items() } } @Test fun `given a valid request, item is retrieved`() { server.enqueue(item()) val items = pocket().retrieveOperations().items() assertFalse(items.isEmpty()) assertEquals("A Test Title", items.first().title) } @Test fun `given an item without title, no exception is thrown`() { server.enqueue(itemWithoutTitle()) val items = pocket().retrieveOperations().items() assertFalse(items.isEmpty()) assertNull(items.first().title) } @Test fun `given an item without title, url is used as label`() { server.enqueue(itemWithoutTitle()) val items = pocket().retrieveOperations().items() assertEquals("https://techdev.de", items.first().label()) } private fun pocket(): Pocket { val pocket = mock(Pocket::class.java) val transport = Components.transport("consumer", "access") `when`(pocket.modifyOperations()).thenReturn(ModifyTemplate(transport, server.url("/v3/send").toString())) `when`(pocket.retrieveOperations()).thenReturn(RetrieveTemplate(transport, server.url("/v3/get").toString())) return pocket } private fun error(code: Int, message: String): MockResponse { val response = MockResponse() response.setResponseCode(code) response.setHeader("X-Error", message) return response } private fun item(): MockResponse { val response = MockResponse() response.setResponseCode(200) response.setHeader("Content-Type", "application/json") response.setBody( """ { "status" : 1, "list" : { "229279689" : { "item_id" : "229279689", "resolved_title" : "A Test Title", "time_added" : "1471869712", "given_url" : "https://techdev.de" } } } """ ) return response } private fun itemWithoutTitle(): MockResponse { val response = MockResponse() response.setResponseCode(200) response.setHeader("Content-Type", "application/json") response.setBody( """ { "status" : 1, "list" : { "229279689" : { "item_id" : "229279689", "time_added" : "1471869712", "given_url" : "https://techdev.de" } } } """ ) return response } }
apache-2.0
91505651eb90322b530d3c56474730eb
28.417323
117
0.558619
4.795892
false
true
false
false
RocketChat/Rocket.Chat.Android
app/src/main/java/chat/rocket/android/authentication/onboarding/ui/OnBoardingFragment.kt
2
3347
package chat.rocket.android.authentication.onboarding.ui import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.view.isVisible import androidx.fragment.app.Fragment import chat.rocket.android.R import chat.rocket.android.analytics.AnalyticsManager import chat.rocket.android.analytics.event.ScreenViewEvent import chat.rocket.android.authentication.onboarding.presentation.OnBoardingPresenter import chat.rocket.android.authentication.onboarding.presentation.OnBoardingView import chat.rocket.android.authentication.ui.AuthenticationActivity import chat.rocket.android.util.extensions.inflate import chat.rocket.android.util.extensions.setLightStatusBar import chat.rocket.android.util.extensions.showToast import chat.rocket.android.util.extensions.ui import dagger.android.support.AndroidSupportInjection import kotlinx.android.synthetic.main.app_bar.* import kotlinx.android.synthetic.main.fragment_authentication_on_boarding.* import javax.inject.Inject fun newInstance() = OnBoardingFragment() class OnBoardingFragment : Fragment(), OnBoardingView { @Inject lateinit var presenter: OnBoardingPresenter @Inject lateinit var analyticsManager: AnalyticsManager override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) AndroidSupportInjection.inject(this) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? = container?.inflate(R.layout.fragment_authentication_on_boarding) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupToolbar() setupOnClickListener() analyticsManager.logScreenView(ScreenViewEvent.OnBoarding) } private fun setupToolbar() { with(activity as AuthenticationActivity) { view?.let { this.setLightStatusBar(it) } toolbar.isVisible = false } } private fun setupOnClickListener() { connect_with_a_server_container.setOnClickListener { signInToYourServer() } join_community_container.setOnClickListener { joinInTheCommunity() } create_server_container.setOnClickListener { createANewServer() } } override fun showLoading() { ui { view_loading.isVisible = true } } override fun hideLoading() { ui { view_loading.isVisible = false } } override fun showMessage(resId: Int) { ui { showToast(resId) } } override fun showMessage(message: String) { ui { showToast(message) } } override fun showGenericErrorMessage() = showMessage(getString(R.string.msg_generic_error)) private fun signInToYourServer() = ui { presenter.toSignInToYourServer() } private fun joinInTheCommunity() = ui { presenter.connectToCommunityServer( getString(R.string.default_protocol) + getString(R.string.community_server_url) ) } private fun createANewServer() = ui { presenter.toCreateANewServer( getString(R.string.default_protocol) + getString(R.string.create_server_url) ) } }
mit
868e9020a09385bff685e4d09bbe9f13
31.495146
95
0.718554
4.781429
false
false
false
false
virvar/magnetic-ball-2
MagneticBallLogic/src/main/kotlin/ru/virvar/apps/magneticBall2/blocks/PointBlock.kt
1
946
package ru.virvar.apps.magneticBall2.blocks import ru.virvar.apps.magneticBallCore.Block import ru.virvar.apps.magneticBallCore.Level import ru.virvar.apps.magneticBallCore.Point2D class PointBlock(scoreBonus: Int = 1) : ActiveBlock() { private var scoreBonus = 1 init { this.scoreBonus = scoreBonus } override fun blockEnter(level: Level, block: Block, direction: Point2D): Point2D { level.moveHelper.move(level, block, direction, location) level.removeBlock(this) level.score += scoreBonus return direction } override fun clone(): Block { val block = PointBlock() block.initFrom(this) return block } override fun initFrom(original: Block) { super.initFrom(original) if (original !is PointBlock) { throw TypeCastException("Original must be PointBlock") } scoreBonus = original.scoreBonus } }
gpl-2.0
2002843eec4bce35d5932626a1815009
26.764706
86
0.664195
4.122271
false
false
false
false
whym/apps-android-commons
app/src/test/kotlin/fr/free/nrw/commons/LatLngTests.kt
9
1673
package fr.free.nrw.commons import fr.free.nrw.commons.location.LatLng import org.junit.Assert.assertEquals import org.junit.Test class LatLngTests { @Test fun testZeroZero() { val place = LatLng(0.0, 0.0, 0f) assertPrettyCoordinateString("0.0 N, 0.0 E", place) } @Test fun testAntipode() { val place = LatLng(0.0, 180.0, 0f) assertPrettyCoordinateString("0.0 N, 180.0 W", place) } @Test fun testNorthPole() { val place = LatLng(90.0, 0.0, 0f) assertPrettyCoordinateString("90.0 N, 0.0 E", place) } @Test fun testSouthPole() { val place = LatLng(-90.0, 0.0, 0f) assertPrettyCoordinateString("90.0 S, 0.0 E", place) } @Test fun testLargerNumbers() { val place = LatLng(120.0, 380.0, 0f) assertPrettyCoordinateString("90.0 N, 20.0 E", place) } @Test fun testNegativeNumbers() { val place = LatLng(-120.0, -30.0, 0f) assertPrettyCoordinateString("90.0 S, 30.0 W", place) } @Test fun testTooBigWestValue() { val place = LatLng(20.0, -190.0, 0f) assertPrettyCoordinateString("20.0 N, 170.0 E", place) } @Test fun testRounding() { val place = LatLng(0.1234567, -0.33333333, 0f) assertPrettyCoordinateString("0.1235 N, 0.3333 W", place) } @Test fun testRoundingAgain() { val place = LatLng(-0.000001, -0.999999, 0f) assertPrettyCoordinateString("0.0 S, 1.0 W", place) } private fun assertPrettyCoordinateString(expected: String, place: LatLng) = assertEquals(expected, place.prettyCoordinateString) }
apache-2.0
487340e07ecc233fadc227f939f752f8
25.140625
79
0.60789
3.38664
false
true
false
false
Assassinss/Jandan-Kotlin
app/src/main/java/me/zsj/dan/ui/adapter/PictureAdapter.kt
1
8695
package me.zsj.dan.ui.adapter import android.app.Activity import android.support.v7.widget.CardView import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import android.widget.ImageView import android.widget.ProgressBar import android.widget.TextView import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView import kotterknife.bindView import me.zsj.dan.R import me.zsj.dan.binder.Holder import me.zsj.dan.data.DataManager import me.zsj.dan.data.Downloader import me.zsj.dan.model.Comment import me.zsj.dan.ui.adapter.common.LoadingHolder import me.zsj.dan.ui.adapter.common.OnErrorListener import me.zsj.dan.ui.adapter.common.OnLoadDataListener import me.zsj.dan.visibility.items.ListItem import me.zsj.dan.visibility.scroll_utils.ItemsProvider import me.zsj.dan.widget.GifRatioScaleImageView import me.zsj.dan.widget.RatioScaleImageView import pl.droidsonroids.gif.GifDrawable /** * @author zsj */ class PictureAdapter(var context: Activity, var comments: ArrayList<Comment>, var dataManager: DataManager) : RecyclerView.Adapter<RecyclerView.ViewHolder>(), ItemsProvider, ItemBinder.OnVoteListener, OnErrorListener { private val GIF_TAG = ".gif" private var recyclerView: RecyclerView? = null private var singleItemBinder: SingleItemBinder? = null private var gifItemBinder: GifItemBinder? = null private var multiItemBinder: MultiItemBinder? = null private var error: Boolean = false private var onLoadDataListener: OnLoadDataListener? = null fun setOnLoadDataListener(onLoadDataListener: OnLoadDataListener) { this.onLoadDataListener = onLoadDataListener } init { singleItemBinder = SingleItemBinder(dataManager) singleItemBinder?.setOnVoteListener(this) gifItemBinder = GifItemBinder(dataManager) gifItemBinder?.setOnVoteListener(this) multiItemBinder = MultiItemBinder(dataManager) multiItemBinder?.setOnVoteListener(this) } override fun onVoteOO(holder: Holder, result: String?) { when (holder) { is SingleHolder -> singleItemBinder?.updateVotePositive(context, holder, result) is GifHolder -> gifItemBinder?.updateVotePositive(context, holder, result) is MultiHolder -> multiItemBinder?.updateVotePositive(context, holder, result) } } override fun onVoteXX(holder: Holder, result: String?) { when (holder) { is SingleHolder -> singleItemBinder?.updateVoteNegative(context, holder, result) is GifHolder -> gifItemBinder?.updateVoteNegative(context, holder, result) is MultiHolder -> multiItemBinder?.updateVoteNegative(context, holder, result) } } override fun getListItem(position: Int): ListItem? { val holder = recyclerView?.findViewHolderForAdapterPosition(position) if (holder is ListItem) { return holder } return null } override fun listItemSize(): Int { return itemCount } fun setRecyclerView(recyclerView: RecyclerView) { this.recyclerView = recyclerView } override fun onLoadingError(error: Boolean) { this.error = error notifyItemChanged(comments.size) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { val inflater = LayoutInflater.from(context) when (viewType) { R.layout.item_load_more -> { val view = inflater.inflate(R.layout.item_load_more, parent, false) return LoadingHolder(view) } R.layout.item_single_pic -> { val view = inflater.inflate(R.layout.item_single_pic, parent, false) return SingleHolder(view) } R.layout.item_gif_pic -> { val view = inflater.inflate(R.layout.item_gif_pic, parent, false) return GifHolder(view) } R.layout.item_multi_pic -> { val view = inflater.inflate(R.layout.item_multi_pic, parent, false) return MultiHolder(view) } else -> throw IllegalArgumentException() } } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { when { getItemViewType(position) == R.layout.item_load_more -> { holder as LoadingHolder holder.showLoading(holder, itemCount, error) holder.loadingContainer.setOnClickListener { holder.progressBar.visibility = View.VISIBLE holder.errorText.visibility = View.GONE onLoadDataListener?.onLoadMoreData() } } getItemViewType(position) == R.layout.item_single_pic -> { val comment = comments[position] holder as SingleHolder singleItemBinder?.bindData(context, holder, comment) } getItemViewType(position) == R.layout.item_gif_pic -> { val comment = comments[position] holder as GifHolder gifItemBinder?.bindData(context, holder, comment) } else -> { val comment = comments[position] holder as MultiHolder multiItemBinder?.bindData(context, holder, comment) } } } override fun getItemCount(): Int { var itemCount = 1 if (comments.size > 0) { itemCount += comments.size } return itemCount } override fun getItemViewType(position: Int): Int { return if (position + 1 == itemCount) { R.layout.item_load_more } else { val comment = comments[position] if (comment.pics?.size == 1) { if (comment.pics[0].endsWith(GIF_TAG)) { R.layout.item_gif_pic } else { R.layout.item_single_pic } } else { R.layout.item_multi_pic } } } inner class SingleHolder(itemView: View) : Holder(itemView) { val card: CardView by bindView(R.id.card) val textContent: TextView by bindView(R.id.text_content) val picture: RatioScaleImageView by bindView(R.id.picture) val browsePicture: TextView by bindView(R.id.browse_big_picture) val scaleImageView: SubsamplingScaleImageView by bindView(R.id.scale_image_view) } inner class GifHolder(itemView: View) : Holder(itemView), ListItem { val card: CardView by bindView(R.id.card) val gifImage: GifRatioScaleImageView by bindView(R.id.gif_picture) val playGif: ImageView by bindView(R.id.play_gif) val loadingProgress: ProgressBar by bindView(R.id.loading_progress) val textContent: TextView by bindView(R.id.text_content) val picContent: FrameLayout by bindView(R.id.pic_content) override fun setActive(newActiveView: View?, newActiveViewPosition: Int) { } override fun deactivate(currentView: View?, position: Int) { Downloader.get().stopDownload(comments[position].pics[0]) val gifImageView = currentView?.findViewById<GifRatioScaleImageView>(R.id.gif_picture) val playGif = currentView?.findViewById<ImageView>(R.id.play_gif) val loadingProgress = currentView?.findViewById<ProgressBar>(R.id.loading_progress) playGif?.visibility = View.VISIBLE loadingProgress?.visibility = View.GONE if (gifImageView != null && playGif != null && loadingProgress != null) { val gifDrawable = gifImageView.drawable if (gifDrawable is GifDrawable) { gifItemBinder?.stopGifAnimation(gifImageView.drawable as GifDrawable) } } } } inner class MultiHolder(itemView: View) : Holder(itemView) { val card: CardView by bindView(R.id.card) val textContent: TextView by bindView(R.id.text_content) val recyclerView: RecyclerView by bindView(R.id.pic_item_list) private var pictureAdapter: ItemPictureAdapter? = null init { pictureAdapter = ItemPictureAdapter() recyclerView.adapter = pictureAdapter } fun setPictures(pics: ArrayList<String>) { pictureAdapter!!.setPics(pics) pictureAdapter?.notifyDataSetChanged() } } }
gpl-3.0
56c6a147d64aedd741d1887402c9b8d9
37.821429
98
0.640253
4.583553
false
false
false
false
tangying91/profit
src/main/java/org/profit/app/EMailSender.kt
1
2152
package org.profit.app import java.util.* import javax.mail.Authenticator import javax.mail.Message import javax.mail.PasswordAuthentication import javax.mail.Session import javax.mail.internet.InternetAddress import javax.mail.internet.MimeMessage /** * 邮件发送者 * * @author TangYing */ object EMailSender { private val props = Properties() private val auth = MyAuthenticator() init { //设置邮件服务器地址,连接超时时限等信息 props["mail.smtp.host"] = "smtp.126.com" props["mail.smtp.auth"] = "true" props["mail.smtp.connectiontimeout"] = "10000" props["mail.smtp.timeout"] = "25000" } /** * 邮件发送 * * @param receiver * @param subject * @param content */ fun send(receiver: String, subject: String, content: String) { if (receiver == "") { return } //创建缺省的session对象 val session = Session.getDefaultInstance(props, auth) //创建message对象 val msg = MimeMessage(session) //设置发件人和收件人 try { // 设置发件人 val internetAddress = InternetAddress("[email protected]") internetAddress.personal = "数据分析结果" msg.setFrom(internetAddress) // 设置收件人 val addressTo = InternetAddress(receiver) msg.setRecipient(Message.RecipientType.TO, addressTo) //设置邮件主题 msg.subject = subject msg.setText(content) // 设置传输协议 val transport = session.getTransport("smtp") transport.connect("smtp.126.com", "[email protected]", "IOGJSYLTLVIMFUDM") transport.sendMessage(msg, msg.allRecipients) transport.close() } catch (e: Exception) { e.printStackTrace() } } class MyAuthenticator: Authenticator() { override fun getPasswordAuthentication(): PasswordAuthentication { return PasswordAuthentication("xlzxbyd", "IOGJSYLTLVIMFUDM") } } }
apache-2.0
1563a37155abcdbc79a015c4c56bf2fb
24.641026
84
0.598
3.992016
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-languages-bukkit/src/main/kotlin/com/rpkit/languages/bukkit/language/RPKLanguageImpl.kt
1
3032
/* * Copyright 2021 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.languages.bukkit.language import com.rpkit.characters.bukkit.race.RPKRace import kotlin.random.Random class RPKLanguageImpl( override val name: RPKLanguageName, private val baseUnderstanding: Map<String, Float>, private val minimumUnderstandingIncrement: Map<String, Float>, private val maximumUnderstandingIncrement: Map<String, Float>, private val cypher: Map<String, String> ) : RPKLanguage { override fun getBaseUnderstanding(race: RPKRace): Float { return baseUnderstanding[race.name.value] ?: 0f } override fun getMinimumUnderstandingIncrement(race: RPKRace): Float { return minimumUnderstandingIncrement[race.name.value] ?: 0f } override fun getMaximumUnderstandingIncrement(race: RPKRace): Float { return maximumUnderstandingIncrement[race.name.value] ?: 0f } override fun randomUnderstandingIncrement(race: RPKRace): Float { val min = getMinimumUnderstandingIncrement(race) val max = getMaximumUnderstandingIncrement(race) return min + (Random.nextFloat() * (max - min)) } override fun apply(message: String, senderUnderstanding: Float, receiverUnderstanding: Float): String { return applyCypher(applyGarble(message, senderUnderstanding), receiverUnderstanding) } private fun applyGarble(message: String, understanding: Float): String { var result = "" for (char in message) { result = if (understanding >= Random.nextFloat() * 100) { result + char } else { char + result } } return result } private fun applyCypher(message: String, understanding: Float): String { var pos = 0 var result = "" msg@ while (pos < message.length) { for (cypherKey in cypher.keys) { if (pos + cypherKey.length <= message.length && message.substring(pos, pos + cypherKey.length) == cypherKey) { result += if (understanding >= Random.nextFloat() * 100) { cypherKey } else { cypher[cypherKey] } pos += cypherKey.length continue@msg } } result += message[pos] pos++ } return result } }
apache-2.0
5cec1c81280989e3b22e09a8463f019d
35.107143
107
0.625989
4.708075
false
false
false
false
arcao/Geocaching4Locus
geocaching-api/src/main/java/com/arcao/geocaching4locus/data/api/util/CoordinatesParser.kt
1
6730
/* Some parts of this file contains work from c:geo licensed under Apache License 2.0. */ package com.arcao.geocaching4locus.data.api.util import com.arcao.geocaching4locus.data.api.model.Coordinates import java.text.ParseException import java.util.regex.Pattern import kotlin.math.abs import kotlin.math.floor object CoordinatesParser { private const val MINUTES_PER_DEGREE = 60.0 private const val SECONDS_PER_DEGREE = 3600.0 private val LATITUDE_PATTERN = Pattern.compile( // ( 1 ) ( 2 ) ( 3 ) ( 4 ) ( 5 ) "\\b([NS])\\s*(\\d+)°?(?:\\s*(\\d+)(?:[.,](\\d+)|'?\\s*(\\d+(?:[.,]\\d+)?)(?:''|\")?)?)?", Pattern.CASE_INSENSITIVE ) private val LONGITUDE_PATTERN = Pattern.compile( "\\b([WE])\\s*(\\d+)°?(?:\\s*(\\d+)(?:[.,](\\d+)|'?\\s*(\\d+(?:[.,]\\d+)?)(?:''|\")?)?)?", Pattern.CASE_INSENSITIVE ) private val LATITUDE_PATTERN_UNSAFE = Pattern.compile( // ( 1 ) ( 2 ) ( 3 ) ( 4 ) ( 5 ) "(?:(?=[\\-\\w])(?<![\\-\\w])|(?<![^\\-\\w]))([NS]|)\\s*(-?\\d+)°?(?:\\s*(\\d+)(?:[.,](\\d+)|'?\\s*(\\d+(?:[.,]\\d+)?)(?:''|\")?)?)?", Pattern.CASE_INSENSITIVE ) private val LONGITUDE_PATTERN_UNSAFE = Pattern.compile( "(?:(?=[\\-\\w])(?<![\\-\\w])|(?<![^\\-\\w]))([WE]|)\\s*(-?\\d+)°?(?:\\s*(\\d+)(?:[.,](\\d+)|'?\\s*(\\d+(?:[.,]\\d+)?)(?:''|\")?)?)?", Pattern.CASE_INSENSITIVE ) private enum class CoordinateType { LAT, LON, LAT_UNSAFE, LON_UNSAFE } @Throws(ParseException::class) fun parse(latitude: String, longitude: String, safe: Boolean = true): Coordinates { return Coordinates( parseLatitude(latitude, safe), parseLongitude(longitude, safe) ) } @Throws(ParseException::class) fun parseLatitude(latitude: String, safe: Boolean = true): Double { return parse(latitude, if (safe) CoordinateType.LAT else CoordinateType.LAT_UNSAFE).result } @Throws(ParseException::class) fun parseLongitude(longitude: String, safe: Boolean = true): Double { return parse(longitude, if (safe) CoordinateType.LON else CoordinateType.LON_UNSAFE).result } @Throws(ParseException::class) fun parse(coordinates: String): Coordinates { val latitudeWrapper = parse(coordinates, CoordinateType.LAT) val lat = latitudeWrapper.result // cut away the latitude part when parsing the longitude val longitudeWrapper = parse( coordinates.substring(latitudeWrapper.matcherPos + latitudeWrapper.matcherLen), CoordinateType.LON ) if (longitudeWrapper.matcherPos - (latitudeWrapper.matcherPos + latitudeWrapper.matcherLen) >= 10) { throw ParseException( "Distance between latitude and longitude text is to large.", latitudeWrapper.matcherPos + latitudeWrapper.matcherLen + longitudeWrapper.matcherPos ) } val lon = longitudeWrapper.result return Coordinates(lat, lon) } @Throws(ParseException::class) private fun parse(coordinate: String, coordinateType: CoordinateType): ParseResult { val pattern = when (coordinateType) { CoordinateType.LAT_UNSAFE -> LATITUDE_PATTERN_UNSAFE CoordinateType.LON_UNSAFE -> LONGITUDE_PATTERN_UNSAFE CoordinateType.LON -> LONGITUDE_PATTERN CoordinateType.LAT -> LATITUDE_PATTERN } val matcher = pattern.matcher(coordinate) if (matcher.find()) { var sign = if ("S".equals(matcher.group(1), ignoreCase = true) || "W".equals( matcher.group(1), ignoreCase = true ) ) -1.0 else 1.0 var degree = matcher.group(2)?.toDouble() ?: 0.0 if (degree < 0) { sign = -1.0 degree = abs(degree) } var minutes = 0.0 var seconds = 0.0 if (matcher.group(3) != null) { minutes = matcher.group(3)?.toDouble() ?: 0.0 if (matcher.group(4) != null) { seconds = ("0." + matcher.group(4)).toDouble() * MINUTES_PER_DEGREE } else if (matcher.group(5) != null) { seconds = matcher.group(5)?.replace(",", ".")?.toDouble() ?: 0.0 } } var result = sign * (degree + minutes / MINUTES_PER_DEGREE + seconds / SECONDS_PER_DEGREE) // normalize result result = when (coordinateType) { CoordinateType.LON_UNSAFE, CoordinateType.LON -> normalize(result, -180.0, 180.0) CoordinateType.LAT_UNSAFE, CoordinateType.LAT -> normalize(result, -90.0, 90.0) } return ParseResult(result, matcher.start(), matcher.group().length) } else { // Nothing found with "N 52...", try to match string as decimaldegree try { val items = coordinate.trim { it <= ' ' }.split(Regex("\\s+")) if (items.size > 1) { val index = if (coordinateType == CoordinateType.LON) { items.size - 1 } else { 0 } val pos = if (coordinateType == CoordinateType.LON) { coordinate.lastIndexOf(items[index]) } else { coordinate.indexOf(items[index]) } return ParseResult(items[index].toDouble(), pos, items[index].length) } } catch (e: NumberFormatException) { // do nothing } } throw ParseException("Could not parse coordinate: \"$coordinate\"", 0) } /** * Normalizes any number to an arbitrary range by assuming the range wraps around when going below min or above max. * * @param value input * @param start range start * @param end range end * @return normalized number */ private fun normalize(value: Double, start: Double, end: Double): Double { val width = end - start val offsetValue = value - start // value relative to 0 return offsetValue - floor(offsetValue / width) * width + start // + start to reset back to start of original range } private class ParseResult( val result: Double, val matcherPos: Int, val matcherLen: Int ) }
gpl-3.0
44d80ea4c1d3eb3e192cdd1c96580e05
36.366667
142
0.52587
4.295019
false
false
false
false
Juuxel/ChatTime
server/src/main/kotlin/chattime/server/plugins/PluginLoader.kt
1
4986
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package chattime.server.plugins import chattime.server.saveProperties import chattime.server.ChatServer import chattime.api.event.EventType import chattime.api.event.PluginLoadEvent import chattime.api.plugin.LoadOrder import chattime.api.plugin.Plugin import chattime.server.L10n import java.net.URLClassLoader import java.nio.file.Files import java.nio.file.Paths import java.util.jar.Manifest class PluginLoader(private val server: ChatServer) { private val pluginLoadList: ArrayList<Plugin> = ArrayList() private val mPlugins: ArrayList<Plugin> = ArrayList() val plugins: List<Plugin> get() = mPlugins internal fun findPluginsFromDirectory(directory: String) { val path = Paths.get(directory) if (Files.notExists(path)) Files.createDirectory(path) val stream = Files.newDirectoryStream(path) stream.forEach { if (it.toString().endsWith(".jar")) { val classLoader = URLClassLoader(arrayOf(it.toUri().toURL()), this::class.java.classLoader) val url = classLoader.findResource("META-INF/MANIFEST.MF") val manifest = Manifest(url.openStream()) val attributes = manifest.mainAttributes val pluginClassesString = attributes.getValue("Plugin-Classes") val pluginClasses = if (pluginClassesString.contains(';')) pluginClassesString.split(';') else listOf(pluginClassesString) pluginClasses.forEach { val pluginClass = Class.forName(it, true, classLoader) addPlugin(constructPlugin(pluginClass)) } } } } fun addPlugin(plugin: Plugin) = pluginLoadList.add(plugin) fun addPlugin(className: String) = addPlugin(constructPlugin(Class.forName(className))) internal fun loadPlugins() { fun doesLoadOrderConflict(p1: Plugin, p2: Plugin): Boolean { // Before if (p1.loadOrder.any { it is LoadOrder.Before && it.id == p2.id} && p2.loadOrder.any { it is LoadOrder.Before && it.id == p1.id}) return true // After if (p1.loadOrder.any { it is LoadOrder.After && it.id == p2.id} && p2.loadOrder.any { it is LoadOrder.After && it.id == p1.id}) return true return false } val sortedLoadList = pluginLoadList.sortedWith(Comparator { p1, p2 -> if (doesLoadOrderConflict(p1, p2)) { println(L10n["plugins.loadOrderConflict", p1.id, p2.id]) pluginLoadList.removeAll(listOf(p1, p2)) } if (p1.loadOrder.any { it is LoadOrder.Before && it.id == p2.id } || p2.loadOrder.any { it is LoadOrder.After && it.id == p1.id }) return@Comparator -1 else if (p1.loadOrder.any { it is LoadOrder.After && it.id == p2.id } || p2.loadOrder.any { it is LoadOrder.Before && it.id == p1.id }) return@Comparator 1 return@Comparator 0 }) val disabledMarkings = ArrayList<Plugin>() mainPlugins@ for (plugin in sortedLoadList) { val pluginProps = server.getPluginProperties(plugin) if (!pluginProps["enabled", "true"].toBoolean()) { println(L10n["plugins.disabled", plugin.id]) disabledMarkings += plugin continue } for (requiredPlugin in plugin.loadOrder.filter { it.isRequired }) { if (!sortedLoadList.any { it.id == requiredPlugin.id } || disabledMarkings.any { it.id == requiredPlugin.id }) { println(L10n["plugins.missingDependency", requiredPlugin.id, plugin.id]) continue@mainPlugins } } mPlugins.add(plugin) server.eventBus.subscribe(EventType.pluginLoad) { if (it.plugin == plugin) plugin.load(it) } plugin.load(PluginLoadEvent(server, plugin)) // Save the initial properties after the plugins have been loaded saveProperties() } } private fun constructPlugin(pluginClass: Class<*>): Plugin { if (pluginClass.interfaces.contains(Plugin::class.java)) { return pluginClass.constructors.first { it.parameters.isEmpty() }.newInstance() as Plugin } else throw IllegalArgumentException("pluginClass does not extend Plugin!") } }
mpl-2.0
bab8844bc1461e88ac9f0c501dda03c9
33.867133
107
0.579021
4.487849
false
false
false
false
CPRTeam/CCIP-Android
app/src/main/java/app/opass/ccip/extension/View.kt
1
1699
package app.opass.ccip.extension import android.view.View import android.view.ViewGroup import android.view.WindowInsets import android.view.inputmethod.InputMethodManager import android.view.inputmethod.InputMethodManager.SHOW_FORCED import androidx.annotation.Px import androidx.core.content.getSystemService import androidx.core.view.* fun View.setOnApplyWindowInsetsListenerCompat(block: (v: View, insets: WindowInsets, insetsCompat: WindowInsetsCompat) -> WindowInsets) { setOnApplyWindowInsetsListener { v, insets -> val insetsCompat = WindowInsetsCompat.toWindowInsetsCompat(insets) block(v, insets, insetsCompat) } } data class EdgeInsets( val left: Int, val top: Int, val right: Int, val bottom: Int ) fun View.doOnApplyWindowInsets(block: (v: View, insets: WindowInsetsCompat, padding: EdgeInsets, margin: EdgeInsets) -> Unit) { val padding = EdgeInsets(this.paddingLeft, this.paddingTop, this.paddingRight, this.paddingBottom) val margin = EdgeInsets(this.marginLeft, this.marginTop, this.marginRight, this.marginBottom) setOnApplyWindowInsetsListenerCompat { v, insets, insetsCompat -> block(v, insetsCompat, padding, margin) insets } } fun View.updateMargin( @Px left: Int = marginLeft, @Px top: Int = marginTop, @Px right: Int = marginRight, @Px bottom: Int = marginBottom ) { updateLayoutParams<ViewGroup.MarginLayoutParams> { this.setMargins(left, top ,right, bottom) } } fun View.getIme() = context.getSystemService<InputMethodManager>() fun View.showIme() = getIme()?.toggleSoftInput(SHOW_FORCED, 0) fun View.hideIme() = getIme()?.hideSoftInputFromWindow(windowToken, 0)
gpl-3.0
6c74857c995fa07e4c968fb6a15989de
34.395833
137
0.747499
4.215881
false
false
false
false
android/user-interface-samples
Haptics/app/src/main/java/com/example/android/haptics/samples/ui/AppDrawer.kt
1
6389
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.haptics.samples.ui import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.material.Icon import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.material.TextButton import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.Home import androidx.compose.material.icons.rounded.OpenWith import androidx.compose.material.icons.rounded.Refresh import androidx.compose.material.icons.rounded.SportsVolleyball import androidx.compose.material.icons.rounded.Water import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.android.haptics.samples.R import com.example.android.haptics.samples.ui.theme.DrawerButtonShape import com.example.android.haptics.samples.ui.theme.HapticSamplerTheme import com.example.android.haptics.samples.ui.theme.secondaryText @Composable fun AppDrawer( currentRoute: String, navigateToHome: () -> Unit, navigateToResist: () -> Unit, navigateToExpand: () -> Unit, navigateToBounce: () -> Unit, navigateToWobble: () -> Unit, closeDrawer: () -> Unit, modifier: Modifier = Modifier ) { Column(modifier = modifier.fillMaxSize()) { Text( stringResource(R.string.app_name), modifier = modifier .padding(start = 32.dp) .padding(vertical = 16.dp), style = MaterialTheme.typography.h5 ) DrawerButton( icon = Icons.Rounded.Home, label = stringResource(R.string.home_screen_title), isSelected = currentRoute === HapticSamplerDestinations.HOME_ROUTE, onClick = { navigateToHome() closeDrawer() } ) Text( stringResource(R.string.drawer_content_example_effects), style = MaterialTheme.typography.subtitle2, modifier = modifier .padding(start = 32.dp) .padding(vertical = 16.dp) ) DrawerButton( icon = Icons.Rounded.Refresh, label = stringResource(R.string.resist_screen_title), isSelected = currentRoute === HapticSamplerDestinations.RESIST_ROUTE, onClick = { navigateToResist() closeDrawer() } ) DrawerButton( icon = Icons.Rounded.OpenWith, label = stringResource(R.string.expand_screen_title), isSelected = currentRoute === HapticSamplerDestinations.EXPAND_ROUTE, onClick = { navigateToExpand() closeDrawer() } ) DrawerButton( icon = Icons.Rounded.SportsVolleyball, label = stringResource(R.string.bounce), isSelected = currentRoute === HapticSamplerDestinations.BOUNCE_ROUTE, onClick = { navigateToBounce() closeDrawer() } ) DrawerButton( icon = Icons.Rounded.Water, label = stringResource(R.string.wobble), currentRoute === HapticSamplerDestinations.WOBBLE_ROUTE, onClick = { navigateToWobble() closeDrawer() } ) } } @Composable private fun DrawerButton( icon: ImageVector, label: String, isSelected: Boolean, onClick: () -> Unit, modifier: Modifier = Modifier ) { val backgroundColor = if (isSelected) { MaterialTheme.colors.secondary } else { Color.Transparent } Surface( color = backgroundColor, shape = DrawerButtonShape, modifier = modifier .padding(horizontal = 8.dp) .fillMaxWidth(), ) { TextButton( onClick = onClick, modifier = modifier .padding(start = 16.dp, top = 8.dp, bottom = 8.dp) .fillMaxWidth() ) { Row( horizontalArrangement = Arrangement.Start, verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth() ) { val textAndIconColor = if (isSelected) MaterialTheme.colors.onSecondary else MaterialTheme.colors.secondaryText Icon(icon, contentDescription = null, tint = textAndIconColor) Spacer(Modifier.width(16.dp)) Text( text = label, color = textAndIconColor, style = MaterialTheme.typography.subtitle2, ) } } } } @Preview(showBackground = true) @Composable fun AppDrawerPreview() { HapticSamplerTheme { AppDrawer( HapticSamplerDestinations.HOME_ROUTE, navigateToHome = {}, navigateToResist = {}, navigateToExpand = {}, navigateToBounce = {}, navigateToWobble = {}, closeDrawer = {}, ) } }
apache-2.0
d17907434c8994ec66269e7fe3aee59c
33.349462
87
0.632493
4.789355
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/website/views/subviews/api/config/types/CustomBadgePayload.kt
1
1526
package net.perfectdreams.loritta.morenitta.website.views.subviews.api.config.types import com.github.salomonbrys.kotson.bool import com.github.salomonbrys.kotson.nullString import com.google.gson.JsonObject import kotlinx.coroutines.runBlocking import net.dv8tion.jda.api.entities.Guild import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.morenitta.dao.DonationConfig import net.perfectdreams.loritta.morenitta.dao.ServerConfig import net.perfectdreams.loritta.morenitta.website.session.LorittaJsonWebSession import java.io.ByteArrayInputStream import java.io.File import java.util.* import javax.imageio.ImageIO class CustomBadgePayload(val loritta: LorittaBot) : ConfigPayloadType("badge") { override fun process(payload: JsonObject, userIdentification: LorittaJsonWebSession.UserIdentification, serverConfig: ServerConfig, guild: Guild) { runBlocking { loritta.pudding.transaction { val donationConfig = serverConfig.donationConfig ?: DonationConfig.new { this.customBadge = false } donationConfig.customBadge = payload["customBadge"].bool serverConfig.donationConfig = donationConfig } val data = payload["badgeImage"].nullString if (data != null) { val base64Image = data.split(",")[1] val imageBytes = Base64.getDecoder().decode(base64Image) val img = ImageIO.read(ByteArrayInputStream(imageBytes)) if (img != null) { ImageIO.write(img, "png", File(LorittaBot.ASSETS, "badges/custom/${guild.id}.png")) } } } } }
agpl-3.0
3cdb73294a5c5564e35741a13f572652
35.357143
148
0.779161
4.037037
false
true
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/minecraft/McUUIDExecutor.kt
1
2028
package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.minecraft import net.perfectdreams.loritta.cinnamon.emotes.Emotes import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.ApplicationCommandContext import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.CinnamonSlashCommandExecutor import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.minecraft.declarations.MinecraftCommand import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.options.LocalizedApplicationCommandOptions import net.perfectdreams.discordinteraktions.common.commands.options.SlashCommandArguments import net.perfectdreams.minecraftmojangapi.MinecraftMojangAPI class McUUIDExecutor(loritta: LorittaBot, val mojang: MinecraftMojangAPI) : CinnamonSlashCommandExecutor(loritta) { inner class Options : LocalizedApplicationCommandOptions(loritta) { val username = string("player_name", MinecraftCommand.I18N_CATEGORY_PREFIX.Options.PlayerNameJavaEdition) } override val options = Options() override suspend fun execute(context: ApplicationCommandContext, args: SlashCommandArguments) { val player = args[options.username] if (!player.matches(McSkinExecutor.VALID_NAME_REGEX)) context.failEphemerally( prefix = Emotes.Error, content = context.i18nContext.get(MinecraftCommand.I18N_CATEGORY_PREFIX.InvalidPlayerName(player)) ) val onlineUniqueId = mojang.getUniqueId(player) ?: context.failEphemerally( prefix = Emotes.Error, content = context.i18nContext.get(MinecraftCommand.I18N_CATEGORY_PREFIX.UnknownPlayer(player)) ) context.sendReply( context.i18nContext.get( MinecraftCommand.I18N_PREFIX.Player.Onlineuuid.Result( player, onlineUniqueId.toString() ) ) ) } }
agpl-3.0
d000b00271dedd8cb404660696e619e5
47.309524
115
0.748028
4.982801
false
false
false
false
luiqn2007/miaowo
app/src/main/java/org/miaowo/miaowo/activity/SendActivity.kt
1
8098
package org.miaowo.miaowo.activity import android.app.FragmentTransaction import android.arch.lifecycle.Observer import android.arch.lifecycle.ViewModelProviders import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.MenuItem import android.view.View import com.blankj.utilcode.util.KeyboardUtils import com.mikepenz.fontawesome_typeface_library.FontAwesome import com.mikepenz.materialdrawer.holder.ImageHolder import kotlinx.android.synthetic.main.activity_send.* import okhttp3.ResponseBody import org.miaowo.miaowo.API import org.miaowo.miaowo.R import org.miaowo.miaowo.data.model.MessageModel import org.miaowo.miaowo.fragment.MarkdownFragment import org.miaowo.miaowo.other.ActivityHttpCallback import org.miaowo.miaowo.other.Const import retrofit2.Call import retrofit2.Response import kotlinx.android.synthetic.main.activity_send.title as eTitle class SendActivity : AppCompatActivity() { companion object { // 新帖 ID const val TYPE_POST = 0 // 回复 ID REPLY const val TYPE_REPLY = 1 // 回复回复 ID ID2 REPLY const val TYPE_REPLY_POST = 2 } private lateinit var mMessageModel: MessageModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_send) setSupportActionBar(toolBar) mMessageModel = ViewModelProviders.of(this)[MessageModel::class.java] mMessageModel.observe(this, Observer { toolBar.menu.getItem(0)?.isEnabled = !it.isNullOrBlank() content.editText!!.setText(it) }) } override fun onPostCreate(savedInstanceState: Bundle?) { super.onPostCreate(savedInstanceState) applyIconsAndActions() val sendButton = toolBar.menu.add(0, 0, 0, R.string.send) when(intent.getIntExtra(Const.TYPE, TYPE_POST)) { TYPE_POST -> { eTitle.isCounterEnabled = true eTitle.editText!!.isEnabled = true eTitle.counterMaxLength = 50 tags.visibility = View.VISIBLE sendButton.apply { setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS) setOnMenuItemClickListener { if (KeyboardUtils.isSoftInputVisible(this@SendActivity)) KeyboardUtils.hideSoftInput(this@SendActivity) isEnabled = false API.Topics.create( intent.getIntExtra(Const.ID, -1), eTitle.editText!!.text.toString(), content.editText!!.text.toString(), tags.editText!!.text.toString().split(";")).enqueue(object : ActivityHttpCallback<ResponseBody>(this@SendActivity) { override fun onSucceed(call: Call<ResponseBody>?, response: Response<ResponseBody>) { finish() } override fun onFailure(call: Call<ResponseBody>?, t: Throwable?, errMsg: Any?) { super.onFailure(call, t, errMsg) isEnabled = true } }) true } } } TYPE_REPLY -> { eTitle.editText!!.setText(getString(R.string.reply_to, intent.getStringExtra(Const.REPLY))) tags.visibility = View.GONE sendButton.apply { setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS) setOnMenuItemClickListener { if (KeyboardUtils.isSoftInputVisible(this@SendActivity)) KeyboardUtils.hideSoftInput(this@SendActivity) isEnabled = false API.Topics.reply( intent.getIntExtra(Const.ID, -1), content.editText!!.text.toString()).enqueue(object : ActivityHttpCallback<ResponseBody>(this@SendActivity) { override fun onSucceed(call: Call<ResponseBody>?, response: Response<ResponseBody>) { finish() } override fun onFailure(call: Call<ResponseBody>?, t: Throwable?, errMsg: Any?) { super.onFailure(call, t, errMsg) isEnabled = true } }) true } } } TYPE_REPLY_POST -> { eTitle.editText!!.setText(getString(R.string.reply_to, intent.getStringExtra(Const.REPLY))) tags.visibility = View.GONE sendButton.apply { setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS) setOnMenuItemClickListener { if (KeyboardUtils.isSoftInputVisible(this@SendActivity)) KeyboardUtils.hideSoftInput(this@SendActivity) isEnabled = false API.Topics.reply( intent.getIntExtra(Const.ID, -1), content.editText!!.text.toString(), intent.getIntExtra(Const.ID2,-1)).enqueue(object : ActivityHttpCallback<ResponseBody>(this@SendActivity) { override fun onSucceed(call: Call<ResponseBody>?, response: Response<ResponseBody>) { finish() } override fun onFailure(call: Call<ResponseBody>?, t: Throwable?, errMsg: Any?) { super.onFailure(call, t, errMsg) isEnabled = true } }) true } } } } } private fun popupTextInput(type: Int) { mMessageModel.set(content.editText!!.text) supportFragmentManager.beginTransaction().apply { setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE) MarkdownFragment.TYPE = type MarkdownFragment().show(this, "input_$type") }.commitNow() } private fun applyIconsAndActions() { bold.setOnClickListener { popupTextInput(Const.MD_BOLD) } italic.setOnClickListener { popupTextInput(Const.MD_ITALIC) } list.setOnClickListener { popupTextInput(Const.MD_LIST) } list_ol.setOnClickListener { popupTextInput(Const.MD_LIST_OL) } strikethrough.setOnClickListener { popupTextInput(Const.MD_ST) } underline.setOnClickListener { popupTextInput(Const.MD_UL) } quote.setOnClickListener { popupTextInput(Const.MD_QUOTE) } code.setOnClickListener { popupTextInput(Const.MD_CODE) } full.setOnClickListener { popupTextInput(Const.MD_FULL) } ImageHolder(FontAwesome.Icon.faw_bold).applyTo(bold) ImageHolder(FontAwesome.Icon.faw_italic).applyTo(italic) ImageHolder(FontAwesome.Icon.faw_list_ul).applyTo(list) ImageHolder(FontAwesome.Icon.faw_list_ol).applyTo(list_ol) ImageHolder(FontAwesome.Icon.faw_strikethrough).applyTo(strikethrough) ImageHolder(FontAwesome.Icon.faw_underline).applyTo(underline) ImageHolder(FontAwesome.Icon.faw_quote_left).applyTo(quote) ImageHolder(FontAwesome.Icon.faw_code).applyTo(code) ImageHolder(FontAwesome.Icon.faw_square_o).applyTo(full) image.setOnClickListener { popupTextInput(Const.MD_IMAGE) } emoji.setOnClickListener { popupTextInput(Const.MD_EMOJI) } link.setOnClickListener { popupTextInput(Const.MD_LINK) } ImageHolder(FontAwesome.Icon.faw_file_image_o).applyTo(image) ImageHolder(FontAwesome.Icon.faw_smile_o).applyTo(emoji) ImageHolder(FontAwesome.Icon.faw_link).applyTo(link) } }
apache-2.0
88dd48c1b7371e274ad2a400ce64111d
45.988372
148
0.584385
5.144494
false
false
false
false
flutter/put-flutter-to-work
newsfeed_android/app/src/main/java/com/example/newsfeed_android/MainActivity.kt
1
4247
package com.example.newsfeed_android import android.os.Bundle import android.view.Window import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.example.newsfeed_android.databinding.ActivityMainBinding import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.android.FlutterActivityLaunchConfigs import io.flutter.embedding.engine.FlutterEngine import io.flutter.embedding.engine.FlutterEngineCache import io.flutter.embedding.engine.dart.DartExecutor import kotlinx.coroutines.* private const val FLUTTER_ENGINE_NAME = "nps_flutter_engine_name" private const val ROW_ITEM_NAME = "row_item" class MainActivity : AppCompatActivity() { private var recyclerViewAdapter: RecyclerViewAdapter? = null private var rowsArrayList: ArrayList<String> = ArrayList() private var isLoading = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) warmupFlutterEngine() this.supportRequestWindowFeature(Window.FEATURE_NO_TITLE) val binding = ActivityMainBinding.inflate(layoutInflater) populateData(rowsArrayList) initAdapter(binding) initScrollListener(binding) setContentView(binding.root) } private fun initScrollListener(binding: ActivityMainBinding) { val loadMoreCallback = LoadMoreOnScrollListener(callback = { val linearLayoutManager = binding.recyclerView.layoutManager as LinearLayoutManager? if (!isLoading) { if (linearLayoutManager != null && linearLayoutManager.findLastCompletelyVisibleItemPosition() == (rowsArrayList.size - 1)) { isLoading = true loadMore() } } }) binding.recyclerView.addOnScrollListener(loadMoreCallback) } private fun initAdapter( binding: ActivityMainBinding) { recyclerViewAdapter = RecyclerViewAdapter(rowsArrayList) binding.recyclerView.layoutManager = LinearLayoutManager(applicationContext) binding.recyclerView.adapter = recyclerViewAdapter } private fun populateData(list: ArrayList<String> ) { for (i in 0..20) { list.add(ROW_ITEM_NAME) } } private fun loadMore() { if(rowsArrayList.size in 19..29){ runFlutterNPS() } runBlocking { launch { fakeRequest() rowsArrayList.removeAt(rowsArrayList.size - 1) val scrollPosition = rowsArrayList.size recyclerViewAdapter?.notifyItemRemoved(scrollPosition) var currentSize = rowsArrayList.size val nextLimit = currentSize + 10 while (currentSize - 1 < nextLimit) { rowsArrayList.add(ROW_ITEM_NAME) currentSize++ } isLoading = false recyclerViewAdapter?.notifyItemRangeInserted(nextLimit - 10,10) } } } private suspend fun fakeRequest(): Boolean { delay(2000) return true } private fun runFlutterNPS() { startActivity( FlutterActivity.withCachedEngine(FLUTTER_ENGINE_NAME) .backgroundMode(FlutterActivityLaunchConfigs.BackgroundMode.transparent) .build(this) ) } private fun warmupFlutterEngine() { val flutterEngine = FlutterEngine(this) // Start executing Dart code to pre-warm the FlutterEngine. flutterEngine.dartExecutor.executeDartEntrypoint( DartExecutor.DartEntrypoint.createDefault() ) // Cache the FlutterEngine to be used by FlutterActivity. FlutterEngineCache .getInstance() .put(FLUTTER_ENGINE_NAME, flutterEngine) } internal class LoadMoreOnScrollListener(private var callback: () -> Unit) : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) callback() } } }
bsd-3-clause
3fe52544f957f40de4f9ab61219ee8d5
34.099174
113
0.660937
5.375949
false
false
false
false
XSmile2008/ImageResizer
src/entities/ImageEntity.kt
1
770
package entities import java.awt.image.BufferedImage /** * Created by vladstarikov on 3/25/17. */ class ImageEntity(var img: BufferedImage, var name: String) { var sizePx = ImageSize(img.width, img.height) var sizeDp = ImageSize(img.width, img.height) private var originScale = 1.0 fun getAspectRatio(): Double = img.width.toDouble() / img.height.toDouble() fun setOriginScale(scale: Double) { originScale = scale if (originScale != 1.0) { sizeDp = sizePx.scale(1 / scale) } } fun getOriginScale(): Double { return originScale } fun getScaledSize(ratio: Double): ImageSize { return if (originScale == 1.0) sizeDp.scale(ratio) else sizePx.scale(ratio / originScale) } }
apache-2.0
00bc9c74cf749f02b16829446df7cc1c
23.870968
97
0.645455
3.701923
false
false
false
false
DevCharly/kotlin-ant-dsl
src/main/kotlin/com/devcharly/kotlin/ant/util/chainedmapper.kt
1
1796
/* * Copyright 2016 Karl Tauber * * 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.devcharly.kotlin.ant import org.apache.tools.ant.util.ChainedMapper import org.apache.tools.ant.util.FileNameMapper /****************************************************************************** DO NOT EDIT - this file was generated ******************************************************************************/ interface IChainedMapperNested { fun chainedmapper( from: String? = null, to: String? = null, nested: (KChainedMapper.() -> Unit)? = null) { _addChainedMapper(ChainedMapper().apply { _init(from, to, nested) }) } fun _addChainedMapper(value: ChainedMapper) } fun IFileNameMapperNested.chainedmapper( from: String? = null, to: String? = null, nested: (KChainedMapper.() -> Unit)? = null) { _addFileNameMapper(ChainedMapper().apply { _init(from, to, nested) }) } fun ChainedMapper._init( from: String?, to: String?, nested: (KChainedMapper.() -> Unit)?) { if (from != null) setFrom(from) if (to != null) setTo(to) if (nested != null) nested(KChainedMapper(this)) } class KChainedMapper(val component: ChainedMapper) : IFileNameMapperNested { override fun _addFileNameMapper(value: FileNameMapper) = component.addConfigured(value) }
apache-2.0
e95491ecabb6cb97f5b12c51dcbcc7f7
25.80597
88
0.655902
3.680328
false
false
false
false
ngageoint/mage-android
mage/src/main/java/mil/nga/giat/mage/network/gson/GeometryTypeAdapter.kt
1
4117
package mil.nga.giat.mage.network.gson import com.google.gson.JsonArray import com.google.gson.JsonParser import com.google.gson.TypeAdapter import com.google.gson.stream.JsonReader import com.google.gson.stream.JsonToken import com.google.gson.stream.JsonWriter import mil.nga.sf.* class GeometryTypeAdapter: TypeAdapter<Geometry>() { override fun write(out: JsonWriter, value: Geometry) { throw UnsupportedOperationException() } override fun read(reader: JsonReader): Geometry? { if (reader.peek() != JsonToken.BEGIN_OBJECT) { reader.skipValue() return null } reader.beginObject() var typeName: String? = null var coordinates: JsonArray? = null var geometry: Geometry? = null while(reader.hasNext()) { when(reader.nextName()) { "type" -> typeName = reader.nextString() "coordinates" -> { coordinates = JsonParser.parseReader(reader) as? JsonArray } else -> reader.skipValue() } } if (typeName != null) { geometry = when (typeName) { "Point" -> toPoint(coordinates) "MultiPoint" -> toMultiPoint(coordinates) "LineString" -> toLineString(coordinates) "MultiLineString" -> toMultiLineString(coordinates) "Polygon" -> toPolygon(coordinates) "MultiPolygon" -> toMultiPolygon(coordinates) "GeometryCollection" -> toGeometryCollection(reader) else -> return null } } reader.endObject() return geometry } private fun toPoint(jsonArray: JsonArray?): Point? { if (jsonArray == null || jsonArray.size() < 2) return null val x = jsonArray[0].asDouble val y = jsonArray[1].asDouble return Point(x, y) } private fun toMultiPoint(jsonArray: JsonArray?): MultiPoint? { if (jsonArray == null) return null val multiPoint = MultiPoint() for (i in 0 until jsonArray.size()) { toPoint(jsonArray[i] as? JsonArray)?.let { multiPoint.addPoint(it) } } return multiPoint } private fun toLineString(jsonArray: JsonArray?): LineString? { if (jsonArray == null) return null val lineString = LineString() for (i in 0 until jsonArray.size()) { toPoint(jsonArray[i] as? JsonArray)?.let { lineString.addPoint(it) } } return lineString } private fun toMultiLineString(jsonArray: JsonArray?): MultiLineString? { if (jsonArray == null) return null val multiLineString = MultiLineString() for (i in 0 until jsonArray.size()) { toLineString(jsonArray[i] as? JsonArray)?.let { multiLineString.addLineString(it) } } return multiLineString } private fun toPolygon(jsonArray: JsonArray?): Polygon? { if (jsonArray == null) return null val polygon = Polygon() for (i in 0 until jsonArray.size()) { toLineString(jsonArray[i] as? JsonArray)?.let { polygon.addRing(it) } } return polygon } private fun toMultiPolygon(jsonArray: JsonArray?): MultiPolygon? { if (jsonArray == null) return null val multiPolygon = MultiPolygon() for (i in 0 until jsonArray.size()) { val polygon = toPolygon(jsonArray[i] as? JsonArray) multiPolygon.addPolygon(polygon) } return multiPolygon } private fun toGeometryCollection(reader: JsonReader): GeometryCollection<Geometry> { val geometryCollection = GeometryCollection<Geometry>() if (reader.peek() != JsonToken.BEGIN_OBJECT) { return geometryCollection } reader.beginObject() while(reader.hasNext()) { when(reader.nextName()) { "geometries" -> { read(reader)?.let { geometryCollection.addGeometry(it) } } else -> reader.skipValue() } } reader.endObject() return geometryCollection } }
apache-2.0
3f42d66bf313107897c64b9e31d69462
27.013605
87
0.60238
4.549171
false
false
false
false
CarrotCodes/Warren
src/test/kotlin/chat/willow/warren/extension/extended_join/ExtendedJoinExtensionTests.kt
1
2042
package chat.willow.warren.extension.extended_join import chat.willow.kale.IKale import chat.willow.kale.IKaleIrcMessageHandler import chat.willow.kale.IKaleMessageHandler import chat.willow.kale.IKaleRouter import chat.willow.kale.helper.CaseMapping import chat.willow.kale.irc.message.rfc1459.JoinMessage import chat.willow.warren.state.* import com.nhaarman.mockito_kotlin.* import org.junit.Before import org.junit.Test class ExtendedJoinExtensionTests { private lateinit var sut: ExtendedJoinExtension private lateinit var mockKale: IKale private lateinit var mockKaleRouter: IKaleRouter<IKaleIrcMessageHandler> private lateinit var mockJoinHandler: IKaleMessageHandler<JoinMessage.Message> private lateinit var mockJoinIrcMessageHandler: IKaleIrcMessageHandler private lateinit var channelsState: ChannelsState private lateinit var connectionState: ConnectionState @Before fun setUp() { val lifecycleState = LifecycleState.DISCONNECTED mockKale = mock() mockKaleRouter = mock() mockJoinHandler = mock() mockJoinIrcMessageHandler = mock() whenever(mockKaleRouter.handlerFor("JOIN")).thenReturn(mockJoinIrcMessageHandler) mockJoinHandler = mock() channelsState = emptyChannelsState(CaseMappingState(CaseMapping.RFC1459)) connectionState = ConnectionState(server = "test.server", port = 6697, nickname = "test-nick", user = "test-nick", lifecycle = lifecycleState) sut = ExtendedJoinExtension(mockKaleRouter, channelsState, CaseMappingState(CaseMapping.RFC1459)) } @Test fun test_setUp_RegistersCorrectHandlers() { sut.setUp() verify(mockKaleRouter).register(eq("JOIN"), any<ExtendedJoinHandler>()) } @Test fun test_tearDown_UnregistersCorrectHandlers() { sut.setUp() sut.tearDown() inOrder(mockKaleRouter) { verify(mockKaleRouter).unregister("JOIN") verify(mockKaleRouter).register("JOIN", mockJoinIrcMessageHandler) } } }
isc
190d7e0dd9c70246fbcdb5aa89d2279a
35.482143
150
0.742899
4.726852
false
true
false
false
tmarsteel/compiler-fiddle
src/compiler/transact/SourceFileReader.kt
1
2410
/* * Copyright 2018 Tobias Marstaller * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package compiler.transact /** * A [TransactionalSequence] on a String that tracks line and column numbers. */ class SourceFileReader(code: String) : TransactionalSequence<Char, SourceFileReader.SourceLocation>(code.toList()) { override public var currentPosition: SourceLocation = SourceLocation(0, 1, 1) protected set override fun copyOfPosition(position: SourceLocation): SourceLocation { return SourceLocation(position.sourceIndex, position.lineNumber, position.columnNumber) } override fun next(): Char? { if (items.lastIndex < currentPosition.sourceIndex) { return null } val char = items[currentPosition.sourceIndex] if (currentPosition.sourceIndex > 0) { var previousChar = items[currentPosition.sourceIndex - 1] if (previousChar == '\n') { currentPosition.lineNumber++ currentPosition.columnNumber = 1 } else { currentPosition.columnNumber++ } } currentPosition.sourceIndex++ return char } fun next(nChars: Int) : String? { if (currentPosition.sourceIndex + nChars - 1 > items.lastIndex) { return null } val buf = StringBuilder(nChars) for (i in 0..nChars - 1) { buf.append(next()!!) } return buf.toString() } class SourceLocation( sourceIndex: Int, var lineNumber: Int, var columnNumber: Int ) : Position(sourceIndex) }
lgpl-3.0
1e77e2b1ad92920031d7d494f02f24df
28.765432
114
0.636515
4.868687
false
false
false
false
mrebollob/LoteriadeNavidad
androidApp/src/main/java/com/mrebollob/loteria/android/presentation/settings/manageticket/ManageTicketsViewModel.kt
1
2658
package com.mrebollob.loteria.android.presentation.settings.manageticket import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.mrebollob.loteria.android.R import com.mrebollob.loteria.android.presentation.platform.ErrorMessage import com.mrebollob.loteria.domain.entity.Ticket import com.mrebollob.loteria.domain.repository.TicketsRepository import java.util.UUID import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch class ManageTicketsViewModel( private val ticketsRepository: TicketsRepository ) : ViewModel() { private val viewModelState = MutableStateFlow(ManageTicketsViewModelState()) val uiState = viewModelState .map { it.toUiState() } .stateIn( viewModelScope, SharingStarted.Eagerly, viewModelState.value.toUiState() ) init { refreshData() } fun refreshData() { viewModelState.update { it.copy(isLoading = true) } viewModelScope.launch { ticketsRepository.getTickets().onSuccess { tickets -> viewModelState.update { it.copy( tickets = tickets, isLoading = false ) } }.onFailure { viewModelState.update { val errorMessages = it.errorMessages + ErrorMessage( id = UUID.randomUUID().mostSignificantBits, messageId = R.string.load_error ) it.copy(errorMessages = errorMessages) } } } } fun onDeleteTicketClick(ticket: Ticket) { viewModelScope.launch { ticketsRepository.deleteTicket(ticket).onSuccess { refreshData() }.onFailure { viewModelState.update { val errorMessages = it.errorMessages + ErrorMessage( id = UUID.randomUUID().mostSignificantBits, messageId = R.string.load_error ) it.copy(errorMessages = errorMessages) } } } } fun errorShown(errorId: Long) { viewModelState.update { currentUiState -> val errorMessages = currentUiState.errorMessages.filterNot { it.id == errorId } currentUiState.copy(errorMessages = errorMessages) } } }
apache-2.0
440e6b4a8f1ce8a2755dba46023cef6e
32.64557
91
0.602709
5.457906
false
false
false
false
beyama/winter
winter/src/main/kotlin/io/jentz/winter/Types.kt
1
2312
package io.jentz.winter import java.lang.reflect.* @Suppress("MagicNumber") internal object Types { fun equals(left: Type, right: Type): Boolean { if (left.javaClass != right.javaClass) return false return when (left) { is Class<*> -> left == right is ParameterizedType -> { right as ParameterizedType equals(left.rawType, right.rawType) && equals(left.actualTypeArguments, right.actualTypeArguments) } is WildcardType -> { right as WildcardType equals(left.lowerBounds, right.lowerBounds) && equals(left.upperBounds, right.upperBounds) } is GenericArrayType -> { right as GenericArrayType equals(left.genericComponentType, right.genericComponentType) } is TypeVariable<*> -> { right as TypeVariable<*> equals(left.bounds, right.bounds) } else -> left == right } } private fun equals(left: Array<Type>, right: Array<Type>): Boolean { if (left.size != right.size) return false return left.indices.all { equals(left[it], right[it]) } } fun hashCode(type: Type): Int = when (type) { is Class<*> -> type.hashCode() is ParameterizedType -> { var hashCode = hashCode(type.rawType) for (arg in type.actualTypeArguments) hashCode = hashCode * 31 + hashCode(arg) hashCode } is WildcardType -> { var hashCode = 0 for (arg in type.upperBounds) hashCode = hashCode * 19 + hashCode(arg) for (arg in type.lowerBounds) hashCode = hashCode * 17 + hashCode(arg) hashCode } is GenericArrayType -> 53 + hashCode(type.genericComponentType) is TypeVariable<*> -> { var hashCode = 0 for (arg in type.bounds) hashCode = hashCode * 29 + hashCode(arg) hashCode } else -> type.hashCode() } fun hashCode(cls: Class<*>, qualifier: Any? = null): Int = 31 * cls.hashCode() + (qualifier?.hashCode() ?: 0) }
apache-2.0
7f891a68a4241008f5aa8df3f3d4e945
32.507246
86
0.529412
4.972043
false
false
false
false
vsch/idea-multimarkdown
src/main/java/com/vladsch/md/nav/actions/handlers/BackspaceHandler.kt
1
3128
// Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.vladsch.md.nav.actions.handlers import com.intellij.codeInsight.editorActions.BackspaceHandlerDelegate import com.intellij.codeInsight.lookup.LookupManager import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiFile import com.vladsch.md.nav.actions.api.MdFormatElementHandler import com.vladsch.md.nav.actions.handlers.util.AutoCharsContext import com.vladsch.md.nav.actions.handlers.util.CaretContextInfo import com.vladsch.md.nav.actions.handlers.util.ParagraphContext import com.vladsch.md.nav.language.MdCodeStyleSettings import com.vladsch.md.nav.psi.element.MdFile class BackspaceHandler : BackspaceHandlerDelegate() { private var skipCharDeleted = false override fun beforeCharDeleted(c: Char, file: PsiFile, editor: Editor) { if (file is MdFile && editor.caretModel.caretCount == 1 && LookupManager.getInstance(file.project).activeLookup == null) { CaretContextInfo.withContext(file, editor, null, true) { caretContext -> caretContext.beforeBackspaceHandler() skipCharDeleted = false val autoCharsContext = AutoCharsContext.getContext(caretContext) if (autoCharsContext != null) { if (autoCharsContext.isAutoTypeEnabled(c)) { autoCharsContext.autoBackspaceChar() skipCharDeleted = true } } } } } override fun charDeleted(c: Char, file: PsiFile, editor: Editor): Boolean { for (handler in MdFormatElementHandler.EXTENSIONS.value) { if (handler.skipBackspaceHandler()) return false } if (file is MdFile && !skipCharDeleted && editor.caretModel.caretCount == 1 && LookupManager.getInstance(file.project).activeLookup == null) { return CaretContextInfo.withContextOr(file, editor, c, isDeleted = true, noContextValue = false, caretOffset = null) { caretContext -> caretContext.backspaceHandler() val styleSettings = MdCodeStyleSettings.getInstance(file) val isFormatRegion = caretContext.isFormatRegion(caretContext.caretOffset) if (isFormatRegion) { if (caretContext.editOpDelta <= 0 && styleSettings.isWrapOnTyping) { // see if need to wrap lines to margins on this line // header looking lines, table looking lines will not get wrapped caretContext.isForceDelete = true val paragraphContext = ParagraphContext.getContext(caretContext) @Suppress("IfThenToSafeAccess") if (paragraphContext != null) { paragraphContext.adjustParagraph(true) } } } true } } return false } }
apache-2.0
dbd6f370ba0e6dc1d3efc6ccf2d12783
46.393939
177
0.640665
4.910518
false
false
false
false
geckour/Egret
app/src/main/java/com/geckour/egret/view/fragment/InstanceMuteFragment.kt
1
4717
package com.geckour.egret.view.fragment import android.databinding.DataBindingUtil import android.os.Bundle import android.support.design.widget.FloatingActionButton import android.text.TextUtils import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.geckour.egret.R import com.geckour.egret.databinding.FragmentMuteInstanceBinding import com.geckour.egret.model.MuteInstance import com.geckour.egret.util.Common import com.geckour.egret.util.OrmaProvider import com.geckour.egret.view.activity.MainActivity import com.geckour.egret.view.adapter.MuteInstanceAdapter import io.reactivex.Observable import io.reactivex.Single import io.reactivex.schedulers.Schedulers import timber.log.Timber class InstanceMuteFragment: BaseFragment() { lateinit private var binding: FragmentMuteInstanceBinding private val adapter: MuteInstanceAdapter by lazy { MuteInstanceAdapter() } private val preItems: ArrayList<MuteInstance> = ArrayList() companion object { val TAG: String = this::class.java.simpleName val ARGS_KEY_DEFAULT_INSTANCE = "defaultInstance" fun newInstance(defaultInstance: MuteInstance? = null): InstanceMuteFragment { val fragment = InstanceMuteFragment() val args = Bundle() if (defaultInstance != null) args.putString(ARGS_KEY_DEFAULT_INSTANCE, defaultInstance.instance) fragment.arguments = args return fragment } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding = DataBindingUtil.inflate(inflater, R.layout.fragment_mute_instance, container, false) binding.defaultInstance = if (arguments.containsKey(ARGS_KEY_DEFAULT_INSTANCE)) { arguments.getString(ARGS_KEY_DEFAULT_INSTANCE, "") } else "" binding.buttonAdd.setOnClickListener { val instance = binding.editTextAddMuteInstance.text.toString() addInstance(instance) } return binding.root } override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.editTextAddMuteInstance.requestFocusFromTouch() binding.editTextAddMuteInstance.requestFocus() val instance = binding.editTextAddMuteInstance.text.toString() binding.editTextAddMuteInstance.setSelection(instance.length) val helper = Common.getSwipeToDismissTouchHelperForMuteInstance(adapter) helper.attachToRecyclerView(binding.recyclerView) binding.recyclerView.addItemDecoration(helper) binding.recyclerView.adapter = adapter } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) bindSavedKeywords() } override fun onResume() { super.onResume() if (activity is MainActivity) ((activity as MainActivity).findViewById(R.id.fab) as FloatingActionButton?)?.hide() } override fun onPause() { super.onPause() manageInstances() } fun bindSavedKeywords() { adapter.clearItems() preItems.clear() val items = OrmaProvider.db.selectFromMuteInstance().toList() adapter.addAllItems(items) preItems.addAll(items) } fun addInstance(instance: String) { if (TextUtils.isEmpty(instance)) return adapter.addItem(MuteInstance(instance = instance)) binding.editTextAddMuteInstance.setText("") } fun manageInstances() { val items = adapter.getItems() removeInstances(items) .subscribeOn(Schedulers.newThread()) .subscribe({ registerInstances(items) }, Throwable::printStackTrace) } fun removeInstances(items: List<MuteInstance>): Single<Int> { val shouldRemoveItems = preItems.filter { items.none { item -> it.id == item.id } } var where = "(`id` = ?)" for (i in 1..shouldRemoveItems.lastIndex) where += " OR (`id` = ?)" return OrmaProvider.db.deleteFromMuteInstance().where(where, *shouldRemoveItems.map { it.id }.toTypedArray()).executeAsSingle() } fun registerInstances(items: List<MuteInstance>) { Observable.fromIterable(items) .subscribeOn(Schedulers.newThread()) .map { OrmaProvider.db.relationOfMuteInstance().upsert(it) } .subscribe({ Timber.d("updated mute instance: ${it.instance}") }, Throwable::printStackTrace) } }
gpl-3.0
18065fe9a975a1d2a5fa41309f5d9c13
35.859375
135
0.697053
4.783976
false
false
false
false
http4k/http4k
http4k-core/src/main/kotlin/org/http4k/filter/TrafficFilters.kt
1
1888
package org.http4k.filter import org.http4k.core.Body import org.http4k.core.Filter import org.http4k.core.Request import org.http4k.core.Response import org.http4k.core.Status.Companion.BAD_REQUEST import org.http4k.traffic.Replay import org.http4k.traffic.Sink import org.http4k.traffic.Source object TrafficFilters { /** * Responds to requests with a stored Response if possible, or falls back to the next Http Handler */ object ServeCachedFrom { operator fun invoke(source: Source): Filter = Filter { next -> { source[it] ?: next(it) } } } /** * Intercepts and Writes Request/Response traffic */ object RecordTo { operator fun invoke(sink: Sink): Filter = Filter { next -> { val copy = it.body(Body(it.body.payload)) next(copy).run { val response = body(Body(body.payload)) response.apply { sink[copy] = this } } } } } /** * Replays Writes Request/Response traffic */ object ReplayFrom { operator fun invoke( replay: Replay, matchFn: (Request, Request) -> Boolean = { received, stored -> received.toString() != stored.toString() } ): Filter { val pairs = replay.requests().zip(replay.responses()) var count = 0 return Filter { val responder = { received: Request -> try { val (req, resp) = pairs.drop(count).first() if (matchFn(received, req)) Response(BAD_REQUEST) else resp.also { count++ } } catch (e: NoSuchElementException) { Response(BAD_REQUEST) } } responder } } } }
apache-2.0
b8e50da9cc6a61ed5334c448fd3dc657
29.451613
117
0.533369
4.431925
false
false
false
false
Zukkari/nirdizati-training-ui
src/main/kotlin/cs/ut/jobs/Job.kt
1
4336
package cs.ut.jobs import cs.ut.engine.IdProvider import cs.ut.engine.JobManager import cs.ut.exceptions.Left import cs.ut.exceptions.ProcessErrorException import cs.ut.exceptions.Right import cs.ut.exceptions.perform import org.apache.logging.log4j.LogManager import java.time.format.DateTimeFormatter import java.util.Date /** * Enum that represents job status */ enum class JobStatus { QUEUED, PREPARING, RUNNING, FINISHING, COMPLETED, FAILED } /** * Abstract class that represents job structure */ abstract class Job protected constructor(generatedId: String = "") : Runnable { val log = LogManager.getLogger(Job::class)!! val id: String = if (generatedId.isBlank()) IdProvider.getNextId() else generatedId var status: JobStatus = JobStatus.QUEUED var startTime: String = start() /** * Action to be performed before job execution */ open fun preProcess() = Unit /** * Action to be performed in execution stage */ open fun execute() = Unit /** * Action to be performed after execute stage */ open fun postExecute() = Unit /** * Should user be notified of job completion */ open fun isNotificationRequired() = false /** * Notification message to show to the user */ open fun getNotificationMessage() = "" /** * Function that is called before interrupting the thread on graceful shutdown */ open fun beforeInterrupt() = Unit /** * In case job wants to handle errors itself */ open fun onError() = Unit /** * Running the job */ override fun run() { val start = System.currentTimeMillis() log.debug("Started job execution: $this") startTime = start() perform { log.debug("Stared pre process stage") status = JobStatus.PREPARING updateEvent() preProcess() }.apply { when (this) { is Right -> log.debug("Job $id finished pre process step") is Left -> { handleError(this) return } } } perform { log.debug("Job $id started execute stage") status = JobStatus.RUNNING updateEvent() execute() if (errorOccurred()) { throw ProcessErrorException() } }.apply { when (this) { is Right -> log.debug("Job $id finished execute step") is Left -> { perform { onError() }.apply { when (this) { is Left -> log.error("Error occurred when handling exception for job $id", this.error) } } log.error("Job $id failed in execute stage", this.error) status = JobStatus.FAILED updateEvent() return } } } perform { log.debug("Job $id started post execute step") status = JobStatus.FINISHING updateEvent() postExecute() }.apply { when (this) { is Right -> log.debug("Job $id completed successfully") is Left -> { handleError(this) return } } } status = JobStatus.COMPLETED updateEvent() val end = System.currentTimeMillis() log.debug("$this finished running in ${end - start} ms") } private fun handleError(left: Left<Exception>) { log.debug("Job $id failed", left.error) status = JobStatus.FAILED updateEvent() } /** * Status have been updated, notify job manager */ private fun updateEvent() { JobManager.statusUpdated(this) } open fun errorOccurred() = false /** * Get start time for the job * * @return start time in ISO format as string */ private fun start(): String { val date = Date() val df = DateTimeFormatter.ISO_INSTANT return df.format(date.toInstant()) } }
lgpl-3.0
91e58005b33b2563a88afa4ad5d85df8
23.22905
114
0.532057
4.995392
false
false
false
false
microg/android_packages_apps_GmsCore
play-services-base-core-ui/src/main/kotlin/org/microg/gms/ui/TextPreference.kt
1
1466
/* * SPDX-FileCopyrightText: 2020, microG Project Team * SPDX-License-Identifier: Apache-2.0 */ package org.microg.gms.ui import android.content.Context import android.util.AttributeSet import android.util.TypedValue import android.view.Gravity import android.view.ViewGroup.LayoutParams.MATCH_PARENT import android.widget.LinearLayout import android.widget.TextView import androidx.preference.Preference import androidx.preference.PreferenceViewHolder class TextPreference : Preference { constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) constructor(context: Context) : super(context) override fun onBindViewHolder(holder: PreferenceViewHolder?) { super.onBindViewHolder(holder) val iconFrame = holder?.findViewById(androidx.preference.R.id.icon_frame) iconFrame?.layoutParams?.height = MATCH_PARENT (iconFrame as? LinearLayout)?.gravity = Gravity.TOP or Gravity.START val pad = (context.resources.displayMetrics.densityDpi/160f * 20).toInt() iconFrame?.setPadding(0, pad, 0, pad) val textView = holder?.findViewById(android.R.id.summary) as? TextView textView?.maxLines = Int.MAX_VALUE } }
apache-2.0
d90e3a9832816b1b7289d18eccd26b53
40.885714
144
0.753752
4.376119
false
false
false
false
square/duktape-android
zipline/src/jniTest/kotlin/app/cash/zipline/ZiplineTest.kt
1
14449
/* * Copyright (C) 2021 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.cash.zipline import app.cash.zipline.internal.consoleName import app.cash.zipline.internal.eventListenerName import app.cash.zipline.internal.eventLoopName import app.cash.zipline.internal.jsPlatformName import app.cash.zipline.testing.EchoRequest import app.cash.zipline.testing.EchoResponse import app.cash.zipline.testing.EchoService import app.cash.zipline.testing.PotatoService import app.cash.zipline.testing.SuspendingEchoService import app.cash.zipline.testing.SuspendingPotatoService import com.google.common.truth.Truth.assertThat import kotlin.test.assertFailsWith import kotlinx.coroutines.CancellationException import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.async import kotlinx.coroutines.cancel import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.runBlocking import kotlinx.coroutines.sync.Semaphore import kotlinx.coroutines.sync.withPermit import kotlinx.coroutines.test.TestCoroutineDispatcher import org.junit.After import org.junit.Before import org.junit.Test @OptIn(ExperimentalCoroutinesApi::class) class ZiplineTest { private val dispatcher = TestCoroutineDispatcher() private val zipline = Zipline.create(dispatcher) private val uncaughtExceptionHandler = TestUncaughtExceptionHandler() @Before fun setUp() = runBlocking(dispatcher) { zipline.loadTestingJs() uncaughtExceptionHandler.setUp() } @After fun tearDown() = runBlocking(dispatcher) { zipline.close() uncaughtExceptionHandler.tearDown() } @Test fun cannotTakeOrBindServiceAfterClose(): Unit = runBlocking(dispatcher) { zipline.close() assertFailsWith<IllegalStateException> { zipline.take<EchoService>("helloService") } assertFailsWith<IllegalStateException> { zipline.bind<EchoService>("supService", JvmEchoService("sup")) } } @Test fun callServiceAfterCloseFailsGracefully() = runBlocking(dispatcher) { zipline.quickJs.evaluate("testing.app.cash.zipline.testing.prepareJsBridges()") val service = zipline.take<EchoService>("helloService") zipline.close() assertThat(assertFailsWith<IllegalStateException> { service.echo(EchoRequest("Jake")) }).hasMessageThat().isEqualTo("Zipline closed") } @Test fun jvmCallJsService() = runBlocking(dispatcher) { zipline.quickJs.evaluate("testing.app.cash.zipline.testing.prepareJsBridges()") val helloService = zipline.take<EchoService>("helloService") val yoService = zipline.take<EchoService>("yoService") assertThat(helloService.echo(EchoRequest("Jake"))) .isEqualTo(EchoResponse("hello from JavaScript, Jake")) assertThat(yoService.echo(EchoRequest("Kevin"))) .isEqualTo(EchoResponse("yo from JavaScript, Kevin")) } @Test fun jsCallJvmService() = runBlocking(dispatcher) { zipline.bind<EchoService>("supService", JvmEchoService("sup")) assertThat(zipline.quickJs.evaluate("testing.app.cash.zipline.testing.callSupService('homie')")) .isEqualTo("JavaScript received 'sup from the JVM, homie' from the JVM") } @Test fun suspendingJvmCallJsService() = runBlocking(dispatcher) { zipline.quickJs.evaluate("testing.app.cash.zipline.testing.prepareSuspendingJsBridges()") val jsSuspendingEchoService = zipline.take<SuspendingEchoService>("jsSuspendingEchoService") val deferred = async { jsSuspendingEchoService.suspendingEcho(EchoRequest("Jake")) } assertThat(deferred.isCompleted).isFalse() zipline.quickJs.evaluate("testing.app.cash.zipline.testing.unblockSuspendingJs()") assertThat(deferred.await()) .isEqualTo(EchoResponse("hello from suspending JavaScript, Jake")) } @Test fun suspendingJsCallJvmService() = runBlocking(dispatcher) { val jvmSuspendingEchoService = object : SuspendingEchoService { override suspend fun suspendingEcho(request: EchoRequest): EchoResponse { return EchoResponse("hello from the suspending JVM, ${request.message}") } } zipline.bind<SuspendingEchoService>( "jvmSuspendingEchoService", jvmSuspendingEchoService ) zipline.quickJs.evaluate("testing.app.cash.zipline.testing.callSuspendingEchoService('Eric')") assertThat(zipline.quickJs.evaluate("testing.app.cash.zipline.testing.suspendingEchoResult")) .isEqualTo("hello from the suspending JVM, Eric") } /** * Don't crash and don't log exceptions if a suspending call completes after the QuickJS instance * is closed. Just ignore the response. */ @Test fun suspendingJvmCallCompletesAfterClose() = runBlocking(dispatcher) { val lock = Semaphore(1) val jvmSuspendingEchoService = object : SuspendingEchoService { override suspend fun suspendingEcho(request: EchoRequest): EchoResponse { lock.withPermit { zipline.close() } return EchoResponse("sup from the suspending JVM, ${request.message}") } } zipline.bind<SuspendingEchoService>( "jvmSuspendingEchoService", jvmSuspendingEchoService ) lock.withPermit { zipline.quickJs.evaluate("testing.app.cash.zipline.testing.callSuspendingEchoService('Eric')") } val e = assertFailsWith<IllegalStateException> { zipline.quickJs.evaluate("testing.app.cash.zipline.testing.suspendingEchoResult") } assertThat(e).hasMessageThat().isEqualTo("QuickJs instance was closed") } @Test fun suspendingJsCallCompletesAfterClose(): Unit = runBlocking(dispatcher) { zipline.quickJs.evaluate("testing.app.cash.zipline.testing.prepareSuspendingJsBridges()") val jsSuspendingEchoService = zipline.take<SuspendingEchoService>("jsSuspendingEchoService") val deferred = async { jsSuspendingEchoService.suspendingEcho(EchoRequest("Jake")) } zipline.close() assertFailsWith<CancellationException> { deferred.await() } } @Test fun serviceNamesAndClientNames(): Unit = runBlocking(dispatcher) { zipline.quickJs.evaluate("testing.app.cash.zipline.testing.initZipline()") assertThat(zipline.serviceNames).containsExactly( consoleName, eventLoopName, eventListenerName, ) assertThat(zipline.clientNames).containsExactly( jsPlatformName, ) zipline.quickJs.evaluate("testing.app.cash.zipline.testing.prepareJsBridges()") assertThat(zipline.serviceNames).containsExactly( consoleName, eventLoopName, eventListenerName, ) assertThat(zipline.clientNames).containsExactly( jsPlatformName, "helloService", "yoService", ) zipline.bind<EchoService>("supService", JvmEchoService("sup")) assertThat(zipline.serviceNames).containsExactly( consoleName, eventLoopName, eventListenerName, "supService", ) assertThat(zipline.clientNames).containsExactly( jsPlatformName, "helloService", "yoService", ) } @Test fun jvmCallIncompatibleJsService() = runBlocking(dispatcher) { zipline.quickJs.evaluate("testing.app.cash.zipline.testing.prepareJsBridges()") assertThat(assertFailsWith<ZiplineApiMismatchException> { zipline.take<PotatoService>("helloService").echo() }).hasMessageThat().startsWith(""" no such method (incompatible API versions?) called function: fun echo(): app.cash.zipline.testing.EchoResponse available functions: fun echo(app.cash.zipline.testing.EchoRequest): app.cash.zipline.testing.EchoResponse fun close(): kotlin.Unit at """.trimIndent() ) } @Test fun suspendingJvmCallIncompatibleJsService() = runBlocking(dispatcher) { zipline.quickJs.evaluate("testing.app.cash.zipline.testing.prepareJsBridges()") assertThat(assertFailsWith<ZiplineApiMismatchException> { zipline.take<SuspendingPotatoService>("helloService").echo() }).hasMessageThat().startsWith(""" no such method (incompatible API versions?) called function: suspend fun echo(): app.cash.zipline.testing.EchoResponse available functions: fun echo(app.cash.zipline.testing.EchoRequest): app.cash.zipline.testing.EchoResponse fun close(): kotlin.Unit at """.trimIndent() ) } @Test fun jsCallIncompatibleJvmService() = runBlocking(dispatcher) { zipline.bind<PotatoService>("supService", JvmPotatoService("sup")) assertThat(assertFailsWith<QuickJsException> { zipline.quickJs.evaluate("testing.app.cash.zipline.testing.callSupService('homie')") }).hasMessageThat().startsWith(""" app.cash.zipline.ZiplineApiMismatchException: no such method (incompatible API versions?) called function: fun echo(app.cash.zipline.testing.EchoRequest): app.cash.zipline.testing.EchoResponse available functions: fun echo(): app.cash.zipline.testing.EchoResponse fun close(): kotlin.Unit """.trimIndent() ) } @Test fun suspendingJsCallIncompatibleJvmService() = runBlocking(dispatcher) { zipline.bind<PotatoService>("jvmSuspendingPotatoService", JvmPotatoService("Veyndan")) zipline.quickJs.evaluate("testing.app.cash.zipline.testing.callSuspendingPotatoService('Veyndan')") assertThat(zipline.quickJs.evaluate("testing.app.cash.zipline.testing.suspendingPotatoResult") as String?) .isNull() assertThat(zipline.quickJs.evaluate("testing.app.cash.zipline.testing.suspendingPotatoException") as String?) .startsWith(""" ZiplineApiMismatchException: app.cash.zipline.ZiplineApiMismatchException: no such method (incompatible API versions?) called function: suspend fun echo(): app.cash.zipline.testing.EchoResponse available functions: fun echo(): app.cash.zipline.testing.EchoResponse fun close(): kotlin.Unit """.trimIndent() ) } @Test fun jvmCallUnknownJsService() = runBlocking(dispatcher) { zipline.quickJs.evaluate("testing.app.cash.zipline.testing.initZipline()") val noSuchService = zipline.take<EchoService>("noSuchService") assertThat(assertFailsWith<ZiplineApiMismatchException> { noSuchService.echo(EchoRequest("hello")) }).hasMessageThat().startsWith(""" no such service (service closed?) called service: noSuchService available services: zipline/js """.trimIndent() ) } @Test fun suspendingJvmCallUnknownJsService() = runBlocking(dispatcher) { zipline.quickJs.evaluate("testing.app.cash.zipline.testing.initZipline()") val noSuchService = zipline.take<SuspendingEchoService>("noSuchService") assertThat(assertFailsWith<ZiplineApiMismatchException> { noSuchService.suspendingEcho(EchoRequest("hello")) }).hasMessageThat().startsWith(""" no such service (service closed?) called service: noSuchService available services: zipline/js """.trimIndent() ) } @Test fun jsCallUnknownJvmService() = runBlocking(dispatcher) { assertThat(assertFailsWith<QuickJsException> { zipline.quickJs.evaluate("testing.app.cash.zipline.testing.callSupService('homie')") }).hasMessageThat().startsWith(""" app.cash.zipline.ZiplineApiMismatchException: no such service (service closed?) called service: supService available services: zipline/console zipline/event_loop zipline/event_listener """.trimIndent() ) } @Test fun suspendingJsCallUnknownJvmService() = runBlocking(dispatcher) { zipline.quickJs.evaluate("testing.app.cash.zipline.testing.callSuspendingPotatoService('Veyndan')") assertThat(zipline.quickJs.evaluate("testing.app.cash.zipline.testing.suspendingPotatoResult") as String?) .isNull() assertThat(zipline.quickJs.evaluate("testing.app.cash.zipline.testing.suspendingPotatoException") as String?) .startsWith(""" ZiplineApiMismatchException: app.cash.zipline.ZiplineApiMismatchException: no such service (service closed?) called service: jvmSuspendingPotatoService available services: zipline/console zipline/event_loop zipline/event_listener """.trimIndent() ) } @Test fun cancelContextJobDoesntDestroyZipline() = runBlocking(dispatcher) { val jvmSuspendingEchoService = object : SuspendingEchoService { var callCount = 0 override suspend fun suspendingEcho(request: EchoRequest): EchoResponse { callCount++ if (callCount == 2) { currentCoroutineContext().cancel() } return EchoResponse("response $callCount") } } zipline.bind<SuspendingEchoService>( "jvmSuspendingEchoService", jvmSuspendingEchoService ) zipline.quickJs.evaluate("testing.app.cash.zipline.testing.callSuspendingEchoService('')") assertThat(zipline.quickJs.evaluate("testing.app.cash.zipline.testing.suspendingEchoResult")) .isEqualTo("response 1") zipline.quickJs.evaluate("testing.app.cash.zipline.testing.callSuspendingEchoService('')") assertThat(zipline.quickJs.evaluate("testing.app.cash.zipline.testing.suspendingEchoResult")) .isEqualTo("response 2") zipline.quickJs.evaluate("testing.app.cash.zipline.testing.callSuspendingEchoService('')") assertThat(zipline.quickJs.evaluate("testing.app.cash.zipline.testing.suspendingEchoResult")) .isEqualTo("response 3") } private class JvmEchoService(private val greeting: String) : EchoService { override fun echo(request: EchoRequest): EchoResponse { return EchoResponse("$greeting from the JVM, ${request.message}") } } private class JvmPotatoService(private val greeting: String) : PotatoService { override fun echo(): EchoResponse { return EchoResponse("$greeting from the JVM, anonymous") } } }
apache-2.0
56337d6df14b7cfd6ed494a8a31b75d0
36.143959
126
0.727317
4.603058
false
true
false
false
rock3r/detekt
detekt-rules/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/bugs/MissingWhenCase.kt
1
3999
package io.gitlab.arturbosch.detekt.rules.bugs import io.gitlab.arturbosch.detekt.api.CodeSmell import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.api.Debt import io.gitlab.arturbosch.detekt.api.Entity import io.gitlab.arturbosch.detekt.api.Issue import io.gitlab.arturbosch.detekt.api.Rule import io.gitlab.arturbosch.detekt.api.Severity import org.jetbrains.kotlin.cfg.WhenChecker import org.jetbrains.kotlin.psi.KtWhenExpression import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression import org.jetbrains.kotlin.resolve.calls.callUtil.getType /** * Turn on this rule to flag `when` expressions that do not check that all cases are covered when the subject is an enum * or sealed class and the `when` expression is used as a statement. * * When this happens it's unclear what was intended when an unhandled case is reached. It is better to be explicit and * either handle all cases or use a default `else` statement to cover the unhandled cases. * * <noncompliant> * enum class Color { * RED, * GREEN, * BLUE * } * * fun whenOnEnumFail(c: Color) { * when(c) { * Color.BLUE -> {} * Color.GREEN -> {} * } * } * </noncompliant> * * <compliant> * enum class Color { * RED, * GREEN, * BLUE * } * * fun whenOnEnumCompliant(c: Color) { * when(c) { * Color.BLUE -> {} * Color.GREEN -> {} * Color.RED -> {} * } * } * * fun whenOnEnumCompliant2(c: Color) { * when(c) { * Color.BLUE -> {} * else -> {} * } * } * </compliant> * * Based on code from Kotlin compiler: * https://github.com/JetBrains/kotlin/blob/v1.3.30/compiler/frontend/src/org/jetbrains/kotlin/cfg/ControlFlowInformationProvider.kt * * @active since v1.2.0 */ class MissingWhenCase(config: Config = Config.empty) : Rule(config) { override val issue: Issue = Issue( "MissingWhenCase", Severity.Defect, "Check usage of `when` used as a statement and don't compare all enum or sealed class cases.", Debt.TWENTY_MINS ) @Suppress("ReturnCount") override fun visitWhenExpression(expression: KtWhenExpression) { if (bindingContext == BindingContext.EMPTY) return if (expression.elseExpression != null) return if (expression.isUsedAsExpression(bindingContext)) return val subjectExpression = expression.subjectExpression ?: return val subjectType = subjectExpression.getType(bindingContext) val enumClassDescriptor = WhenChecker.getClassDescriptorOfTypeIfEnum(subjectType) if (enumClassDescriptor != null) { val enumMissingCases = WhenChecker.getEnumMissingCases(expression, bindingContext, enumClassDescriptor) if (enumMissingCases.isNotEmpty()) { report( CodeSmell( issue, Entity.from(expression), "When expression is missing cases: ${enumMissingCases.joinToString()}. Either add missing " + "cases or a default `else` case." ) ) } } val sealedClassDescriptor = WhenChecker.getClassDescriptorOfTypeIfSealed(subjectType) if (sealedClassDescriptor != null) { val sealedClassMissingCases = WhenChecker.getSealedMissingCases(expression, bindingContext, sealedClassDescriptor) if (sealedClassMissingCases.isNotEmpty()) { report( CodeSmell( issue, Entity.from(expression), "When expression is missing cases: ${sealedClassMissingCases.joinToString()}. Either add " + "missing cases or a default `else` case." ) ) } } super.visitWhenExpression(expression) } }
apache-2.0
24df91fccbf4939e642d8b9b70a54f00
35.027027
132
0.634909
4.443333
false
false
false
false
bs616/Note
app/src/main/java/com/dev/bins/note/adapter/MainFragmentRecycleViewAdapter.kt
1
2352
package com.dev.bins.note.adapter import android.content.Context import android.content.Intent import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.ViewGroup import com.dev.bins.note.R import com.dev.bins.note.model.Note import com.dev.bins.note.ui.DetailActivity import java.text.SimpleDateFormat import java.util.* /** * Created by bin on 11/24/15. */ class MainFragmentRecycleViewAdapter(private val context: Context) : RecyclerView.Adapter<Holder>() { private val sdf: SimpleDateFormat internal var notes: MutableList<Note> init { sdf = SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss") notes = ArrayList() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder { val view = LayoutInflater.from(parent.context).inflate(R.layout.recycleview_item, parent, false) return Holder(view) } override fun onBindViewHolder(holder: Holder, position: Int) { val note = notes[position] val title = note.title if (title == "无标题") { holder.title.text = note.id.toString() } else { holder.title.text = title } holder.content.text = note.content val date = sdf.format(note.date) holder.time.text = date holder.cardView.setOnClickListener { val intent = Intent(context, DetailActivity::class.java) intent.putExtra("id", note.id) context.startActivity(intent) } } override fun getItemCount(): Int { return notes.size } fun add(data: List<Note>) { notes.clear() notes.addAll(data) notifyDataSetChanged() } // class Holder extends RecyclerView.ViewHolder{ // TextView title; // TextView content; // TextView time; // MaterialRippleLayout cardView; // // public Holder(View itemView) { // super(itemView); // title = (TextView) itemView.findViewById(R.id.title); // content = (TextView) itemView.findViewById(R.id.content); // time = (TextView) itemView.findViewById(R.id.time); // cardView = (MaterialRippleLayout) itemView.findViewById(R.id.cardView); // // } // } }
apache-2.0
f7dc40a6a3b17afdfa57888dd0121b27
29
104
0.623504
4.231465
false
false
false
false
ghonix/Problems
src/main/kotlin/MedianTwoSortedArrays.kt
1
1893
/** * https://leetcode.com/problems/median-of-two-sorted-arrays/#/description * Created by aghoneim on 4/18/17. */ class MedianTwoSortedArrays { fun findMedianSortedArrays(nums1: IntArray?, nums2: IntArray?): Double { var nums1 = nums1 var nums2 = nums2 if (nums1 == null) { nums1 = intArrayOf() } if (nums2 == null) { nums2 = intArrayOf() } val size = nums1.size + nums2.size return if (size > 0) { var firstMedian = 0 var secondMedian = 0 var i = 0 var j = 0 var medianIndex = 0 val middle = (size - 1) / 2 while (i < nums1.size || j < nums2.size) { var current = 0 if (i >= nums1.size) { current = nums2[j] j++ } else if (j >= nums2.size) { current = nums1[i] i++ } else if (nums1[i] < nums2[j]) { current = nums1[i] i++ } else { current = nums2[j] j++ } if (medianIndex == middle) { firstMedian = current } else if (medianIndex == middle + 1) { secondMedian = current } else if (medianIndex > middle) { break } medianIndex++ } if (size % 2 == 0) (firstMedian + secondMedian) / 2.0 else firstMedian.toDouble() } else { 0.0 } } companion object { @JvmStatic fun main(args: Array<String>) { val m = MedianTwoSortedArrays() println(m.findMedianSortedArrays(intArrayOf(0, 2, 3, 3), intArrayOf(4, 5))) } } }
apache-2.0
6c1dc000c3303ac60a6015e322796b86
30.566667
93
0.423666
4.216036
false
false
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/ui/adapter/BuddyNameAdapter.kt
1
3710
package com.boardgamegeek.ui.adapter import android.content.Context import android.view.View import android.view.ViewGroup import android.widget.* import com.boardgamegeek.R import com.boardgamegeek.entities.PlayerEntity import com.boardgamegeek.entities.UserEntity import com.boardgamegeek.extensions.inflate import com.boardgamegeek.extensions.loadThumbnailInList import com.boardgamegeek.extensions.setTextOrHide class BuddyNameAdapter(context: Context) : ArrayAdapter<BuddyNameAdapter.Result>(context, R.layout.autocomplete_player), Filterable { private var playerList = listOf<PlayerEntity>() private var userList = listOf<UserEntity>() private var resultList = listOf<Result>() class Result( val title: String, val subtitle: String, val username: String, val avatarUrl: String = "", ) { override fun toString() = username } override fun getCount() = resultList.size override fun getItem(index: Int) = resultList.getOrNull(index) override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { val view = convertView ?: parent.inflate(R.layout.autocomplete_player) val result = getItem(position) ?: return view view.findViewById<TextView>(R.id.player_title)?.setTextOrHide(result.title) view.findViewById<TextView>(R.id.player_subtitle)?.setTextOrHide(result.subtitle) view.findViewById<ImageView>(R.id.player_avatar)?.loadThumbnailInList(result.avatarUrl, R.drawable.person_image_empty) view.tag = result.title return view } fun addPlayers(list: List<PlayerEntity>) { playerList = list .filter { it.username.isNotBlank() } .sortedByDescending { it.playCount } .distinctBy { it.username } notifyDataSetChanged() } fun addUsers(list: List<UserEntity>) { userList = list.sortedBy { it.userName } notifyDataSetChanged() } override fun getFilter(): Filter = object : Filter() { override fun performFiltering(constraint: CharSequence?): FilterResults { val filter = constraint?.toString().orEmpty() val playerListFiltered = if (filter.isEmpty()) playerList else { playerList.filter { it.username.startsWith(filter, ignoreCase = true) } } val userListFiltered = if (filter.isEmpty()) userList else { userList.filter { it.userName.startsWith(filter, ignoreCase = true) } } val playerResults = playerListFiltered.map { player -> Result( player.name, player.username, player.username, player.avatarUrl, ) } val usernames = playerResults.map { it.username } val userResults = userListFiltered .asSequence() .filterNot { usernames.contains(it.userName) } .map { Result( it.fullName, it.userName, it.userName, it.avatarUrl, ) } return FilterResults().apply { values = playerResults + userResults count = (playerResults + userResults).size } } override fun publishResults(constraint: CharSequence?, results: FilterResults?) { @Suppress("UNCHECKED_CAST") resultList = results?.values as? List<Result> ?: emptyList() notifyDataSetChanged() } } }
gpl-3.0
6a4aed2212bcd63a1a6bc9c8286a463e
35.019417
133
0.604582
5.110193
false
false
false
false
WindSekirun/RichUtilsKt
demo/src/main/java/pyxis/uzuki/live/richutilskt/demo/set/NetworkSet.kt
1
2132
package pyxis.uzuki.live.richutilskt.demo.set import android.content.Context import pyxis.uzuki.live.richutilskt.demo.item.CategoryItem import pyxis.uzuki.live.richutilskt.demo.item.ExecuteItem import pyxis.uzuki.live.richutilskt.demo.item.generateExecuteItem import pyxis.uzuki.live.richutilskt.utils.* /** * RichUtilsKt * Class: NetworkSet * Created by Pyxis on 2017-11-09. * * Description: */ fun Context.getNetworkSet(): ArrayList<ExecuteItem> { val list = arrayListOf<ExecuteItem>() val checkNetwork = generateExecuteItem(CategoryItem.NETWORK, "checkNetwork", "get network connection check", "checkNetwork()", "RichUtils.checkNetwork(this)") { val message = when (checkNetwork()) { 2 -> "Wifi" 1 -> "Mobile" else -> "Not Connected" } toast("Connection status = $message") } list.add(checkNetwork) val isWifiConnected = generateExecuteItem(CategoryItem.NETWORK, "isWifiConnected", "get Wifi connection check", "isWifiConnected()", "RichUtils.isWifiConnected()") { toast("isWifiConnected ? = ${isWifiConnected()}") } list.add(isWifiConnected) val isMobileConnected = generateExecuteItem(CategoryItem.NETWORK, "isMobileConnected", "get Mobile connection check", "isMobileConnected()", "RichUtils.isMobileConnected()") { toast("isMobileConnected ? = ${isMobileConnected()}") } list.add(isMobileConnected) val isNotConnected = generateExecuteItem(CategoryItem.NETWORK, "isNotConnected", "get state of not connected", "isNotConnected()", "RichUtils.isNotConnected()") { toast("isNotConnected ? = ${isNotConnected()}") } list.add(isNotConnected) val isConnected = generateExecuteItem(CategoryItem.NETWORK, "isConnected", "get state of connected", "isConnected()", "RichUtils.isConnected()") { toast("isConnected ? = ${isConnected()}") } list.add(isConnected) return list }
apache-2.0
267e6822ab06463d43152ec99333b2c2
28.219178
90
0.640713
4.95814
false
false
false
false
ageery/kwicket
kwicket-wicket-bootstrap-core/src/main/kotlin/org/kwicket/agilecoders/wicket/core/ajax/markup/html/bootstrap/form/KFormGroup.kt
1
1693
package org.kwicket.agilecoders.wicket.core.ajax.markup.html.bootstrap.form import de.agilecoders.wicket.core.markup.html.bootstrap.form.FormGroup import org.apache.wicket.behavior.Behavior import org.apache.wicket.model.IModel import org.kwicket.component.init import org.kwicket.model.model open class KFormGroup( id: String, label: IModel<String> = "".model(), help: IModel<String> = "".model(), outputMarkupId: Boolean? = null, outputMarkupPlaceholderTag: Boolean? = null, visible: Boolean? = null, enabled: Boolean? = null, useFormComponentLabel: Boolean? = null, behaviors: List<Behavior>? = null ) : FormGroup(id, label, help) { constructor( id: String, label: IModel<String> = "".model(), help: IModel<String> = "".model(), outputMarkupId: Boolean? = null, outputMarkupPlaceholderTag: Boolean? = null, visible: Boolean? = null, enabled: Boolean? = null, useFormComponentLabel: Boolean? = null, behavior: Behavior ) : this( id = id, label = label, help = help, useFormComponentLabel = useFormComponentLabel, outputMarkupId = outputMarkupId, outputMarkupPlaceholderTag = outputMarkupPlaceholderTag, visible = visible, enabled = enabled, behaviors = listOf(behavior) ) init { init( outputMarkupId = outputMarkupId, outputMarkupPlaceholderTag = outputMarkupPlaceholderTag, visible = visible, enabled = enabled, behaviors = behaviors ) useFormComponentLabel?.let { this.useFormComponentLabel(it) } } }
apache-2.0
f60096abf411ee7c14220a64be8dfb6e
30.37037
75
0.642056
4.613079
false
false
false
false
Ruben-Sten/TeXiFy-IDEA
src/nl/hannahsten/texifyidea/util/General.kt
1
2277
package nl.hannahsten.texifyidea.util import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import java.util.regex.Pattern /** * Returns `1` when `true`, returns `0` when `false`. */ val Boolean.int: Int get() = if (this) 1 else 0 /** * Creates a pair of two objects, analogous to [to]. */ infix fun <T1, T2> T1.and(other: T2) = Pair(this, other) /** * Prints the object in default string presentation to the console. */ fun Any.print() = print(this) /** * Prints the object in default string presentation to the console including line feed. */ fun Any.println() = println(this) /** * Prints `message: OBJECT` to the console. */ infix fun Any.debug(message: Any) = print("$message: $this") /** * Prints `message: OBJECT` to the console including line feed. */ infix fun Any.debugln(message: Any) = println("$message: $this") /** * Executes the given run write action. */ fun runWriteAction(writeAction: () -> Unit) { ApplicationManager.getApplication().runWriteAction(writeAction) } fun runWriteCommandAction(project: Project, writeCommandAction: () -> Unit) { WriteCommandAction.runWriteCommandAction(project, writeCommandAction) } /** * Converts an [IntRange] to [TextRange]. */ fun IntRange.toTextRange() = TextRange(this.first, this.last + 1) /** * Get the length of an [IntRange]. */ val IntRange.length: Int get() = endInclusive - start /** * Converts the range to a range representation with the given seperator. * When the range has size 0, it will only print the single number. */ fun IntRange.toRangeString(separator: String = "-") = if (start == endInclusive) start else "$start$separator$endInclusive" /** * Shift the range to the right by the number of places given. */ fun IntRange.shiftRight(displacement: Int): IntRange { return (this.first + displacement)..(this.last + displacement) } /** * Converts a [TextRange] to [IntRange]. */ fun TextRange.toIntRange() = startOffset..endOffset /** * Easy access to [java.util.regex.Matcher.matches]. */ fun Pattern.matches(sequence: CharSequence?) = if (sequence != null) matcher(sequence).matches() else false
mit
aaf66fa29490f4dbedb616f511cdd9d0
26.445783
123
0.714097
3.745066
false
false
false
false
hartwigmedical/hmftools
paddle/src/main/kotlin/com/hartwig/hmftools/paddle/mutation/Mutations.kt
1
6236
package com.hartwig.hmftools.paddle.mutation import com.hartwig.hmftools.paddle.Impact import com.hartwig.hmftools.paddle.dnds.DndsMutation import com.hartwig.hmftools.paddle.dnds.DndsMutationComparator data class Mutations(val known: Int, val unknown: Int) { val total = known + unknown operator fun plus(other: Mutations): Mutations { return Mutations(known + other.known, unknown + other.unknown) } } data class MutationsGene( val gene: String, val synonymous: Int, val redundant: Int, val missense: Mutations, val nonsense: Mutations, val splice: Mutations, val inframe: Mutations, val frameshift: Mutations) { fun add(impact: Impact, known: Int, unknown: Int): MutationsGene { val additional = Mutations(known, unknown) return when (impact) { Impact.MISSENSE -> copy(missense = missense + additional) Impact.NONSENSE -> copy(nonsense = nonsense + additional) Impact.SPLICE -> copy(splice = splice + additional) Impact.INFRAME -> copy(inframe = inframe + additional) Impact.FRAMESHIFT -> copy(frameshift = frameshift + additional) else -> throw IllegalStateException("Unexpected impact: $impact") } } operator fun plus(count: MutationsGene): MutationsGene { if (gene != count.gene) { throw IllegalArgumentException("Incompatible genes: $gene != ${count.gene}") } return MutationsGene(gene, synonymous + count.synonymous, redundant + count.redundant, missense + count.missense, nonsense + count.nonsense, splice + count.splice, inframe + count.inframe, frameshift + count.frameshift ) } companion object { private val tsgComparator = DndsMutationComparator { x -> x.isKnownOncoDriver } private val oncoComparator = DndsMutationComparator { x -> x.isKnownTsgDriver } private val emptyCount = Mutations(0, 0) private val empty = MutationsGene("empty", 0, 0, emptyCount, emptyCount, emptyCount, emptyCount, emptyCount) fun oncoGeneMutations(mutations: List<DndsMutation>): List<MutationsGene> { return summary(mutations, this::oncoSampleSummary) } fun tsgGeneMutations(mutations: List<DndsMutation>): List<MutationsGene> { return summary(mutations, this::tsgSampleSummary) } internal fun oncoSampleSummary(gene: String, sampleMutations: List<DndsMutation>): MutationsGene { fun Boolean.toInt() = if (this) 1 else 0 val synonymous = sampleMutations.filter { x -> x.impact == Impact.SYNONYMOUS }.count() val filteredAndSorted = sampleMutations.filter { x -> x.impact != Impact.UNKNOWN && x.impact != Impact.SYNONYMOUS }.sortedWith(oncoComparator) if (filteredAndSorted.isEmpty()) { return empty.copy(gene = gene, synonymous = synonymous) } val worst = filteredAndSorted[0] val redundant = filteredAndSorted.size - 1 val isKnown = worst.isKnownOncoDriver val isUnknown = !isKnown val result = empty.copy(gene = gene, synonymous = synonymous, redundant = redundant) return result.add(worst.impact, isKnown.toInt(), isUnknown.toInt()) } internal fun tsgSampleSummary(gene: String, sampleMutations: List<DndsMutation>): MutationsGene { fun Boolean.toInt() = if (this) 1 else 0 val synonymous = sampleMutations.filter { x -> x.impact == Impact.SYNONYMOUS }.count() val filteredAndSorted = sampleMutations.filter { x -> x.impact != Impact.UNKNOWN && x.impact != Impact.SYNONYMOUS }.sortedWith(tsgComparator) if (filteredAndSorted.isEmpty()) { return empty.copy(gene = gene, synonymous = synonymous) } val worst = filteredAndSorted[0] val isKnown = worst.isKnownTsgDriver val isUnknown = !isKnown val isMultiHit = !isKnown && filteredAndSorted.size > 1 val redundant = filteredAndSorted.size - 1 - isMultiHit.toInt() var result = empty.copy(gene = gene, synonymous = synonymous, redundant = redundant) result = result.add(worst.impact, isKnown.toInt(), isUnknown.toInt()) if (isMultiHit) { val secondWorst = filteredAndSorted[1] result = result.add(secondWorst.impact, 0, 1) } return result } private fun summary(mutations: List<DndsMutation>, sampleSummary: (String, List<DndsMutation>) -> MutationsGene): List<MutationsGene> { val result = mutableListOf<MutationsGene>() for (geneMutations in mutations.sortedPartition { x -> x.gene }) { val gene = geneMutations[0].gene result.add(geneSummary(gene, geneMutations, sampleSummary)) } return result } private fun geneSummary(gene: String, geneMutations: List<DndsMutation>, sampleSummary: (String, List<DndsMutation>) -> MutationsGene): MutationsGene { var result = empty.copy(gene = gene) for (sampleMutations in geneMutations.sortedPartition { x -> x.sample }) { result += sampleSummary(gene, sampleMutations) } return result } private fun List<DndsMutation>.sortedPartition(key: (DndsMutation) -> String): List<List<DndsMutation>> { val result = mutableListOf<List<DndsMutation>>() val sorted = this.sortedBy { x -> key(x) } var currentKey = "" var keyMutations = mutableListOf<DndsMutation>() for (mutation in sorted) { if (key(mutation) != currentKey) { if (keyMutations.isNotEmpty()) { result.add(keyMutations) } keyMutations = mutableListOf() currentKey = key(mutation) } keyMutations.add(mutation) } if (keyMutations.isNotEmpty()) { result.add(keyMutations) } return result } } }
gpl-3.0
5e3aed1fc350b265ecef7ac6d5665c45
42.922535
159
0.618987
4.35171
false
false
false
false
benkyokai/tumpaca
app/src/main/kotlin/com/tumpaca/tp/fragment/DashboardFragment.kt
1
6436
package com.tumpaca.tp.fragment; import android.content.BroadcastReceiver import android.os.Bundle import android.support.v4.view.ViewPager import android.util.Log import android.view.* import android.widget.ImageButton import android.widget.TextView import android.widget.Toast import com.tumblr.jumblr.types.Post import com.tumpaca.tp.R import com.tumpaca.tp.model.PostList import com.tumpaca.tp.model.TPRuntime import com.tumpaca.tp.util.* class DashboardFragment : FragmentBase() { companion object { const val TAG = "DashboardFragment" private const val OFFSCREEN_PAGE_LIMIT = 4 } var postList: PostList? = null var likeButton: ImageButton? = null var isFabOpen = false var viewPager: ViewPager? = null var dashboardAdapter: DashboardPageAdapter? = null var changedListener: PostList.ChangedListener? = null var networkReceiver: BroadcastReceiver? = null var currentPost: Post? = null get() = postList?.get(viewPager!!.currentItem) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.fr_dashboard, container, false) val page = view.findViewById<TextView>(R.id.page) val postCount = view.findViewById<TextView>(R.id.post_count) (view.findViewById<ViewPager>(R.id.view_pager)).let { viewPager = it it.offscreenPageLimit = OFFSCREEN_PAGE_LIMIT it.addOnPageChangeListener(object : ViewPager.OnPageChangeListener { override fun onPageScrollStateChanged(state: Int) { } override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) { page.text = "${position + 1}" postCount.text = "${postList?.size}" } override fun onPageSelected(position: Int) { toggleLikeButton(postList?.get(position)!!) } }) } // PostList と ViewPage のバインド postList = TPRuntime.tumblrService.postList val settingsButton = view.findViewById<View>(R.id.settings_button) settingsButton.setOnClickListener { val ft = fragmentManager.beginTransaction() ft.addToBackStack(null) ft.replace(R.id.fragment_container, SettingsFragment()) ft.commit() } if (postList == null) { // postListがnullなら何も表示しない return view } changedListener = object : PostList.ChangedListener { override fun onChanged() { postCount.text = postList?.size.toString() } } postList?.addListeners(changedListener!!) dashboardAdapter = DashboardPageAdapter(childFragmentManager, postList!!) viewPager?.adapter = dashboardAdapter dashboardAdapter?.onBind() // Like (view.findViewById<ImageButton>(R.id.like_button)).let { likeButton = it it.setOnClickListener { doLike() } } // reblog val reblogButton = view.findViewById<View>(R.id.reblog_button) reblogButton.setOnClickListener { doReblog() } // ダッシュボードをロードしようとした時点でネットワークに接続できない場合、 // ネットワークが復活したらダッシュボードを丸々リロードする // TODO: これはすごくイケてないので、activityを殺さずに表示を更新できるようにする // onDestroyView() で networkReceiver を登録解除していることに注意 if (!context.isOnline()) { Toast.makeText(context, R.string.offline_toast, Toast.LENGTH_SHORT).show() networkReceiver = context.onNetworkRestored { activity.finish() activity.startActivity(activity.intent) } } return view } override fun onResume() { super.onResume() getActionBar()?.show() } override fun onDestroyView() { super.onDestroyView() dashboardAdapter?.onUnbind() changedListener?.let { postList?.removeListeners(it) } networkReceiver?.let { try { context.unregisterReceiver(it) } catch (e: Throwable) { Log.d(TAG, "Receiver was not registered", e) } } } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.menu_dashboard, menu) super.onCreateOptionsMenu(menu, inflater) } private fun doLike() { val likeMsg = resources.getString(R.string.liked_result) val unlikeMsg = resources.getString(R.string.unliked_result) val errorMsg = resources.getString(R.string.error_like) currentPost?.likeAsync({ post, result -> if (result) { // ここまで来ると違うPostが表示されているかもしれないのでチェック currentPost?.let { if (it == post) { toggleLikeButton(post) } } if (post.isLiked) { TPToastManager.show(likeMsg) } else { TPToastManager.show(unlikeMsg) } } else { TPToastManager.show(errorMsg) } }) } private fun doReblog() { val blogName = TPRuntime.tumblrService.user?.blogs?.first()?.name!! val msg = resources.getString(R.string.reblogged_result) val errorMsg = resources.getString(R.string.error_reblog) currentPost ?.reblogAsync(blogName, null) ?.subscribe({ _ -> TPToastManager.show(msg) }) { _ -> TPToastManager.show(errorMsg) } } private fun toggleLikeButton(post: Post) { val state = android.R.attr.state_checked * if (post.isLiked) 1 else -1 likeButton?.setImageState(intArrayOf(state), false) } }
gpl-3.0
04441b44c2f140a14b80f666ae9c2e04
32.102703
116
0.596506
4.546399
false
false
false
false
AoEiuV020/PaNovel
reader/src/main/java/cc/aoeiuv020/reader/simple/ImageViewHolder.kt
1
2185
package cc.aoeiuv020.reader.simple import android.content.Context import android.net.Uri import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import cc.aoeiuv020.reader.* import kotlinx.android.synthetic.main.simple_image_item.view.* import org.jetbrains.anko.dip /** * Created by AoEiuV020 on 2018.06.11-11:05:03. */ internal class ImageViewHolder( itemView: View, private val prAdapter: PageRecyclerAdapter ) : PageRecyclerAdapter.ViewHolder(itemView) { companion object { fun create(ctx: Context, parent: ViewGroup, prAdapter: PageRecyclerAdapter): ImageViewHolder { val view = LayoutInflater.from(ctx).inflate(R.layout.simple_image_item, parent, false) return ImageViewHolder(view, prAdapter) } } private val ctx: Context = itemView.context private val tvPage = itemView.tvPage private val ivImage = itemView.ivImage fun setImage(reader: INovelReader, index: Int, image: Image) { tvPage.text = (index + 1).toString() tvPage.setTextColor(reader.config.textColor) ivImage.apply { post { layoutParams = (layoutParams as ViewGroup.MarginLayoutParams).apply { setMargins((prAdapter.mLeftSpacing.toFloat() / 100 * itemView.width).toInt(), topMargin, (prAdapter.mRightSpacing.toFloat() / 100 * itemView.width).toInt(), ctx.dip(prAdapter.mParagraphSpacing)) } } } itemView.layoutParams = itemView.layoutParams.apply { height = ViewGroup.LayoutParams.MATCH_PARENT } ivImage.setImageDrawable(null) tvPage.show() ivImage.tag = index prAdapter.reader.requester.requestImage(image) { file -> if (ivImage.tag != index) { return@requestImage } tvPage.hide() itemView.layoutParams = itemView.layoutParams.apply { height = ViewGroup.LayoutParams.WRAP_CONTENT } ivImage.setImageURI(Uri.fromFile(file)) } } }
gpl-3.0
11865b54a46de3cfe2a279a27b1089e3
34.836066
102
0.626545
4.6
false
false
false
false
soniccat/android-taskmanager
quizlet_repository/src/main/java/com/example/alexeyglushkov/quizletservice/deserializers/QuizletUserDeserializer.kt
1
1361
package com.example.alexeyglushkov.quizletservice.deserializers import com.example.alexeyglushkov.jacksonlib.CustomDeserializer import com.example.alexeyglushkov.quizletservice.entities.QuizletUser import com.fasterxml.jackson.core.JsonParser import com.fasterxml.jackson.databind.DeserializationContext import java.io.IOException /** * Created by alexeyglushkov on 27.03.16. */ class QuizletUserDeserializer(vc: Class<*>) : CustomDeserializer<QuizletUser>(vc) { override fun createObject(): QuizletUser { return QuizletUser() } @Throws(IOException::class) protected override fun handle(p: JsonParser, ctxt: DeserializationContext, user: QuizletUser): Boolean { var isHandled = false val name = p.currentName if (name == "id") { user.id = _parseLongPrimitive(p, ctxt) isHandled = true } else if (name == "username") { user.name = _parseString(p, ctxt) isHandled = true } else if (name == "profile_image") { user.imageUrl = _parseString(p, ctxt) isHandled = true } else if (name == "account_type") { user.type = _parseString(p, ctxt) isHandled = true } return isHandled } companion object { private const val serialVersionUID = 4365096740984693871L } }
mit
169b35736ee72ed08da4e3b0c7c50693
33.05
108
0.65687
4.293375
false
false
false
false
goodwinnk/intellij-community
uast/uast-java/src/org/jetbrains/uast/java/expressions/JavaUAnnotationCallExpression.kt
2
2208
/* * Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package org.jetbrains.uast.java.expressions import com.intellij.psi.PsiAnnotation import com.intellij.psi.PsiMethod import com.intellij.psi.PsiType import com.intellij.psi.ResolveResult import org.jetbrains.uast.* import org.jetbrains.uast.java.JavaAbstractUExpression import org.jetbrains.uast.java.JavaConverter import org.jetbrains.uast.java.JavaUAnnotation import org.jetbrains.uast.java.lz import org.jetbrains.uast.visitor.UastVisitor class JavaUAnnotationCallExpression( override val psi: PsiAnnotation, givenParent: UElement? ) : JavaAbstractUExpression(givenParent), UCallExpressionEx, UMultiResolvable { val uAnnotation: JavaUAnnotation by lz { JavaUAnnotation(psi, this) } override val returnType: PsiType? get() = uAnnotation.qualifiedName?.let { PsiType.getTypeByName(it, psi.project, psi.resolveScope) } override val kind: UastCallKind get() = UastCallKind.CONSTRUCTOR_CALL override val methodName: String? get() = null override val receiver: UExpression? get() = null override val receiverType: PsiType? get() = null override val methodIdentifier: UIdentifier? get() = null override val classReference: UReferenceExpression? by lz { psi.nameReferenceElement?.let { ref -> JavaConverter.convertReference(ref, this, null) as? UReferenceExpression } } override val valueArgumentCount: Int get() = psi.parameterList.attributes.size override val valueArguments: List<UNamedExpression> by lz { uAnnotation.attributeValues } override fun getArgumentForParameter(i: Int): UExpression? = valueArguments.getOrNull(i) override fun accept(visitor: UastVisitor) { visitor.visitCallExpression(this) uAnnotation.accept(visitor) visitor.afterVisitCallExpression(this) } override val typeArgumentCount: Int = 0 override val typeArguments: List<PsiType> = emptyList() override fun resolve(): PsiMethod? = uAnnotation.resolve()?.constructors?.firstOrNull() override fun multiResolve(): Iterable<ResolveResult> = uAnnotation.multiResolve() }
apache-2.0
4947e20225549a17a6b4587e286f418d
30.098592
140
0.766304
4.648421
false
false
false
false
DemonWav/IntelliJBukkitSupport
src/main/kotlin/platform/mixin/config/reference/MixinPackage.kt
1
2404
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.config.reference import com.demonwav.mcdev.platform.mixin.util.MixinConstants.Annotations.MIXIN import com.demonwav.mcdev.util.packageName import com.demonwav.mcdev.util.reference.PackageNameReferenceProvider import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiClass import com.intellij.psi.PsiElement import com.intellij.psi.PsiPackage import com.intellij.psi.search.PackageScope import com.intellij.psi.search.searches.AnnotatedElementsSearch import com.intellij.util.ArrayUtil import com.intellij.util.PlatformIcons object MixinPackage : PackageNameReferenceProvider() { override fun collectVariants(element: PsiElement, context: PsiElement?): Array<Any> { val mixinAnnotation = JavaPsiFacade.getInstance(element.project).findClass(MIXIN, element.resolveScope) ?: return ArrayUtil.EMPTY_OBJECT_ARRAY return if (context == null) { findPackages(mixinAnnotation, element) } else { findChildrenPackages(mixinAnnotation, element, context as PsiPackage) } } private fun findPackages(mixinAnnotation: PsiClass, element: PsiElement): Array<Any> { val packages = HashSet<String>() val list = ArrayList<LookupElementBuilder>() for (mixin in AnnotatedElementsSearch.searchPsiClasses(mixinAnnotation, element.resolveScope)) { val packageName = mixin.packageName ?: continue if (packages.add(packageName)) { list.add(LookupElementBuilder.create(packageName).withIcon(PlatformIcons.PACKAGE_ICON)) } val topLevelPackage = packageName.substringBefore('.') if (packages.add(topLevelPackage)) { list.add(LookupElementBuilder.create(topLevelPackage).withIcon(PlatformIcons.PACKAGE_ICON)) } } return list.toArray() } private fun findChildrenPackages(mixinAnnotation: PsiClass, element: PsiElement, context: PsiPackage): Array<Any> { val scope = PackageScope(context, true, true).intersectWith(element.resolveScope) return collectSubpackages(context, AnnotatedElementsSearch.searchPsiClasses(mixinAnnotation, scope)) } }
mit
d4762791d8c2a6313eea952295843854
38.409836
119
0.730865
4.946502
false
false
false
false
pennlabs/penn-mobile-android
PennMobile/src/main/java/com/pennapps/labs/pennmobile/components/sneaker/Sneaker.kt
1
15538
package com.pennapps.labs.pennmobile.components.sneaker import android.app.Activity import android.content.Context import android.graphics.Color import android.graphics.Typeface import android.graphics.drawable.Drawable import android.os.Build import android.os.Handler import android.view.Gravity import android.view.View import android.view.ViewGroup import android.view.animation.AnimationUtils import android.widget.LinearLayout import androidx.annotation.DrawableRes import androidx.appcompat.widget.ViewUtils import androidx.coordinatorlayout.widget.CoordinatorLayout import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import androidx.lifecycle.LifecycleObserver import com.google.android.material.appbar.AppBarLayout import com.pennapps.labs.pennmobile.R import com.pennapps.labs.pennmobile.components.sneaker.intf.OnSneakerClickListener import com.pennapps.labs.pennmobile.components.sneaker.intf.OnSneakerDismissListener /** * Sneaker is a third party replacement for android's native toasts. * Original project can be found here: https://github.com/Hamadakram/Sneaker * Created by Hammad Akram on 5/24/2017. * * Modified for PennMobile by Davies Lumumba on 7/25/2020 * */ class Sneaker(private var context: Context) : View.OnClickListener, LifecycleObserver { private val DEFAULT_VALUE = -100000 private var mIconDrawable: Drawable? = null private var mBackgroundColor = DEFAULT_VALUE private var mHeight = DEFAULT_VALUE private var mIconColorFilterColor = DEFAULT_VALUE private var mIconSize = 24 private var mTitle = "" private var mMessage = "" private var mTitleColor = DEFAULT_VALUE private var mMessageColor = DEFAULT_VALUE private var mAutoHide = true private var mDuration = 3000 private var mIsCircular = false private var mListener: OnSneakerClickListener? = null private var mDismissListener: OnSneakerDismissListener? = null private var mTypeFace: Typeface? = null private var mCornerRadius = DEFAULT_VALUE private var mMargin = DEFAULT_VALUE private var targetView: ViewGroup? = null private var isActivity: Boolean = false private val sneakerView by lazy { SneakerView(context) } companion object { /** * Create Sneaker instance * * @param activity * @return Sneaker instance */ @JvmStatic fun with(activity: Activity): Sneaker { return Sneaker(activity).also { it.setTargetView(activity) } } /** * Create Sneaker instance * * @param fragment * @return Sneaker instance */ @JvmStatic fun with(fragment: Fragment): Sneaker { return Sneaker(fragment.requireContext()).also { it.setTargetView(fragment) } } /** * Create Sneaker instance * * @param viewGroup * @return Sneaker instance */ @JvmStatic fun with(viewGroup: ViewGroup): Sneaker { return Sneaker(viewGroup.context).also { it.setTargetView(viewGroup) } } } private fun setTargetView(targetView: Any) { this.targetView = when (targetView) { is Activity -> { isActivity = true targetView.window?.decorView as ViewGroup } is Fragment -> targetView.view as ViewGroup is ViewGroup -> targetView else -> null } } /** * Hides the sneaker */ fun hide() { removeView(sneakerView) mDismissListener?.onDismiss() } /** * Sets the title of the sneaker * * @param title string value of title * @return */ fun setTitle(title: String): Sneaker { mTitle = title return this.also { mTitle = title } } /** * Sets the title of the sneaker with color * * @param title string value of title * @param color Color resource for title text * @return */ fun setTitle(title: String, color: Int): Sneaker { mTitle = title mTitleColor = try { ContextCompat.getColor(context, color) } catch (e: Exception) { color } return this } /** * Sets the message to sneaker * * @param message String value of message * @return */ fun setMessage(message: String): Sneaker { mMessage = message return this } /** * Sets the message to sneaker with color * * @param message String value of message * @param color Color resource for message text * @return */ fun setMessage(message: String, color: Int): Sneaker { mMessage = message mMessageColor = try { ContextCompat.getColor(context, color) } catch (e: Exception) { color } return this } /** * Sets the icon to sneaker * * @param icon Icon resource for sneaker * @return */ fun setIcon(@DrawableRes icon: Int): Sneaker { setIcon(icon, DEFAULT_VALUE, false) return this } /** * Sets the icon to sneaker * * @param icon Icon drawable for sneaker * @return */ fun setIcon(icon: Drawable): Sneaker { setIcon(icon, DEFAULT_VALUE, false) return this } /** * Sets the icon to sneaker with circular option * * @param icon * @param isCircular If icon is round or not * @return */ fun setIcon(@DrawableRes icon: Int, isCircular: Boolean): Sneaker { setIcon(icon, DEFAULT_VALUE, isCircular) return this } /** * Sets the icon to sneaker with circular option * * @param icon * @param isCircular If icon is round or not * @return */ fun setIcon(icon: Drawable, isCircular: Boolean): Sneaker { setIcon(icon, DEFAULT_VALUE, isCircular) return this } fun setIcon(@DrawableRes icon: Int, tintColor: Int): Sneaker { setIcon(icon, tintColor, false) return this } fun setIcon(icon: Drawable, tintColor: Int): Sneaker { setIcon(icon, tintColor, false) return this } /** * Sets the icon to sneaker with circular option and icon tint * * @param icon * @param tintColor Icon tint color * @param isCircular If icon is round or not * @return */ fun setIcon(@DrawableRes icon: Int, tintColor: Int, isCircular: Boolean): Sneaker { mIconDrawable = ContextCompat.getDrawable(context, icon) mIsCircular = isCircular mIconColorFilterColor = Utils.getColor(context, tintColor) return this } /** * Sets the icon to sneaker with circular option and icon tint * * @param icon * @param tintColor Icon tint color * @param isCircular If icon is round or not * @return */ fun setIcon(icon: Drawable, tintColor: Int, isCircular: Boolean): Sneaker { mIconDrawable = icon mIsCircular = isCircular mIconColorFilterColor = Utils.getColor(context, tintColor) return this } /** * Sets the size of the icon. * * @param size New icon size. */ fun setIconSize(size: Int): Sneaker { mIconSize = size return this } /** * Sets the corner radius for round corner sneaker. * * @param radius Corner radius. */ fun setCornerRadius(radius: Int): Sneaker { setCornerRadius(radius, DEFAULT_VALUE) return this } /** * Sets the corner radius for round corner sneaker with margin. * * @param radius Corner radius. * @param margin margin. */ fun setCornerRadius(radius: Int, margin: Int): Sneaker { mCornerRadius = radius mMargin = margin return this } /** * Disable/Enable auto hiding sneaker * * @param autoHide * @return */ fun autoHide(autoHide: Boolean): Sneaker { mAutoHide = autoHide return this } /** * Sets the height to sneaker * * @param height Height value for sneaker * @return */ fun setHeight(height: Int): Sneaker { mHeight = height return this } /** * Sets the duration for sneaker. * After this duration sneaker will disappear * * @param duration * @return */ fun setDuration(duration: Int): Sneaker { mDuration = duration return this } /** * Sets the click listener to sneaker * * @param listener * @return */ fun setOnSneakerClickListener(listener: OnSneakerClickListener): Sneaker { mListener = listener return this } /** * Sets the dismiss listener to sneaker */ fun setOnSneakerDismissListener(listener: OnSneakerDismissListener): Sneaker { mDismissListener = listener return this } /** * Set font for title and message * * @param typeface * @return */ fun setTypeface(typeface: Typeface): Sneaker { mTypeFace = typeface return this } /** * Shows sneaker with custom color * * @param backgroundColor Color resource for sneaker background color */ fun sneak(backgroundColor: Int) { mBackgroundColor = try { ContextCompat.getColor(context, backgroundColor) } catch (e: Exception) { backgroundColor } sneakView() } /** * Shows warning sneaker with fixed icon, background color and icon color. * Icons, background and text colors for this are not customizable */ fun sneakWarning() { mBackgroundColor = Color.parseColor("#ffc100") mTitleColor = Color.parseColor("#000000") mMessageColor = Color.parseColor("#000000") mIconColorFilterColor = Color.parseColor("#000000") mIconDrawable = ContextCompat.getDrawable(context, R.drawable.ic_warning) sneakView() } /** * Shows error sneaker with fixed icon, background color and icon color. * Icons, background and text colors for this are not customizable */ fun sneakError() { mBackgroundColor = Color.parseColor("#ff0000") mTitleColor = Color.parseColor("#FFFFFF") mMessageColor = Color.parseColor("#FFFFFF") mIconColorFilterColor = Color.parseColor("#FFFFFF") mIconDrawable = ContextCompat.getDrawable(context, R.drawable.ic_error) sneakView() } /** * Shows success sneaker with fixed icon, background color and icon color. * Icons, background and text colors for this are not customizable */ fun sneakSuccess() { mBackgroundColor = Color.parseColor("#2bb600") mTitleColor = Color.parseColor("#FFFFFF") mMessageColor = Color.parseColor("#FFFFFF") mIconColorFilterColor = Color.parseColor("#FFFFFF") mIconDrawable = ContextCompat.getDrawable(context, R.drawable.ic_success) sneakView() } /** * Creates the view and sneaks in */ private fun sneakView() { // Main layout targetView?.let { val layoutParams = CoordinatorLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) if (mMargin != DEFAULT_VALUE) { val margin = Utils.convertToDp(context, mMargin.toFloat()) layoutParams.setMargins(margin, margin, margin, margin) } layoutParams.behavior = AppBarLayout.ScrollingViewBehavior() layoutParams.anchorGravity = Gravity.BOTTOM with(sneakerView) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) elevation = 6f this.layoutParams = layoutParams orientation = LinearLayout.HORIZONTAL gravity = Gravity.CENTER_VERTICAL setPadding(46, if (isActivity) Utils.getStatusBarHeight(it) else 0, 46, 0) setBackground(mBackgroundColor, mCornerRadius) setIcon(mIconDrawable, Utils.convertToDp(context, mIconSize.toFloat()), mIconColorFilterColor) setTextContent(mTitle, mTitleColor, mMessage, mMessageColor, mTypeFace) setOnClickListener(this@Sneaker) } removeExistingSneakerView(it) it.addView(sneakerView, 0) sneakerView.startAnimation(AnimationUtils.loadAnimation(context, R.anim.popup_show)) if (mAutoHide) { val handler = Handler() handler.removeCallbacks { } handler.postDelayed({ removeView(sneakerView) mDismissListener?.onDismiss() }, mDuration.toLong()) } } } fun sneakCustom(layout: View): Sneaker { sneakerView.setCustomView(layout) val layoutParams = CoordinatorLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) layoutParams.behavior = AppBarLayout.ScrollingViewBehavior() layoutParams.anchorGravity = Gravity.BOTTOM layoutParams.bottomMargin = Utils.convertToDp(context, 52f) with(sneakerView) { this.layoutParams = layoutParams } targetView?.let { removeExistingSneakerView(it) it.addView(sneakerView) sneakerView.startAnimation(AnimationUtils.loadAnimation(context, R.anim.popup_show)) if (mAutoHide) { val handler = Handler() handler.removeCallbacks { } handler.postDelayed({ removeView(sneakerView) mDismissListener?.onDismiss() }, mDuration.toLong()) } } return this } /** * Gets the existing sneaker and removes before adding new one * * @param parent */ private fun removeExistingSneakerView(parent: ViewGroup) { parent.findViewById<LinearLayout>(R.id.mainLayout)?.let { removeView(it, false) } } private fun removeView(view: View?, animate: Boolean = true) { view?.let { if (animate) it.startAnimation(AnimationUtils.loadAnimation(context, R.anim.popup_hide)) targetView?.removeView(it) } } /** * Sneaker on click * * @param view */ override fun onClick(view: View) { mListener?.onSneakerClick(view) removeView(sneakerView) } fun getView(): ViewGroup = sneakerView }
mit
6c693838b520c5b29c122b721179fcb9
27.938343
110
0.585017
4.776514
false
false
false
false
openstreetview/android
app/src/androidTest/java/com/telenav/osv/ui/fragment/settings/ResolutionViewModelTest.kt
1
3295
package com.telenav.osv.ui.fragment.settings import android.Manifest import android.content.Context import android.view.View import android.widget.RadioGroup import androidx.preference.PreferenceViewHolder import androidx.test.InstrumentationRegistry import androidx.test.annotation.UiThreadTest import androidx.test.rule.GrantPermissionRule import com.telenav.osv.R import com.telenav.osv.application.ApplicationPreferences import com.telenav.osv.application.KVApplication import com.telenav.osv.application.PreferenceTypes import com.telenav.osv.ui.fragment.settings.custom.RadioGroupPreference import com.telenav.osv.ui.fragment.settings.viewmodel.ResolutionViewModel import com.telenav.osv.utils.Size import org.junit.Assert import org.junit.Before import org.junit.Test import org.mockito.MockitoAnnotations class ResolutionViewModelTest { private lateinit var viewModel: ResolutionViewModel private lateinit var context: Context private lateinit var appPrefs: ApplicationPreferences @Before fun setUp() { GrantPermissionRule.grant(Manifest.permission.CAMERA) context = InstrumentationRegistry.getTargetContext() val app = InstrumentationRegistry.getTargetContext().applicationContext as KVApplication MockitoAnnotations.initMocks(this) appPrefs = ApplicationPreferences(app) viewModel = ResolutionViewModel(app, appPrefs) } @Test @UiThreadTest fun testResolutionClick() { val preference = getGroupPreference() val checkedChangeListener = preference.onCheckedChangeListener var preferenceChanged = false preference.onCheckedChangeListener = (RadioGroup.OnCheckedChangeListener { radioGroup, i -> preferenceChanged = true checkedChangeListener.onCheckedChanged(radioGroup, i) }) preference.onBindViewHolder(PreferenceViewHolder.createInstanceForTests(View.inflate(context, R.layout.settings_item_radio_group, null))) preference.radioButtonList[0].isChecked = false preference.radioButtonList[0].isChecked = true Assert.assertTrue(preferenceChanged) val size = preference.radioButtonList[0].tag as Size Assert.assertEquals(size.width, appPrefs.getIntPreference(PreferenceTypes.K_RESOLUTION_WIDTH)) Assert.assertEquals(size.height, appPrefs.getIntPreference(PreferenceTypes.K_RESOLUTION_HEIGHT)) } @Test @UiThreadTest fun testStoredResolutionCheckedWhenDisplayingTheList() { val preference = getGroupPreference() for (radioButton in preference.radioButtonList) { if (radioButton.isChecked) { val size = radioButton.tag as Size Assert.assertEquals(size.width, appPrefs.getIntPreference(PreferenceTypes.K_RESOLUTION_WIDTH)) Assert.assertEquals(size.height, appPrefs.getIntPreference(PreferenceTypes.K_RESOLUTION_HEIGHT)) return } } Assert.assertTrue(false) } private fun getGroupPreference(): RadioGroupPreference { viewModel.settingsDataObservable viewModel.start() val settingsGroups = viewModel.settingsDataObservable.value!! return settingsGroups[0].getPreference(context) as RadioGroupPreference } }
lgpl-3.0
702b07ce1811d6f8896bb858967cb192
40.721519
145
0.752352
5.272
false
true
false
false
mayank408/susi_android
app/src/main/java/org/fossasia/susi/ai/rest/responses/others/LocationResponse.kt
1
475
package org.fossasia.susi.ai.rest.responses.others /** * <h1>Kotlin Data class to parse retrofit response from location client.</h1> * * Created by chiragw15 on 6/12/16. */ class LocationResponse ( var ip: String? = null, var hostname: String? = null, var city: String? = null, var region: String? = null, var country: String? = null, var loc: String = "", var org: String? = null, var postal: String? )
apache-2.0
b928846fcedc72e9fd6471c221f94e35
22.8
78
0.597895
3.598485
false
false
false
false
codeka/wwmmo
server/src/main/kotlin/au/com/codeka/warworlds/server/store/StatsStore.kt
1
4468
package au.com.codeka.warworlds.server.store import au.com.codeka.warworlds.common.proto.Account import au.com.codeka.warworlds.common.proto.DeviceInfo import au.com.codeka.warworlds.common.proto.LoginRequest import au.com.codeka.warworlds.server.proto.DailyStat import au.com.codeka.warworlds.server.proto.LoginEvent import au.com.codeka.warworlds.server.store.base.BaseStore import org.joda.time.DateTime import java.util.* /** * Store for various stats that we want to keep track of. */ class StatsStore internal constructor(fileName: String) : BaseStore(fileName) { /** Store the given [LoginRequest] */ fun addLoginEvent(loginRequest: LoginRequest?, account: Account) { val now = System.currentTimeMillis() newWriter() .stmt("INSERT INTO login_events (" + "timestamp, day, empire_id, device_id, email_addr, device_info) " + "VALUES (?, ?, ?, ?, ?, ?)") .param(0, now) .param(1, StatsHelper.timestampToDay(now)) .param(2, account.empire_id) .param(3, loginRequest!!.device_info.device_id) .param(4, account.email) .param(5, loginRequest.device_info.encode()) .execute() } /** Gets the most recent `num` login events. */ fun getRecentLogins(num: Int): List<LoginEvent> { val loginEvents: ArrayList<LoginEvent> = ArrayList<LoginEvent>() newReader() .stmt("SELECT timestamp, day, empire_id, email_addr, device_info FROM login_events ORDER BY timestamp DESC") .query().use { res -> while (res.next()) { loginEvents.add(LoginEvent( timestamp = res.getLong(0), day = res.getInt(1), empire_id = res.getLong(2), email_addr = res.getStringOrNull(3), device_info = DeviceInfo.ADAPTER.decode(res.getBytes(4)))) if (loginEvents.size >= num) { break } } } return loginEvents } /** Get the [DailyStat] for the last `num` days. */ fun getDailyStats(num: Int): Map<Int, DailyStat> { val dt = DateTime.now().minusDays(num + 7) // 7 more to calculate the 7da correctly var currDay = StatsHelper.dateTimeToDay(dt) val lastEmpires = ArrayList<MutableSet<Long>>() lastEmpires.add(HashSet()) val dailyStats: HashMap<Int, DailyStat> = HashMap<Int, DailyStat>() newReader() .stmt("SELECT day, empire_id FROM login_events WHERE day >= ? ORDER BY day ASC") .param(0, currDay) .query().use { res -> while (res.next()) { val day = res.getInt(0) val empireId = res.getLong(1) if (day == currDay) { lastEmpires[0].add(empireId) } else { appendStats(dailyStats, currDay, lastEmpires) currDay = day lastEmpires.add(0, HashSet()) lastEmpires[0].add(empireId) } } appendStats(dailyStats, currDay, lastEmpires) } return dailyStats } private fun appendStats( dailyStats: MutableMap<Int, DailyStat>, day: Int, lastEmpires: ArrayList<MutableSet<Long>>) { val sevenda: MutableSet<Long> = HashSet() var i = 0 while (i < 7 && i < lastEmpires.size) { sevenda.addAll(lastEmpires[i]) i++ } dailyStats[day] = DailyStat( day = day, oneda = lastEmpires[0].size, sevenda = sevenda.size, signups = 0 /* TODO: populate */) } override fun onOpen(diskVersion: Int): Int { var version = diskVersion if (version == 0) { newWriter() .stmt( "CREATE TABLE login_events (" + " timestamp INTEGER," + " day INTEGER," + " empire_id INTEGER," + " device_id STRING," + " email_addr STRING," + " device_info BLOB)") .execute() newWriter() .stmt("CREATE INDEX IX_login_events_day ON login_events (day)") .execute() newWriter() .stmt( "CREATE TABLE create_empire_events (" + " timestamp INTEGER," + " day INTEGER," + " empire_id INTEGER)") .execute() newWriter() .stmt("CREATE INDEX IX_create_empire_events_day ON create_empire_events (day)") .execute() version++ } return version } }
mit
91d012fa6973b8dfd6a4107bcda97a99
33.914063
116
0.572516
3.940035
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/lang/core/completion/RsVisRestrictionCompletionProvider.kt
2
2026
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.completion import com.intellij.codeInsight.completion.CompletionParameters import com.intellij.codeInsight.completion.CompletionResultSet import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.patterns.PlatformPatterns.psiElement import com.intellij.patterns.PsiElementPattern import com.intellij.psi.PsiElement import com.intellij.util.ProcessingContext import org.rust.ide.icons.RsIcons import org.rust.lang.core.psi.RsElementTypes import org.rust.lang.core.psi.RsPath import org.rust.lang.core.psi.RsVisRestriction import org.rust.lang.core.psi.ext.qualifier import org.rust.lang.core.psiElement import org.rust.lang.core.with /** * Provides completion inside visibility restriction: * `pub(<here>)` */ object RsVisRestrictionCompletionProvider : RsCompletionProvider() { override val elementPattern: PsiElementPattern.Capture<PsiElement> get() = psiElement(RsElementTypes.IDENTIFIER) .withParent( psiElement<RsPath>() .with("hasOneSegment") { item, _ -> item.qualifier == null && item.typeQual == null && !item.hasColonColon } ) .withSuperParent(2, psiElement<RsVisRestriction>() .with("hasNoIn") { item, _ -> item.`in` == null } ) override fun addCompletions( parameters: CompletionParameters, context: ProcessingContext, result: CompletionResultSet ) { for (name in listOf("crate", "super", "self")) { result.addElement( LookupElementBuilder .create(name) .withIcon(RsIcons.MODULE) .bold() .toKeywordElement() ) } result.addElement(LookupElementBuilder.create("in ").withPresentableText("in")) } }
mit
f011c0bc529c46b03cdb13f0d12d0ea3
34.54386
94
0.652024
4.678984
false
false
false
false
TeamWizardry/LibrarianLib
modules/foundation/src/main/kotlin/com/teamwizardry/librarianlib/foundation/BaseMod.kt
1
7699
package com.teamwizardry.librarianlib.foundation import com.teamwizardry.librarianlib.core.util.loc import com.teamwizardry.librarianlib.courier.CourierChannel import com.teamwizardry.librarianlib.foundation.registration.RegistrationManager import com.teamwizardry.librarianlib.foundation.util.ModLogManager import net.minecraft.block.Block import net.minecraft.entity.EntityType import net.minecraft.fluid.Fluid import net.minecraft.inventory.container.ContainerType import net.minecraft.item.Item import net.minecraft.tileentity.TileEntityType import net.minecraft.util.SoundEvent import net.minecraftforge.common.MinecraftForge import net.minecraftforge.event.RegistryEvent import net.minecraftforge.eventbus.api.IEventBus import net.minecraftforge.eventbus.api.SubscribeEvent import net.minecraftforge.fml.ModLoadingContext import net.minecraftforge.fml.common.Mod import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent import net.minecraftforge.fml.event.lifecycle.FMLDedicatedServerSetupEvent import net.minecraftforge.fml.event.lifecycle.InterModEnqueueEvent import net.minecraftforge.fml.event.lifecycle.InterModProcessEvent import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext import net.minecraftforge.registries.IForgeRegistry import org.apache.logging.log4j.Logger import thedarkcolour.kotlinforforge.forge.MOD_BUS /** * * Order of events: * - constructor * - [createRegistries] * - Forge registries * - mod registries * - [commonSetup] * - [clientSetup]/[dedicatedServerSetup] * - [interModCommsEnqueue] * - [interModCommsProcess] * * @constructor * @param kotlinContext Pass a value of true if your mod uses the Kotlin for Forge language provider */ @Suppress("LeakingThis") public abstract class BaseMod @JvmOverloads constructor(private val kotlinContext: Boolean = false) { public val modid: String = this.javaClass.getAnnotation(Mod::class.java)?.value ?: throw IllegalStateException("Could not find mod annotation on ${javaClass.canonicalName}") public val version: String = ModLoadingContext.get().activeContainer.modInfo.version.toString() public val registrationManager: RegistrationManager public val courier: CourierChannel public val eventBus: IEventBus = modLoadingContextEventBus() public val logManager: ModLogManager = ModLogManager(modid) public val logger: Logger by lazy { makeLogger(null) } init { registrationManager = RegistrationManager(modid, eventBus) courier = CourierChannel(loc(modid, "courier"), version) eventBus.register(this) MinecraftForge.EVENT_BUS.register(this) } //region Override points /** * Create any custom registries here using the [RegistryBuilder][net.minecraftforge.registries.RegistryBuilder] */ protected open fun createRegistries() {} protected open fun registerBlocks(registry: IForgeRegistry<Block>) {} protected open fun registerItems(registry: IForgeRegistry<Item>) {} protected open fun registerTileEntities(registry: IForgeRegistry<TileEntityType<*>>) {} protected open fun registerEntities(registry: IForgeRegistry<EntityType<*>>) {} protected open fun registerFluids(registry: IForgeRegistry<Fluid>) {} protected open fun registerContainers(registry: IForgeRegistry<ContainerType<*>>) {} protected open fun registerSounds(registry: IForgeRegistry<SoundEvent>) {} /** * Called in parallel after all the registries have been populated */ protected open fun commonSetup(e: FMLCommonSetupEvent) { } /** * Called in parallel after [commonSetup] to do client-specific setup */ protected open fun clientSetup(e: FMLClientSetupEvent) { } /** * Called in parallel after [commonSetup] to do dedicated server-specific setup */ protected open fun dedicatedServerSetup(e: FMLDedicatedServerSetupEvent) { } /** * Send events over inter-mod comms */ protected open fun interModCommsEnqueue(e: InterModEnqueueEvent) { } /** * Process events received over inter-mod comms */ protected open fun interModCommsProcess(e: InterModProcessEvent) { } /** * Gets the mod loading event bus. Override this if your mod uses a non-standard mod loader. Mods using the * Kotlin for Forge mod language provider should pass true to the `kotlinContext` constructor parameter instead of * overriding this method. */ protected open fun modLoadingContextEventBus(): IEventBus { return if(kotlinContext) { MOD_BUS } else { FMLJavaModLoadingContext.get().modEventBus } } //endregion //region Public API /** * Sets the base name for this mod's loggers. The root logger will be `"<logBaseName>"`, and any class loggers will * be `"<logBaseName> (<className>)"`. * * Any loggers created before this is called will not be affected by the change */ protected fun setLoggerBaseName(name: String) { logManager.baseName = name } /** * Create a logger for the specified class. */ public fun makeLogger(clazz: Class<*>): Logger { return logManager.makeLogger(clazz.simpleName) } /** * Create a logger for the specified class. */ @JvmSynthetic public inline fun <reified T> makeLogger(): Logger { return logManager.makeLogger(T::class.java) } /** * Create a logger with the specified label. */ public fun makeLogger(label: String?): Logger { return logManager.makeLogger(label) } //endregion //region Internal implementation @SubscribeEvent @JvmSynthetic internal fun baseCreateRegistries(e: RegistryEvent.NewRegistry) { createRegistries() } @SubscribeEvent @JvmSynthetic internal fun baseRegisterBlocks(e: RegistryEvent.Register<Block>) { registerBlocks(e.registry) } @SubscribeEvent @JvmSynthetic internal fun baseRegisterItems(e: RegistryEvent.Register<Item>) { registerItems(e.registry) } @SubscribeEvent @JvmSynthetic internal fun baseRegisterTileEntities(e: RegistryEvent.Register<TileEntityType<*>>) { registerTileEntities(e.registry) } @SubscribeEvent @JvmSynthetic internal fun baseRegisterEntities(e: RegistryEvent.Register<EntityType<*>>) { registerEntities(e.registry) } @SubscribeEvent @JvmSynthetic internal fun baseRegisterFluids(e: RegistryEvent.Register<Fluid>) { registerFluids(e.registry) } @SubscribeEvent @JvmSynthetic internal fun baseRegisterContainers(e: RegistryEvent.Register<ContainerType<*>>) { registerContainers(e.registry) } @SubscribeEvent @JvmSynthetic internal fun baseRegisterSounds(e: RegistryEvent.Register<SoundEvent>) { registerSounds(e.registry) } @SubscribeEvent @JvmSynthetic internal fun baseCommonSetup(e: FMLCommonSetupEvent) { commonSetup(e) } @SubscribeEvent @JvmSynthetic internal fun baseClientSetup(e: FMLClientSetupEvent) { clientSetup(e) } @SubscribeEvent @JvmSynthetic internal fun baseDedicatedServerSetup(e: FMLDedicatedServerSetupEvent) { dedicatedServerSetup(e) } @SubscribeEvent @JvmSynthetic internal fun baseInterModCommsEnqueue(e: InterModEnqueueEvent) { interModCommsEnqueue(e) } @SubscribeEvent @JvmSynthetic internal fun baseInterModCommsProcess(e: InterModProcessEvent) { interModCommsProcess(e) } //endregion }
lgpl-3.0
368efbc8a97fb66de105ba6e06dfab00
32.624454
119
0.726848
4.63516
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/cargo/runconfig/buildtool/RsBuildTaskProvider.kt
3
1639
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.cargo.runconfig.buildtool import com.intellij.execution.BeforeRunTask import com.intellij.execution.BeforeRunTaskProvider import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.icons.AllIcons import com.intellij.openapi.util.Key import com.intellij.task.ProjectTaskManager import org.rust.cargo.runconfig.buildtool.CargoBuildManager.createBuildEnvironment import org.rust.cargo.runconfig.command.CargoCommandConfiguration import java.util.concurrent.CompletableFuture import javax.swing.Icon abstract class RsBuildTaskProvider<T : RsBuildTaskProvider.BuildTask<T>> : BeforeRunTaskProvider<T>() { override fun getName(): String = "Build" override fun getIcon(): Icon = AllIcons.Actions.Compile override fun isSingleton(): Boolean = true protected fun doExecuteTask(buildConfiguration: CargoCommandConfiguration, environment: ExecutionEnvironment): Boolean { val buildEnvironment = createBuildEnvironment(buildConfiguration, environment) ?: return false val buildableElement = CargoBuildConfiguration(buildConfiguration, buildEnvironment) val result = CompletableFuture<Boolean>() ProjectTaskManager.getInstance(environment.project).build(buildableElement).onProcessed { result.complete(!it.hasErrors() && !it.isAborted) } return result.get() } abstract class BuildTask<T : BuildTask<T>>(providerId: Key<T>) : BeforeRunTask<T>(providerId) { init { isEnabled = true } } }
mit
3d337e042c76d69524fffb72fb2184bf
39.975
124
0.76205
4.921922
false
true
false
false
HabitRPG/habitrpg-android
Habitica/src/main/java/com/habitrpg/android/habitica/interactors/NotifyUserUseCase.kt
1
6627
package com.habitrpg.android.habitica.interactors import android.content.Context import android.graphics.Bitmap import android.graphics.drawable.BitmapDrawable import android.text.SpannableStringBuilder import android.view.Gravity import android.view.View import android.view.ViewGroup import android.widget.LinearLayout import android.widget.TextView import androidx.core.content.ContextCompat import androidx.core.util.Pair import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.data.UserRepository import com.habitrpg.android.habitica.executors.PostExecutionThread import com.habitrpg.android.habitica.extensions.round import com.habitrpg.android.habitica.models.user.Stats import com.habitrpg.android.habitica.models.user.User import com.habitrpg.android.habitica.ui.activities.BaseActivity import com.habitrpg.android.habitica.ui.views.HabiticaIconsHelper import com.habitrpg.android.habitica.ui.views.HabiticaSnackbar import com.habitrpg.android.habitica.ui.views.HabiticaSnackbar.SnackbarDisplayType import io.reactivex.rxjava3.core.Flowable import javax.inject.Inject import kotlin.math.abs class NotifyUserUseCase @Inject constructor( postExecutionThread: PostExecutionThread, private val levelUpUseCase: LevelUpUseCase, private val userRepository: UserRepository ) : UseCase<NotifyUserUseCase.RequestValues, Stats>(postExecutionThread) { override fun buildUseCaseObservable(requestValues: RequestValues): Flowable<Stats> { return Flowable.defer { if (requestValues.user == null) { return@defer Flowable.empty<Stats>() } val stats = requestValues.user.stats val pair = getNotificationAndAddStatsToUser(requestValues.context, requestValues.xp, requestValues.hp, requestValues.gold, requestValues.mp, requestValues.questDamage, requestValues.user) val view = pair.first val type = pair.second if (view != null && type != null) { HabiticaSnackbar.showSnackbar(requestValues.snackbarTargetView, null, null, view, type) } if (requestValues.hasLeveledUp == true) { return@defer levelUpUseCase.observable(LevelUpUseCase.RequestValues(requestValues.user, requestValues.level, requestValues.context, requestValues.snackbarTargetView)) .flatMap { userRepository.retrieveUser(true) } .map { it.stats } } else { return@defer Flowable.just(stats) } } } class RequestValues(val context: BaseActivity, val snackbarTargetView: ViewGroup, val user: User?, val xp: Double?, val hp: Double?, val gold: Double?, val mp: Double?, val questDamage: Double?, val hasLeveledUp: Boolean?, val level: Int?) : UseCase.RequestValues companion object { fun getNotificationAndAddStatsToUser(context: Context, xp: Double?, hp: Double?, gold: Double?, mp: Double?, questDamage: Double?, user: User?): Pair<View, SnackbarDisplayType> { var displayType = SnackbarDisplayType.SUCCESS val container = LinearLayout(context) container.orientation = LinearLayout.HORIZONTAL if (xp != null && xp > 0) { container.addView(createTextView(context, xp, HabiticaIconsHelper.imageOfExperience())) } if (hp != null && hp != 0.0) { if (hp < 0) { displayType = SnackbarDisplayType.FAILURE } container.addView(createTextView(context, hp, HabiticaIconsHelper.imageOfHeartDarkBg())) } if (gold != null && gold != 0.0) { container.addView(createTextView(context, gold, HabiticaIconsHelper.imageOfGold())) if (gold < 0) { displayType = SnackbarDisplayType.FAILURE } } if (mp != null && mp > 0 && user?.hasClass == true) { container.addView(createTextView(context, mp, HabiticaIconsHelper.imageOfMagic())) } if (questDamage != null && questDamage > 0) { container.addView(createTextView(context, questDamage, HabiticaIconsHelper.imageOfDamage())) } val padding = context.resources.getDimension(R.dimen.spacing_medium).toInt() (1 until container.childCount) .map { container.getChildAt(it) } .forEach { it.setPadding(padding, 0, 0, 0) } return Pair(container, displayType) } private fun createTextView(context: Context, value: Double, icon: Bitmap): View { val textView = TextView(context) val iconDrawable = BitmapDrawable(context.resources, icon) textView.setCompoundDrawablesWithIntrinsicBounds(iconDrawable, null, null, null) val text: String = if (value > 0) { " + " + abs(value.round(2)).toString() } else { " - " + abs(value.round(2)).toString() } textView.text = text textView.gravity = Gravity.CENTER_VERTICAL textView.setTextColor(ContextCompat.getColor(context, R.color.white)) return textView } fun getNotificationAndAddStatsToUserAsText(xp: Double?, hp: Double?, gold: Double?, mp: Double?): Pair<SpannableStringBuilder, SnackbarDisplayType> { val builder = SpannableStringBuilder() var displayType = SnackbarDisplayType.NORMAL if ((xp ?: 0.0) > 0) { builder.append(" + ").append(xp?.round(2).toString()).append(" Exp") } if (hp != 0.0) { displayType = SnackbarDisplayType.FAILURE builder.append(" - ").append(abs(hp?.round(2) ?: 0.0).toString()).append(" Health") } if (gold != 0.0) { if ((gold ?: 0.0) > 0) { builder.append(" + ").append(gold?.round(2).toString()) } else if ((gold ?: 0.0) < 0) { displayType = SnackbarDisplayType.FAILURE builder.append(" - ").append(abs(gold?.round(2) ?: 0.0).toString()) } builder.append(" Gold") } if ((mp ?: 0.0) > 0) { builder.append(" + ").append(mp?.round(2).toString()).append(" Mana") } return Pair(builder, displayType) } } }
gpl-3.0
30477fb7560e94d1f92a836870dc1808
45
267
0.615512
4.784838
false
false
false
false
googlemaps/android-maps-compose
maps-compose/src/main/java/com/google/maps/android/compose/MapUpdater.kt
1
7661
// 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.maps.android.compose import android.annotation.SuppressLint import androidx.compose.foundation.layout.PaddingValues import androidx.compose.runtime.Composable import androidx.compose.runtime.ComposeNode import androidx.compose.runtime.currentComposer import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.LayoutDirection import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.LocationSource import com.google.android.gms.maps.model.IndoorBuilding internal class MapPropertiesNode( val map: GoogleMap, cameraPositionState: CameraPositionState, contentDescription: String?, var clickListeners: MapClickListeners, var density: Density, var layoutDirection: LayoutDirection, ) : MapNode { init { cameraPositionState.setMap(map) if (contentDescription != null) { map.setContentDescription(contentDescription) } } var contentDescription = contentDescription set(value) { field = value map.setContentDescription(contentDescription) } var cameraPositionState = cameraPositionState set(value) { if (value == field) return field.setMap(null) field = value value.setMap(map) } override fun onAttached() { map.setOnCameraIdleListener { cameraPositionState.isMoving = false // setOnCameraMoveListener is only invoked when the camera position // is changed via .animate(). To handle updating state when .move() // is used, it's necessary to set the camera's position here as well cameraPositionState.rawPosition = map.cameraPosition } map.setOnCameraMoveCanceledListener { cameraPositionState.isMoving = false } map.setOnCameraMoveStartedListener { cameraPositionState.cameraMoveStartedReason = CameraMoveStartedReason.fromInt(it) cameraPositionState.isMoving = true } map.setOnCameraMoveListener { cameraPositionState.rawPosition = map.cameraPosition } map.setOnMapClickListener { clickListeners.onMapClick(it) } map.setOnMapLongClickListener { clickListeners.onMapLongClick(it) } map.setOnMapLoadedCallback { clickListeners.onMapLoaded() } map.setOnMyLocationButtonClickListener { clickListeners.onMyLocationButtonClick() } map.setOnMyLocationClickListener { clickListeners.onMyLocationClick(it) } map.setOnPoiClickListener { clickListeners.onPOIClick(it) } map.setOnIndoorStateChangeListener(object : GoogleMap.OnIndoorStateChangeListener { override fun onIndoorBuildingFocused() { clickListeners.indoorStateChangeListener.onIndoorBuildingFocused() } override fun onIndoorLevelActivated(building: IndoorBuilding) { clickListeners.indoorStateChangeListener.onIndoorLevelActivated(building) } }) } override fun onRemoved() { cameraPositionState.setMap(null) } override fun onCleared() { cameraPositionState.setMap(null) } } internal val NoPadding = PaddingValues() /** * Used to keep the primary map properties up to date. This should never leave the map composition. */ @SuppressLint("MissingPermission") @Suppress("NOTHING_TO_INLINE") @Composable internal inline fun MapUpdater( contentDescription: String?, cameraPositionState: CameraPositionState, clickListeners: MapClickListeners, contentPadding: PaddingValues = NoPadding, locationSource: LocationSource?, mapProperties: MapProperties, mapUiSettings: MapUiSettings, ) { val map = (currentComposer.applier as MapApplier).map val density = LocalDensity.current val layoutDirection = LocalLayoutDirection.current ComposeNode<MapPropertiesNode, MapApplier>( factory = { MapPropertiesNode( map = map, contentDescription = contentDescription, cameraPositionState = cameraPositionState, clickListeners = clickListeners, density = density, layoutDirection = layoutDirection, ) } ) { // The node holds density and layoutDirection so that the updater blocks can be // non-capturing, allowing the compiler to turn them into singletons update(density) { this.density = it } update(layoutDirection) { this.layoutDirection = it } update(contentDescription) { this.contentDescription = it } set(locationSource) { map.setLocationSource(it) } set(mapProperties.isBuildingEnabled) { map.isBuildingsEnabled = it } set(mapProperties.isIndoorEnabled) { map.isIndoorEnabled = it } set(mapProperties.isMyLocationEnabled) { map.isMyLocationEnabled = it } set(mapProperties.isTrafficEnabled) { map.isTrafficEnabled = it } set(mapProperties.latLngBoundsForCameraTarget) { map.setLatLngBoundsForCameraTarget(it) } set(mapProperties.mapStyleOptions) { map.setMapStyle(it) } set(mapProperties.mapType) { map.mapType = it.value } set(mapProperties.maxZoomPreference) { map.setMaxZoomPreference(it) } set(mapProperties.minZoomPreference) { map.setMinZoomPreference(it) } set(contentPadding) { val node = this with(this.density) { map.setPadding( it.calculateLeftPadding(node.layoutDirection).roundToPx(), it.calculateTopPadding().roundToPx(), it.calculateRightPadding(node.layoutDirection).roundToPx(), it.calculateBottomPadding().roundToPx() ) } } set(mapUiSettings.compassEnabled) { map.uiSettings.isCompassEnabled = it } set(mapUiSettings.indoorLevelPickerEnabled) { map.uiSettings.isIndoorLevelPickerEnabled = it } set(mapUiSettings.mapToolbarEnabled) { map.uiSettings.isMapToolbarEnabled = it } set(mapUiSettings.myLocationButtonEnabled) { map.uiSettings.isMyLocationButtonEnabled = it } set(mapUiSettings.rotationGesturesEnabled) { map.uiSettings.isRotateGesturesEnabled = it } set(mapUiSettings.scrollGesturesEnabled) { map.uiSettings.isScrollGesturesEnabled = it } set(mapUiSettings.scrollGesturesEnabledDuringRotateOrZoom) { map.uiSettings.isScrollGesturesEnabledDuringRotateOrZoom = it } set(mapUiSettings.tiltGesturesEnabled) { map.uiSettings.isTiltGesturesEnabled = it } set(mapUiSettings.zoomControlsEnabled) { map.uiSettings.isZoomControlsEnabled = it } set(mapUiSettings.zoomGesturesEnabled) { map.uiSettings.isZoomGesturesEnabled = it } update(cameraPositionState) { this.cameraPositionState = it } update(clickListeners) { this.clickListeners = it } } }
apache-2.0
5e6e3f43068183430cc00d6645621871
42.039326
132
0.700039
5.036818
false
false
false
false
foreverigor/TumCampusApp
app/src/main/java/de/tum/in/tumcampusapp/component/ui/ticket/fragment/EventDetailsFragment.kt
1
11016
package de.tum.`in`.tumcampusapp.component.ui.ticket.fragment import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle import android.provider.CalendarContract import android.support.v4.app.Fragment import android.support.v4.widget.SwipeRefreshLayout import android.support.v7.app.AlertDialog import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.squareup.picasso.Picasso import de.tum.`in`.tumcampusapp.R import de.tum.`in`.tumcampusapp.api.app.TUMCabeClient import de.tum.`in`.tumcampusapp.api.tumonline.AccessTokenManager import de.tum.`in`.tumcampusapp.component.tumui.calendar.CreateEventActivity import de.tum.`in`.tumcampusapp.component.ui.ticket.EventsController import de.tum.`in`.tumcampusapp.component.ui.ticket.activity.BuyTicketActivity import de.tum.`in`.tumcampusapp.component.ui.ticket.activity.ShowTicketActivity import de.tum.`in`.tumcampusapp.component.ui.ticket.model.Event import de.tum.`in`.tumcampusapp.component.ui.ticket.payload.TicketStatus import de.tum.`in`.tumcampusapp.utils.Const import de.tum.`in`.tumcampusapp.utils.Const.KEY_EVENT_ID import de.tum.`in`.tumcampusapp.utils.DateTimeUtils import de.tum.`in`.tumcampusapp.utils.Utils import de.tum.`in`.tumcampusapp.utils.into import kotlinx.android.synthetic.main.fragment_event_details.* import kotlinx.android.synthetic.main.fragment_event_details.view.* import org.joda.time.DateTime import retrofit2.Call import retrofit2.Callback import retrofit2.Response import java.util.* /** * Fragment for displaying information about an [Event]. Manages content that's shown in the * PagerAdapter. */ class EventDetailsFragment : Fragment(), SwipeRefreshLayout.OnRefreshListener { private var event: Event? = null private lateinit var eventsController: EventsController override fun onAttach(context: Context?) { super.onAttach(context) eventsController = EventsController(context) arguments?.let { args -> event = args.getParcelable(Const.KEY_EVENT) } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = LayoutInflater.from(container?.context) .inflate(R.layout.fragment_event_details, container, false) view.swipeRefreshLayout.setOnRefreshListener(this) view.swipeRefreshLayout.setColorSchemeResources( R.color.color_primary, R.color.tum_A100, R.color.tum_A200 ) return view } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) event?.let { showEventDetails(it) loadAvailableTicketCount(it) } } override fun onRefresh() { event?.let { loadAvailableTicketCount(it) } } override fun onResume() { super.onResume() event?.let { if (!eventsController.isEventBooked(event) && isEventImminent(event as Event)) { ticketButton.visibility = View.GONE } } } /** * Checks if the event starts less than 4 hours from now. * (-> user won't be able to buy tickets anymore) */ private fun isEventImminent(event: Event): Boolean { val eventStart = DateTime(event.startTime) return eventStart.minusHours(4).isAfterNow } private fun showEventImminentDialog() { context?.let { val dialog = AlertDialog.Builder(it) .setTitle(R.string.error) .setMessage(R.string.event_imminent_error) .setPositiveButton(R.string.ok, null) .create() dialog.window.setBackgroundDrawableResource(R.drawable.rounded_corners_background) dialog.show() } } private fun showEventDetails(event: Event) { val url = event.imageUrl if (url != null) { Picasso.get() .load(url) .noPlaceholder() .into(posterView) { posterProgressBar?.visibility = View.GONE } } else { posterProgressBar.visibility = View.GONE } if (eventsController.isEventBooked(event)) { ticketButton.text = getString(R.string.show_ticket) ticketButton.setOnClickListener { showTicket(event) } } else { ticketButton.text = getString(R.string.buy_ticket) ticketButton.setOnClickListener { buyTicket(event) } } context?.let { dateTextView.text = event.getFormattedStartDateTime(it) dateContainer.setOnClickListener { _ -> displayAddToCalendarDialog() } } locationTextView.text = event.locality locationContainer.setOnClickListener { openMaps(event) } descriptionTextView.text = event.description linkButton.setOnClickListener { openEventLink(event) } linkButton.visibility = if (event.eventUrl.isNotBlank()) View.VISIBLE else View.GONE } private fun openEventLink(event: Event) { val intent = Intent(Intent.ACTION_VIEW, Uri.parse(event.eventUrl)) startActivity(intent) } private fun loadAvailableTicketCount(event: Event) { TUMCabeClient .getInstance(context) .fetchTicketStats(event.id, object : Callback<List<TicketStatus>> { override fun onResponse(call: Call<List<TicketStatus>>, response: Response<List<TicketStatus>>) { val statuses = response.body() ?: return val sum = statuses.sumBy { it.availableTicketCount } val text = String.format(Locale.getDefault(), "%d", sum) if (isDetached.not()) { remainingTicketsTextView.text = text swipeRefreshLayout.isRefreshing = false } } override fun onFailure(call: Call<List<TicketStatus>>, t: Throwable) { Utils.log(t) if (isDetached.not()) { remainingTicketsTextView.setText(R.string.unknown) swipeRefreshLayout.isRefreshing = false } } }) } private fun showTicket(event: Event) { val intent = Intent(context, ShowTicketActivity::class.java).apply { putExtra(KEY_EVENT_ID, event.id) } startActivity(intent) } private fun buyTicket(event: Event) { val c = context ?: return if (isEventImminent(event)) { showEventImminentDialog() ticketButton.visibility = View.GONE return } val lrzId = Utils.getSetting(c, Const.LRZ_ID, "") val chatRoomName = Utils.getSetting(c, Const.CHAT_ROOM_DISPLAY_NAME, "") val isLoggedIn = AccessTokenManager.hasValidAccessToken(context) if (!isLoggedIn || lrzId.isEmpty() || chatRoomName.isEmpty()) { context?.let { val dialog = AlertDialog.Builder(it) .setTitle(R.string.error) .setMessage(R.string.not_logged_in_error) .setPositiveButton(R.string.ok) { _, _ -> activity?.finish() } .create() dialog.window?.setBackgroundDrawableResource(R.drawable.rounded_corners_background) dialog.show() } return } val intent = Intent(context, BuyTicketActivity::class.java).apply { putExtra(KEY_EVENT_ID, event.id) } startActivity(intent) } private fun addToTUMCalendar() { val event = event ?: return val endTime = event.endTime ?: event.startTime.plus(Event.defaultDuration.toLong()) val intent = Intent(context, CreateEventActivity::class.java).apply { putExtra(Const.EVENT_EDIT, false) putExtra(Const.EVENT_TITLE, event.title) putExtra(Const.EVENT_COMMENT, event.description) putExtra(Const.EVENT_START, event.startTime) putExtra(Const.EVENT_END, endTime) } startActivity(intent) } private fun addToExternalCalendar() { val event = event ?: return val endTime = event.endTime ?: event.startTime.plus(Event.defaultDuration.toLong()) val eventEnd = DateTimeUtils.getDateTimeString(endTime) val intent = Intent(Intent.ACTION_INSERT).apply { data = CalendarContract.Events.CONTENT_URI putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, event.startTime.millis) putExtra(CalendarContract.EXTRA_EVENT_END_TIME, eventEnd) putExtra(CalendarContract.Events.TITLE, event.title) putExtra(CalendarContract.Events.DESCRIPTION, event.description) putExtra(CalendarContract.Events.EVENT_LOCATION, event.locality) // Indicates that this event is free time and will not conflict with other events putExtra(CalendarContract.Events.AVAILABILITY, CalendarContract.Events.AVAILABILITY_FREE) } startActivity(intent) } private fun openMaps(event: Event) { val url = "http://maps.google.co.in/maps?q=${event.locality}" val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url)) startActivity(intent) } private fun displayAddToCalendarDialog() { val context = requireContext() val calendars = arrayOf( getString(R.string.external_calendar), getString(R.string.tum_calendar) ) val dialog = AlertDialog.Builder(context) .setTitle(R.string.add_to_calendar_info) .setSingleChoiceItems(calendars, 0, null) .setNegativeButton(R.string.cancel, null) .setPositiveButton(R.string.add) { _, which -> handleCalendarExportSelection(which) } .setCancelable(true) .create() dialog.window?.setBackgroundDrawableResource(R.drawable.rounded_corners_background) dialog.show() } private fun handleCalendarExportSelection(which: Int) { when(which) { 0 -> addToExternalCalendar() else -> addToTUMCalendar() } } companion object { @JvmStatic fun newInstance(event: Event): EventDetailsFragment { return EventDetailsFragment().apply { arguments = Bundle().apply { putParcelable(Const.KEY_EVENT, event) } } } } }
gpl-3.0
8bbb863a425eab7a0e7e9cd692052545
35.118033
101
0.616195
4.779176
false
false
false
false
androidx/androidx
tv/tv-material/samples/src/main/java/androidx/tv/tvmaterial/samples/ImmersiveList.kt
3
3366
/* * 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.tvmaterial.samples import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.width import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import androidx.tv.material.ExperimentalTvMaterialApi import androidx.tv.material.immersivelist.ImmersiveList @OptIn(ExperimentalTvMaterialApi::class) @Composable fun SampleImmersiveList() { val immersiveListHeight = 300.dp val cardSpacing = 10.dp val cardWidth = 200.dp val cardHeight = 150.dp val backgrounds = listOf( Color.Red, Color.Blue, Color.Magenta, ) Box( modifier = Modifier .height(immersiveListHeight + cardHeight / 2) .fillMaxWidth() ) { ImmersiveList( modifier = Modifier .height(immersiveListHeight) .fillMaxWidth(), listAlignment = Alignment.BottomEnd, background = { index, _ -> Box( modifier = Modifier .background(backgrounds[index].copy(alpha = 0.3f)) .fillMaxSize() ) } ) { Row( horizontalArrangement = Arrangement.spacedBy(cardSpacing), modifier = Modifier.offset(y = cardHeight / 2) ) { backgrounds.forEachIndexed { index, backgroundColor -> var isFocused by remember { mutableStateOf(false) } Box( modifier = Modifier .background(backgroundColor) .width(cardWidth) .height(cardHeight) .border(5.dp, Color.White.copy(alpha = if (isFocused) 1f else 0.3f)) .onFocusChanged { isFocused = it.isFocused } .focusableItem(index) ) } } } } }
apache-2.0
ba0dacfe6f05820f85a41b9d171d3909
35.193548
96
0.644385
4.815451
false
false
false
false
Soya93/Extract-Refactoring
platform/configuration-store-impl/src/StreamProvider.kt
4
2013
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.configurationStore import com.intellij.openapi.components.RoamingType import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream import java.io.InputStream interface StreamProvider { open val enabled: Boolean get() = true open fun isApplicable(fileSpec: String, roamingType: RoamingType = RoamingType.DEFAULT): Boolean = true /** * @param fileSpec * @param content bytes of content, size of array is not actual size of data, you must use `size` * @param size actual size of data */ fun write(fileSpec: String, content: ByteArray, size: Int = content.size, roamingType: RoamingType = RoamingType.DEFAULT) fun read(fileSpec: String, roamingType: RoamingType = RoamingType.DEFAULT): InputStream? /** * You must close passed input stream. */ fun processChildren(path: String, roamingType: RoamingType, filter: (name: String) -> Boolean, processor: (name: String, input: InputStream, readOnly: Boolean) -> Boolean) /** * Delete file or directory */ fun delete(fileSpec: String, roamingType: RoamingType = RoamingType.DEFAULT) } fun StreamProvider.write(path: String, content: String) { write(path, content.toByteArray()) } fun StreamProvider.write(path: String, content: BufferExposingByteArrayOutputStream, roamingType: RoamingType = RoamingType.DEFAULT) { write(path, content.internalBuffer, content.size(), roamingType) }
apache-2.0
355cba9273fc920a2e4da42e04b785fd
36.296296
173
0.749131
4.385621
false
false
false
false
minecraft-dev/MinecraftDev
src/main/kotlin/platform/mixin/reference/DescReference.kt
1
5808
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.reference import com.demonwav.mcdev.platform.mixin.util.MixinConstants.Annotations.DESC import com.demonwav.mcdev.platform.mixin.util.findClassNodeByQualifiedName import com.demonwav.mcdev.util.MemberReference import com.demonwav.mcdev.util.findModule import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.command.CommandProcessor import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.util.text.StringUtil import com.intellij.patterns.ElementPattern import com.intellij.patterns.PsiJavaPatterns import com.intellij.patterns.StandardPatterns import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiAnnotation import com.intellij.psi.PsiAnnotationMemberValue import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementFactory import com.intellij.psi.PsiFile import com.intellij.psi.PsiLiteral import com.intellij.psi.util.parentOfType import org.objectweb.asm.Type import org.objectweb.asm.tree.ClassNode object DescReference : AbstractMethodReference() { val ELEMENT_PATTERN: ElementPattern<PsiLiteral> = PsiJavaPatterns.psiLiteral(StandardPatterns.string()).insideAnnotationParam( StandardPatterns.string().equalTo(DESC) ) override val description = "method '%s'" override fun isValidAnnotation(name: String, project: Project) = name == DESC override fun parseSelector(context: PsiElement): DescSelector? { val annotation = context.parentOfType<PsiAnnotation>() ?: return null // @Desc return DescSelectorParser.descSelectorFromAnnotation(annotation) } override fun getTargets(context: PsiElement): Collection<ClassNode>? { return parseSelector(context)?.owners?.mapNotNull { internalName -> findClassNodeByQualifiedName(context.project, context.findModule(), internalName.replace('/', '.')) } } override fun addCompletionInfo( builder: LookupElementBuilder, context: PsiElement, targetMethodInfo: MemberReference ): LookupElementBuilder { return builder.withInsertHandler { insertionContext, _ -> insertionContext.laterRunnable = CompleteDescReference(insertionContext.editor, insertionContext.file, targetMethodInfo) } } override val requireDescriptor = true private class CompleteDescReference( private val editor: Editor, private val file: PsiFile, private val targetMethodInfo: MemberReference ) : Runnable { private fun PsiElementFactory.createAnnotationMemberValueFromText( text: String, context: PsiElement? ): PsiAnnotationMemberValue { val annotation = this.createAnnotationFromText("@Foo($text)", context) return annotation.findDeclaredAttributeValue("value")!! } override fun run() { // Commit changes made by code completion PsiDocumentManager.getInstance(file.project).commitDocument(editor.document) // Run command to replace PsiElement CommandProcessor.getInstance().runUndoTransparentAction { runWriteAction { val descAnnotation = file.findElementAt(editor.caretModel.offset)?.parentOfType<PsiAnnotation>() ?: return@runWriteAction val project = editor.project ?: return@runWriteAction val elementFactory = JavaPsiFacade.getElementFactory(project) descAnnotation.setDeclaredAttributeValue( "value", elementFactory.createExpressionFromText( "\"${StringUtil.escapeStringCharacters(targetMethodInfo.name)}\"", descAnnotation ) ) val desc = targetMethodInfo.descriptor ?: return@runWriteAction val argTypes = Type.getArgumentTypes(desc) if (argTypes.isNotEmpty()) { val argsText = if (argTypes.size == 1) { "${argTypes[0].className.replace('$', '.')}.class" } else { "{${ argTypes.joinToString(", ") { type -> "${type.className.replace('$', '.')}.class" } }}" } descAnnotation.setDeclaredAttributeValue( "args", elementFactory.createAnnotationMemberValueFromText(argsText, descAnnotation) ) } else { descAnnotation.setDeclaredAttributeValue("desc", null) } val returnType = Type.getReturnType(desc) if (returnType.sort != Type.VOID) { descAnnotation.setDeclaredAttributeValue( "ret", elementFactory.createAnnotationMemberValueFromText( "${returnType.className.replace('$', '.')}.class", descAnnotation ) ) } else { descAnnotation.setDeclaredAttributeValue("ret", null) } } } } } }
mit
28c487cfbabb520f8dfd36914d3f15e1
41.086957
116
0.611742
5.884498
false
false
false
false
InfiniteSoul/ProxerAndroid
src/main/kotlin/me/proxer/app/ui/view/bbcode/prototype/QuotePrototype.kt
1
2631
package me.proxer.app.ui.view.bbcode.prototype import android.view.View import android.view.ViewGroup import android.view.ViewGroup.LayoutParams.MATCH_PARENT import android.view.ViewGroup.LayoutParams.WRAP_CONTENT import android.widget.FrameLayout import android.widget.LinearLayout import android.widget.LinearLayout.VERTICAL import me.proxer.app.R import me.proxer.app.ui.view.bbcode.BBArgs import me.proxer.app.ui.view.bbcode.BBCodeView import me.proxer.app.ui.view.bbcode.BBTree import me.proxer.app.ui.view.bbcode.BBUtils import me.proxer.app.ui.view.bbcode.prototype.BBPrototype.Companion.REGEX_OPTIONS import me.proxer.app.ui.view.bbcode.toSpannableStringBuilder import me.proxer.app.util.extension.dip import me.proxer.app.util.extension.linkify import me.proxer.app.util.extension.resolveColor object QuotePrototype : AutoClosingPrototype { private const val QUOTE_ARGUMENT = "quote" private val quoteAttributeRegex = Regex("quote *= *(.+?)( |$)", REGEX_OPTIONS) override val startRegex = Regex(" *quote( *=\"?.+?\"?)?( .*?)?", REGEX_OPTIONS) override val endRegex = Regex("/ *quote *", REGEX_OPTIONS) override fun construct(code: String, parent: BBTree): BBTree { val quote = BBUtils.cutAttribute(code, quoteAttributeRegex) return BBTree(this, parent, args = BBArgs(custom = *arrayOf(QUOTE_ARGUMENT to quote))) } override fun makeViews(parent: BBCodeView, children: List<BBTree>, args: BBArgs): List<View> { val childViews = super.makeViews(parent, children, args) val quote = args[QUOTE_ARGUMENT] as String? val result = mutableListOf<View>() val layout = when (childViews.size) { 0 -> null 1 -> FrameLayout(parent.context) else -> LinearLayout(parent.context).apply { orientation = VERTICAL } } layout?.apply { val fourDip = parent.dip(4) layoutParams = ViewGroup.MarginLayoutParams(MATCH_PARENT, WRAP_CONTENT) setPadding(fourDip, fourDip, fourDip, fourDip) setBackgroundColor(parent.context.resolveColor(R.attr.colorSelectedSurface)) childViews.forEach { addView(it) } } if (quote != null) { val quoteText = args.safeResources.getString(R.string.view_bbcode_quote, quote.trim()) val boldQuoteText = BoldPrototype.mutate(quoteText.linkify().toSpannableStringBuilder(), args) result += TextPrototype.makeView(parent, args + BBArgs(text = boldQuoteText)) } if (layout != null) { result += layout } return result } }
gpl-3.0
40217757a61c34d5fb928a917cafe046
36.056338
106
0.690992
4.130298
false
false
false
false
saki4510t/libcommon
app/src/main/java/com/serenegiant/libcommon/TitleFragment.kt
1
4141
package com.serenegiant.libcommon /* * libcommon * utility/helper classes for myself * * Copyright (c) 2014-2022 saki [email protected] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.serenegiant.libcommon.TitleFragment.OnListFragmentInteractionListener import com.serenegiant.libcommon.databinding.FragmentItemListBinding import com.serenegiant.libcommon.list.DummyContent import com.serenegiant.libcommon.list.DummyContent.DummyItem import com.serenegiant.libcommon.list.MyItemRecyclerViewAdapter /** * A fragment representing a list of Items. * * * Activities containing this fragment MUST implement the [OnListFragmentInteractionListener] * interface. */ class TitleFragment: BaseFragment() { private lateinit var list: RecyclerView private var mColumnCount = 1 private var mListener: OnListFragmentInteractionListener? = null override fun onAttach(context: Context) { super.onAttach(context) mListener = if (context is OnListFragmentInteractionListener) { context } else { throw RuntimeException(context.toString() + " must implement OnListFragmentInteractionListener") } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (arguments != null) { mColumnCount = requireArguments().getInt(ARG_COLUMN_COUNT) } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return FragmentItemListBinding.inflate(inflater, container, false) .apply { swipeRefresh.setOnRefreshListener { // 何もしてないけどしたつもりになってちょっと待ってからプログレス表示を非表示にする runOnUiThread({ swipeRefresh.isRefreshing = false }, 1000) } [email protected] = list list.run { // Set the adapter layoutManager = if (mColumnCount <= 1) { LinearLayoutManager(context) } else { GridLayoutManager(context, mColumnCount) } adapter = MyItemRecyclerViewAdapter(DummyContent.ITEMS, mListener) } } .run { root } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) } override fun internalOnResume() { super.internalOnResume() requireActivity().title = getString(R.string.app_name) } override fun onDetach() { mListener = null super.onDetach() } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * * * See the Android Training lesson [Communicating with Other Fragments](http://developer.android.com/training/basics/fragments/communicating.html) for more information. */ interface OnListFragmentInteractionListener { fun onListFragmentInteraction(item: DummyItem) } companion object { private const val DEBUG = true // set false on production private val TAG = TitleFragment::class.java.simpleName private const val ARG_COLUMN_COUNT = "column-count" fun newInstance(columnCount: Int): TitleFragment { val fragment = TitleFragment() val args = Bundle() args.putInt(ARG_COLUMN_COUNT, columnCount) fragment.arguments = args return fragment } } }
apache-2.0
f95a9e68f7988063633538d5ec97902c
30
169
0.761635
4.081407
false
false
false
false
Zeyad-37/GenericUseCase
usecases/src/main/java/com/zeyad/usecases/db/RoomManager.kt
2
4020
package com.zeyad.usecases.db import android.arch.persistence.db.SimpleSQLiteQuery import android.arch.persistence.room.RoomDatabase import com.zeyad.usecases.Config import com.zeyad.usecases.Mockable import io.reactivex.Flowable import io.reactivex.Single import org.json.JSONArray import org.json.JSONObject @Mockable class RoomManager(private val db: RoomDatabase, private val daoResolver: DaoResolver) : DataBaseManager { override fun <E> getQuery(query: String, clazz: Class<E>): Flowable<List<E>> { return db.singleTypedTransactionBlock { daoResolver.getDao(clazz).getQuery(SimpleSQLiteQuery(query)) }.toFlowable() } override fun <E> getById(idColumnName: String, itemId: Any, clazz: Class<E>): Flowable<E> { return db.singleTypedTransactionBlock { daoResolver.getDao(clazz) .getItem(SimpleSQLiteQuery("Select * From ${clazz.simpleName} " + "Where $idColumnName=$itemId")) }.toFlowable() } override fun <E> getAll(clazz: Class<E>): Flowable<List<E>> { return db.singleTypedTransactionBlock { daoResolver.getDao(clazz) .getAllItems(SimpleSQLiteQuery("Select * From ${clazz.simpleName}")) }.toFlowable() } override fun <E> put(entity: E, clazz: Class<E>): Single<Any> { return db.singleTransactionBlock { Single.just(daoResolver.getDao(clazz).insertItemsReplace(listOf(entity)).isNotEmpty()) } } override fun <E> put(jsonObject: JSONObject, clazz: Class<E>): Single<Any> { return db.singleTransactionBlock { Single.just(daoResolver.getDao(clazz) .insertItemsReplace(Config.gson.fromJson(jsonObject.toString(), clazz)).isNotEmpty()) } } override fun <E> putAll(entities: List<E>, clazz: Class<E>): Single<Any> { return db.singleTransactionBlock { Single.just(daoResolver.getDao(clazz).insertItemsReplace(entities).isNotEmpty()) } } override fun <E> putAll(jsonArray: JSONArray, clazz: Class<E>): Single<Any> { val list = mutableListOf<E>() val length = jsonArray.length() for (i in 0 until length) { list.add(Config.gson.fromJson(jsonArray.get(i).toString(), clazz)) } return putAll(list, clazz) } override fun <E> evictAll(clazz: Class<E>): Single<Boolean> { return db.singleTypedTransactionBlock { Single.just(daoResolver.getDao(clazz) .deleteAllItems(SimpleSQLiteQuery("DELETE FROM ${clazz.simpleName}")) > 0) } } override fun <E> evictCollection(list: List<E>, clazz: Class<E>): Single<Boolean> { return db.singleTypedTransactionBlock { Single.just(daoResolver.getDao(clazz).deleteItems(list) > 0) } } override fun <E> evictCollectionById(list: List<Any>, clazz: Class<E>, idFieldName: String): Single<Boolean> { return db.singleTypedTransactionBlock { Single.just(list).flatMap { evictById(clazz, idFieldName, it) } } } override fun <E> evictById(clazz: Class<E>, idFieldName: String, idFieldValue: Any): Single<Boolean> { return db.singleTypedTransactionBlock { Single.just(daoResolver.getDao(clazz) .deleteItems(getById(idFieldName, idFieldValue, clazz).blockingFirst()) > 0) } } } private inline fun <E> RoomDatabase.singleTypedTransactionBlock(r: RoomDatabase.() -> Single<E>): Single<E> { beginTransaction() try { val single = r.invoke(this) setTransactionSuccessful() return single } finally { endTransaction() } } private inline fun RoomDatabase.singleTransactionBlock(r: RoomDatabase.() -> Single<Any>): Single<Any> { beginTransaction() try { val single = r.invoke(this) setTransactionSuccessful() return single } finally { endTransaction() } }
apache-2.0
ae9b48aa82a66453cf11815f81c10fd4
35.216216
114
0.643781
4.231579
false
false
false
false
HabitRPG/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/purchases/GiftBalanceGemsFragment.kt
1
3021
package com.habitrpg.android.habitica.ui.fragments.purchases import android.annotation.SuppressLint import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.lifecycle.lifecycleScope import com.habitrpg.android.habitica.components.UserComponent import com.habitrpg.android.habitica.data.SocialRepository import com.habitrpg.android.habitica.data.UserRepository import com.habitrpg.android.habitica.databinding.FragmentGiftGemBalanceBinding import com.habitrpg.android.habitica.helpers.ExceptionHandler import com.habitrpg.android.habitica.models.members.Member import com.habitrpg.android.habitica.ui.fragments.BaseFragment import kotlinx.coroutines.launch import javax.inject.Inject class GiftBalanceGemsFragment : BaseFragment<FragmentGiftGemBalanceBinding>() { @Inject lateinit var socialRepository: SocialRepository @Inject lateinit var userRepository: UserRepository override var binding: FragmentGiftGemBalanceBinding? = null private var isGifting = false override fun createBinding(inflater: LayoutInflater, container: ViewGroup?): FragmentGiftGemBalanceBinding { return FragmentGiftGemBalanceBinding.inflate(inflater, container, false) } var giftedMember: Member? = null @SuppressLint("SetTextI18n") set(value) { field = value field?.let { updateMemberViews() } } private fun updateMemberViews() { val it = giftedMember ?: return binding?.avatarView?.setAvatar(it) binding?.displayNameTextview?.username = it.profile?.name binding?.displayNameTextview?.tier = it.contributor?.level ?: 0 binding?.usernameTextview?.text = it.formattedUsername } override fun injectFragment(component: UserComponent) { component.inject(this) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding?.giftButton?.setOnClickListener { sendGift() } updateMemberViews() } private fun sendGift() { if (isGifting) return isGifting = true try { val amount = binding?.giftEditText?.text.toString().toInt() giftedMember?.id?.let { compositeSubscription.add( socialRepository.transferGems(it, amount) .doOnError { isGifting = false } .subscribe( { lifecycleScope.launch(ExceptionHandler.coroutine()) { userRepository.retrieveUser(false) } activity?.finish() }, ExceptionHandler.rx() ) ) } } catch (ignored: NumberFormatException) {} } }
gpl-3.0
b3b7c58402d861df877ce5e24b5fc15f
34.964286
112
0.642171
5.356383
false
false
false
false
PoweRGbg/AndroidAPS
app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/activities/DanaRUserOptionsActivity.kt
3
6857
package info.nightscout.androidaps.plugins.pump.danaR.activities import android.content.Intent import android.os.Bundle import info.nightscout.androidaps.Constants import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.activities.ErrorHelperActivity import info.nightscout.androidaps.activities.NoSplashAppCompatActivity import info.nightscout.androidaps.events.EventInitializationChanged import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.logging.L import info.nightscout.androidaps.plugins.bus.RxBus.toObservable import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump import info.nightscout.androidaps.plugins.pump.danaRS.DanaRSPlugin import info.nightscout.androidaps.plugins.pump.danaRv2.DanaRv2Plugin import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.FabricPrivacy import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import kotlinx.android.synthetic.main.danar_user_options_activity.* import org.slf4j.LoggerFactory import java.text.DecimalFormat import kotlin.math.max import kotlin.math.min class DanaRUserOptionsActivity : NoSplashAppCompatActivity() { private val log = LoggerFactory.getLogger(L.PUMP) private val disposable = CompositeDisposable() // This is for Dana pumps only private var isRS = DanaRSPlugin.getPlugin().isEnabled(PluginType.PUMP) private var isDanaR = DanaRPlugin.getPlugin().isEnabled(PluginType.PUMP) private var isDanaRv2 = DanaRv2Plugin.getPlugin().isEnabled(PluginType.PUMP) @Synchronized override fun onResume() { super.onResume() disposable.add(toObservable(EventInitializationChanged::class.java) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ setData() }) { FabricPrivacy.logException(it) } ) } @Synchronized override fun onPause() { disposable.clear() super.onPause() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.danar_user_options_activity) save_user_options.setOnClickListener { onSaveClick() } val pump = DanaRPump.getInstance() if (L.isEnabled(L.PUMP)) log.debug("UserOptionsLoaded:" + (System.currentTimeMillis() - pump.lastConnection) / 1000 + " s ago" + "\ntimeDisplayType:" + pump.timeDisplayType + "\nbuttonScroll:" + pump.buttonScrollOnOff + "\ntimeDisplayType:" + pump.timeDisplayType + "\nlcdOnTimeSec:" + pump.lcdOnTimeSec + "\nbackLight:" + pump.backlightOnTimeSec + "\npumpUnits:" + pump.units + "\nlowReservoir:" + pump.lowReservoirRate) danar_screentimeout.setParams(pump.lcdOnTimeSec.toDouble(), 5.0, 240.0, 5.0, DecimalFormat("1"), false, save_user_options) danar_backlight.setParams(pump.backlightOnTimeSec.toDouble(), 1.0, 60.0, 1.0, DecimalFormat("1"), false, save_user_options) danar_shutdown.setParams(pump.shutdownHour.toDouble(), 0.0, 24.0, 1.0, DecimalFormat("1"), true, save_user_options) danar_lowreservoir.setParams(pump.lowReservoirRate.toDouble(), 10.0, 60.0, 10.0, DecimalFormat("10"), false, save_user_options) when (pump.beepAndAlarm) { 0x01 -> danar_pumpalarm_sound.isChecked = true 0x02 -> danar_pumpalarm_vibrate.isChecked = true 0x11 -> danar_pumpalarm_both.isChecked = true 0x101 -> { danar_pumpalarm_sound.isChecked = true danar_beep.isChecked = true } 0x110 -> { danar_pumpalarm_vibrate.isChecked = true danar_beep.isChecked = true } 0x111 -> { danar_pumpalarm_both.isChecked = true danar_beep.isChecked = true } } if (pump.lastSettingsRead == 0L) log.error("No settings loaded from pump!") else setData() } fun setData() { val pump = DanaRPump.getInstance() // in DanaRS timeDisplay values are reversed danar_timeformat.isChecked = !isRS && pump.timeDisplayType != 0 || isRS && pump.timeDisplayType == 0 danar_buttonscroll.isChecked = pump.buttonScrollOnOff != 0 danar_beep.isChecked = pump.beepAndAlarm > 4 danar_screentimeout.value = pump.lcdOnTimeSec.toDouble() danar_backlight.value = pump.backlightOnTimeSec.toDouble() danar_units.isChecked = pump.getUnits() == Constants.MMOL danar_shutdown.value = pump.shutdownHour.toDouble() danar_lowreservoir.value = pump.lowReservoirRate.toDouble() } private fun onSaveClick() { //exit if pump is not DanaRS, DanaR, or DanaR with upgraded firmware if (!isRS && !isDanaR && !isDanaRv2) return val pump = DanaRPump.getInstance() if (isRS) // displayTime on RS is reversed pump.timeDisplayType = if (danar_timeformat.isChecked) 0 else 1 else pump.timeDisplayType = if (danar_timeformat.isChecked) 1 else 0 pump.buttonScrollOnOff = if (danar_buttonscroll.isChecked) 1 else 0 pump.beepAndAlarm = when { danar_pumpalarm_sound.isChecked -> 1 danar_pumpalarm_vibrate.isChecked -> 2 danar_pumpalarm_both.isChecked -> 3 else -> 1 } if (danar_beep.isChecked) pump.beepAndAlarm += 4 // step is 5 seconds, 5 to 240 pump.lcdOnTimeSec = min(max(danar_screentimeout.value.toInt() / 5 * 5, 5), 240) // 1 to 60 pump.backlightOnTimeSec = min(max(danar_backlight.value.toInt(), 1), 60) pump.units = if (danar_units.isChecked) 1 else 0 pump.shutdownHour = min(danar_shutdown.value.toInt(),24) // 10 to 50 pump.lowReservoirRate = min(max(danar_lowreservoir.value.toInt() * 10 / 10, 10), 50) ConfigBuilderPlugin.getPlugin().commandQueue.setUserOptions(object : Callback() { override fun run() { if (!result.success) { val i = Intent(MainApp.instance(), ErrorHelperActivity::class.java) i.putExtra("soundid", R.raw.boluserror) i.putExtra("status", result.comment) i.putExtra("title", MainApp.gs(R.string.pumperror)) i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) MainApp.instance().startActivity(i) } } }) finish() } }
agpl-3.0
89c643959a1fa6a395c4f24f829b4cec
42.132075
135
0.660785
4.256363
false
false
false
false
rhdunn/xquery-intellij-plugin
src/plugin-basex/main/uk/co/reecedunn/intellij/plugin/basex/lang/BaseXSyntaxValidator.kt
1
3129
/* * Copyright (C) 2020-2021 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.basex.lang import com.intellij.psi.util.elementType import uk.co.reecedunn.intellij.plugin.basex.resources.BaseXBundle import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathIfExpr import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathTernaryConditionalExpr import uk.co.reecedunn.intellij.plugin.xpm.lang.validation.XpmSyntaxErrorReporter import uk.co.reecedunn.intellij.plugin.xpm.lang.validation.XpmSyntaxValidationElement import uk.co.reecedunn.intellij.plugin.xpm.lang.validation.XpmSyntaxValidator import uk.co.reecedunn.intellij.plugin.xpm.lang.validation.requires.XpmRequiresProductVersion import uk.co.reecedunn.intellij.plugin.xquery.ast.plugin.PluginElvisExpr import uk.co.reecedunn.intellij.plugin.xquery.ast.plugin.PluginFTFuzzyOption import uk.co.reecedunn.intellij.plugin.xquery.ast.plugin.PluginNonDeterministicFunctionCall import uk.co.reecedunn.intellij.plugin.xquery.ast.plugin.PluginUpdateExpr import uk.co.reecedunn.intellij.plugin.xquery.lexer.XQueryTokenType import xqt.platform.intellij.xpath.XPathTokenProvider object BaseXSyntaxValidator : XpmSyntaxValidator { override fun validate( element: XpmSyntaxValidationElement, reporter: XpmSyntaxErrorReporter ): Unit = when (element) { is PluginElvisExpr -> reporter.requires(element, BASEX_9_1) is PluginFTFuzzyOption -> reporter.requires(element, BASEX_6_1) is PluginNonDeterministicFunctionCall -> reporter.requires(element, BASEX_8_4) is XPathTernaryConditionalExpr -> reporter.requires(element, BASEX_9_1) is PluginUpdateExpr -> when (element.conformanceElement.elementType) { XQueryTokenType.K_UPDATE -> reporter.requires(element, BASEX_7_8) else -> reporter.requires(element, BASEX_8_5) } is XPathIfExpr -> when (element.conformanceElement.elementType) { XPathTokenProvider.KIf -> reporter.requires( element, BASEX_9_1, BaseXBundle.message("conformance.if-without-else") ) else -> { } } else -> { } } private val BASEX_6_1 = XpmRequiresProductVersion.since(BaseX.VERSION_6_1) private val BASEX_7_8 = XpmRequiresProductVersion.since(BaseX.VERSION_7_8) private val BASEX_8_4 = XpmRequiresProductVersion.since(BaseX.VERSION_8_4) private val BASEX_8_5 = XpmRequiresProductVersion.since(BaseX.VERSION_8_5) private val BASEX_9_1 = XpmRequiresProductVersion.since(BaseX.VERSION_9_1) }
apache-2.0
26307bee4852a84633bab2cd58c163be
48.666667
93
0.753915
4.021851
false
false
false
false
rhdunn/xquery-intellij-plugin
src/lang-xqdoc/main/uk/co/reecedunn/intellij/plugin/xqdoc/documentation/XQDocDocumentationDownloader.kt
1
4004
/* * Copyright (C) 2019-2020 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.xqdoc.documentation import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.PathManager import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.io.HttpRequests import com.intellij.util.xmlb.XmlSerializerUtil import uk.co.reecedunn.intellij.plugin.core.progress.TaskManager import uk.co.reecedunn.intellij.plugin.core.progress.TaskProgressListener import uk.co.reecedunn.intellij.plugin.core.progress.waitCancellable import uk.co.reecedunn.intellij.plugin.xpm.lang.documentation.XpmDocumentationSource import uk.co.reecedunn.intellij.plugin.xqdoc.resources.XQDocBundle import java.io.File import java.io.IOException @State(name = "XdmDocumentationDownloader", storages = [Storage("xijp_settings.xml")]) class XQDocDocumentationDownloader : PersistentStateComponent<XQDocDocumentationDownloader> { var basePath: String? = null get() = field ?: "${PathManager.getSystemPath()}/xdm-cache/documentation" private val tasks = TaskManager<XpmDocumentationSource>() fun addListener(listener: TaskProgressListener<XpmDocumentationSource>): Boolean = tasks.addListener(listener) fun removeListener(listener: TaskProgressListener<XpmDocumentationSource>): Boolean { return tasks.removeListener(listener) } fun download(source: XpmDocumentationSource): Boolean { return tasks.backgroundable(XQDocBundle.message("documentation-source.download.title"), source) { indicator -> val file = File("$basePath/${source.path}") try { HttpRequests.request(source.href).saveToFile(file, indicator) } catch (e: IOException) { return@backgroundable } XQDocDocumentationSourceProvider.invalidate(source) } } fun load(source: XpmDocumentationSource, download: Boolean = false): VirtualFile? { val file = file(source) if (download) { if (!file.exists() || tasks.isActive(source)) { if (download(source)) waitCancellable { !tasks.isActive(source) } waitCancellable { tasks.isActive(source) } } } return LocalFileSystem.getInstance().findFileByIoFile(file) } fun file(source: XpmDocumentationSource): File = File("$basePath/${source.path}") fun status(source: XpmDocumentationSource): XQDocDocumentationDownloadStatus = when { tasks.isActive(source) -> XQDocDocumentationDownloadStatus.Downloading file(source).exists() -> XQDocDocumentationDownloadStatus.Downloaded else -> XQDocDocumentationDownloadStatus.NotDownloaded } // region PersistentStateComponent override fun getState(): XQDocDocumentationDownloader = this override fun loadState(state: XQDocDocumentationDownloader): Unit = XmlSerializerUtil.copyBean(state, this) // endregion companion object { fun getInstance(): XQDocDocumentationDownloader { return ApplicationManager.getApplication().getService(XQDocDocumentationDownloader::class.java) } } }
apache-2.0
f1e37a8744d4984ae85097ce8417409c
40.708333
118
0.726274
4.824096
false
false
false
false
westnordost/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/data/user/UserController.kt
1
4008
package de.westnordost.streetcomplete.data.user import android.util.Log import de.westnordost.osmapi.OsmConnection import de.westnordost.streetcomplete.data.UserApi import de.westnordost.streetcomplete.data.osmnotes.OsmAvatarsDownloader import de.westnordost.streetcomplete.data.user.achievements.* import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import oauth.signpost.OAuthConsumer import java.util.concurrent.CopyOnWriteArrayList import javax.inject.Inject import javax.inject.Singleton /** Controller that handles user login, logout, auth and updated data */ @Singleton class UserController @Inject constructor( private val userApi: UserApi, private val oAuthStore: OAuthStore, private val userStore: UserStore, private val userAchievementsDao: UserAchievementsDao, private val userLinksDao: UserLinksDao, private val avatarsDownloader: OsmAvatarsDownloader, private val statisticsUpdater: StatisticsUpdater, private val statisticsDao: QuestStatisticsDao, private val countryStatisticsDao: CountryStatisticsDao, private val osmConnection: OsmConnection ): CoroutineScope by CoroutineScope(Dispatchers.Default), LoginStatusSource, UserAvatarUpdateSource { private val loginStatusListeners: MutableList<UserLoginStatusListener> = CopyOnWriteArrayList() private val userAvatarListeners: MutableList<UserAvatarListener> = CopyOnWriteArrayList() override val isLoggedIn: Boolean get() = oAuthStore.isAuthorized fun logIn(consumer: OAuthConsumer) { oAuthStore.oAuthConsumer = consumer osmConnection.oAuth = consumer updateUser() loginStatusListeners.forEach { it.onLoggedIn() } } fun logOut() { userStore.clear() oAuthStore.oAuthConsumer = null osmConnection.oAuth = null statisticsDao.clear() countryStatisticsDao.clear() userAchievementsDao.clear() userLinksDao.clear() userStore.clear() loginStatusListeners.forEach { it.onLoggedOut() } } fun updateUser() = launch(Dispatchers.IO) { try { val userDetails = userApi.getMine() userStore.setDetails(userDetails) val profileImageUrl = userDetails.profileImageUrl if (profileImageUrl != null) { updateAvatar(userDetails.id, profileImageUrl) } updateStatistics(userDetails.id) } catch (e: Exception) { Log.w(TAG, "Unable to download user details", e) } } private fun updateAvatar(userId: Long, imageUrl: String) = launch(Dispatchers.IO) { avatarsDownloader.download(userId, imageUrl) userAvatarListeners.forEach { it.onUserAvatarUpdated() } } private fun updateStatistics(userId: Long) = launch(Dispatchers.IO) { statisticsUpdater.updateFromBackend(userId) } override fun addLoginStatusListener(listener: UserLoginStatusListener) { loginStatusListeners.add(listener) } override fun removeLoginStatusListener(listener: UserLoginStatusListener) { loginStatusListeners.remove(listener) } override fun addUserAvatarListener(listener: UserAvatarListener) { userAvatarListeners.add(listener) } override fun removeUserAvatarListener(listener: UserAvatarListener) { userAvatarListeners.remove(listener) } companion object { const val TAG = "UserController" } } interface UserLoginStatusListener { fun onLoggedIn() fun onLoggedOut() } interface UserAvatarListener { fun onUserAvatarUpdated() } interface LoginStatusSource { val isLoggedIn: Boolean fun addLoginStatusListener(listener: UserLoginStatusListener) fun removeLoginStatusListener(listener: UserLoginStatusListener) } interface UserAvatarUpdateSource { fun addUserAvatarListener(listener: UserAvatarListener) fun removeUserAvatarListener(listener: UserAvatarListener) }
gpl-3.0
ffb387b51b3cc42ac5895a4d0d0d65e4
33.852174
101
0.738273
4.875912
false
false
false
false
mitallast/netty-queue
src/main/java/org/mitallast/queue/common/netty/NettyServer.kt
1
2680
package org.mitallast.queue.common.netty import com.typesafe.config.Config import io.netty.bootstrap.ServerBootstrap import io.netty.buffer.ByteBufAllocator import io.netty.buffer.PooledByteBufAllocator import io.netty.channel.* import org.mitallast.queue.common.component.AbstractLifecycleComponent import org.mitallast.queue.common.logging.LoggingService abstract class NettyServer protected constructor( config: Config, logging: LoggingService, protected val provider: NettyProvider, protected val host: String, protected val port: Int ) : AbstractLifecycleComponent(logging) { private val backlog: Int = config.getInt("netty.backlog") private val keepAlive: Boolean = config.getBoolean("netty.keep_alive") private val reuseAddress: Boolean = config.getBoolean("netty.reuse_address") private val tcpNoDelay: Boolean = config.getBoolean("netty.tcp_no_delay") private val sndBuf: Int = config.getInt("netty.snd_buf") private val rcvBuf: Int = config.getInt("netty.rcv_buf") protected var channel: Channel? = null protected var bootstrap: ServerBootstrap? = null override fun doStart() { try { bootstrap = ServerBootstrap() bootstrap!!.group(provider.parent(), provider.child()) .channel(provider.serverChannel()) .childHandler(channelInitializer()) .option(ChannelOption.SO_BACKLOG, backlog) .option(ChannelOption.SO_REUSEADDR, reuseAddress) .option(ChannelOption.SO_KEEPALIVE, keepAlive) .option(ChannelOption.TCP_NODELAY, tcpNoDelay) .option(ChannelOption.SO_SNDBUF, sndBuf) .option(ChannelOption.SO_RCVBUF, rcvBuf) .option<ByteBufAllocator>(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .option<RecvByteBufAllocator>(ChannelOption.RCVBUF_ALLOCATOR, AdaptiveRecvByteBufAllocator()) logger.info("listen {}:{}", host, port) channel = bootstrap!!.bind(host, port) .sync() .channel() } catch (e: InterruptedException) { Thread.currentThread().interrupt() throw RuntimeException(e) } } protected abstract fun channelInitializer(): ChannelInitializer<*> override fun doStop() {} override fun doClose() { try { if (channel != null) { channel!!.close().sync() } } catch (e: InterruptedException) { Thread.currentThread().interrupt() throw RuntimeException(e) } channel = null bootstrap = null } }
mit
850bb439ad6aba449cc619cc2d4ee368
37.285714
109
0.653358
4.743363
false
true
false
false
kazhida/kotos2d
src/jp/kazhida/kotos2d/Kotos2dGLSurfaceView.kt
1
1917
package jp.kazhida.kotos2d import android.content.Context import android.os.Handler import android.opengl.GLSurfaceView import android.util.AttributeSet /** * Created by kazhida on 2013/07/27. */ public class Kotos2dGLSurfaceView(context: Context, attrs: AttributeSet? = null): GLSurfaceView(context, attrs) { class object { val TAG = javaClass<Kotos2dActivity>().getSimpleName() val HANDLER_OPEN_IME_KEYBOARD: Int = 2 val HANDLER_CLOSE_IME_KEYBOARD: Int = 3 //todo: Static handler -> Potential leak! val handler = Handler() var glSurfaceView: Kotos2dGLSurfaceView? = null // todo: クラスができてからやる // var textInputWrapper: = Kotos2dTextInputWrapper? = null public fun queueAccelerometer(x : Float, y : Float, z : Float, timestamp : Long) : Unit { glSurfaceView?.queueEvent{ Kotos2dAccelerometer.onSensorChanged(x, y, z, timestamp) } } } public var renderer: Kotos2dRenderer? = null get() { return $renderer } set(renderer: Kotos2dRenderer?) { $renderer = renderer setRenderer(renderer) } private val contentText: String? get() { // return renderer?.getContentText() return null } public var editText: Kotos2dEditText? = null override fun onResume() { super.onResume() queueEvent { renderer?.handleOnResume() } } override fun onPause() { queueEvent { renderer?.handleOnPause() } //super.onPause() } public fun insertText(text: String?) : Unit { this.queueEvent { renderer?.handleInsertText(text) } } public fun deleteBackward() : Unit { this.queueEvent { renderer?.handleDeleteBackward() } } }
mit
7a2acd6461e16d5ed0d2d2759d1cfd84
24.28
113
0.596306
4.326484
false
false
false
false
WangDaYeeeeee/GeometricWeather
app/src/main/java/wangdaye/com/geometricweather/background/polling/PollingUpdateHelper.kt
1
5586
package wangdaye.com.geometricweather.background.polling import android.content.Context import android.widget.Toast import wangdaye.com.geometricweather.R import wangdaye.com.geometricweather.common.basic.models.Location import wangdaye.com.geometricweather.common.basic.models.weather.Weather import wangdaye.com.geometricweather.common.bus.EventBus import wangdaye.com.geometricweather.common.utils.helpers.AsyncHelper import wangdaye.com.geometricweather.db.DatabaseHelper import wangdaye.com.geometricweather.location.LocationHelper import wangdaye.com.geometricweather.weather.WeatherHelper import wangdaye.com.geometricweather.weather.WeatherHelper.OnRequestWeatherListener class PollingUpdateHelper( private val context: Context, private val locationHelper: LocationHelper, private val weatherHelper: WeatherHelper ) { private var isUpdating = false private var ioController: AsyncHelper.Controller? = null private var locationList = emptyList<Location>().toMutableList() private var listener: OnPollingUpdateListener? = null interface OnPollingUpdateListener { fun onUpdateCompleted( location: Location, old: Weather?, succeed: Boolean, index: Int, total: Int ) fun onPollingCompleted(locationList: List<Location>?) } // control. fun pollingUpdate() { if (isUpdating) { return } isUpdating = true ioController = AsyncHelper.runOnIO({ emitter -> val list = DatabaseHelper.getInstance(context).readLocationList().map { it.copy(weather = DatabaseHelper.getInstance(context).readWeather(it)) } emitter.send(list, true) }, { locations: List<Location>?, _: Boolean -> locations?.let { locationList = it.toMutableList() requestData(0, false) } }) } fun cancel() { isUpdating = false ioController?.cancel() locationHelper.cancel() weatherHelper.cancel() } private fun requestData(position: Int, located: Boolean) { if (locationList[position].weather?.isValid(0.25f) == true) { RequestWeatherCallback(position, locationList.size).requestWeatherSuccess(locationList[position]) return } if (locationList[position].isCurrentPosition && !located) { locationHelper.requestLocation( context, locationList[position], true, RequestLocationCallback(position, locationList.size) ) return } weatherHelper.requestWeather( context, locationList[position], RequestWeatherCallback(position, locationList.size) ) } // interface. fun setOnPollingUpdateListener(l: OnPollingUpdateListener?) { listener = l } // on request location listener. private inner class RequestLocationCallback( private val index: Int, private val total: Int ) : LocationHelper.OnRequestLocationListener { override fun requestLocationSuccess(requestLocation: Location) { locationList[index] = requestLocation if (requestLocation.isUsable) { requestData(index, true) } else { requestLocationFailed(requestLocation) Toast.makeText( context, context.getString(R.string.feedback_not_yet_location), Toast.LENGTH_SHORT ).show() } } override fun requestLocationFailed(requestLocation: Location) { if (locationList[index].isUsable) { requestData(index, true) } else { RequestWeatherCallback(index, total).requestWeatherFailed(locationList[index]) } } } // on request weather listener. private inner class RequestWeatherCallback( private val index: Int, private val total: Int ) : OnRequestWeatherListener { override fun requestWeatherSuccess(requestLocation: Location) { val oldWeather = locationList[index].weather if (requestLocation.weather != null && (oldWeather == null || requestLocation.weather.base.timeStamp != oldWeather.base.timeStamp)) { locationList[index] = requestLocation EventBus.instance .with(Location::class.java) .postValue(requestLocation) listener?.onUpdateCompleted(requestLocation, oldWeather, true, index, total) checkToRequestNextOrCompleted() } else { requestWeatherFailed(requestLocation) } } override fun requestWeatherFailed(requestLocation: Location) { val old = locationList[index].weather locationList[index] = requestLocation listener?.onUpdateCompleted(requestLocation, old, false, index, total) checkToRequestNextOrCompleted() } private fun checkToRequestNextOrCompleted() { if (!isUpdating) { return } val next = index + 1 if (next < total) { requestData(next, false) return } listener?.onPollingCompleted(locationList) isUpdating = false } } }
lgpl-3.0
518105f2f2f6a9145f7abca2aca38a89
30.564972
113
0.613856
5.294787
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/view/step_quiz_review/ui/widget/ReviewStatusView.kt
2
2375
package org.stepik.android.view.step_quiz_review.ui.widget import android.content.Context import android.content.res.ColorStateList import android.util.AttributeSet import android.view.View import android.widget.FrameLayout import android.widget.TextView import androidx.appcompat.content.res.AppCompatResources import androidx.core.view.isVisible import kotlinx.android.synthetic.main.view_review_status.view.* import org.stepic.droid.R import org.stepic.droid.util.resolveColorAttribute import ru.nobird.android.view.base.ui.extension.inflate class ReviewStatusView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : FrameLayout(context, attrs, defStyleAttr) { private val colorActive = AppCompatResources.getColorStateList(context, R.color.color_peer_review_step) private val colorError = ColorStateList.valueOf(context.resolveColorAttribute(R.attr.colorError)) private val drawableActive = R.drawable.bg_peer_review_step_active private val drawableError = R.drawable.bg_peer_review_step_error private val textView: TextView private val imageView: View var status = Status.PENDING set(value) { field = value imageView.isVisible = value == Status.COMPLETED textView.isVisible = value != Status.COMPLETED val (color, drawableRes) = if (value == Status.ERROR) { colorError to drawableError } else { colorActive to drawableActive } textView.setTextColor(color) textView.setBackgroundResource(drawableRes) textView.isEnabled = value != Status.PENDING } var position: Int = 1 set(value) { field = value textView.text = value.toString() } init { val view = inflate(R.layout.view_review_status, true) textView = view.peerReviewStatusText imageView = view.peerReviewStatusImage val typedArray = context.obtainStyledAttributes(attrs, R.styleable.ReviewStatusView) try { position = typedArray.getInteger(R.styleable.ReviewStatusView_position, 1) } finally { typedArray.recycle() } } enum class Status { ERROR, PENDING, IN_PROGRESS, COMPLETED } }
apache-2.0
5cbb7599ad0aa205675eed2bab34f912
31.108108
107
0.679158
4.64775
false
false
false
false
walleth/walleth
app/src/main/java/org/walleth/data/chaininfo/ChainInfo.kt
1
1083
package org.walleth.data.chaininfo import androidx.room.ColumnInfo import androidx.room.Embedded import androidx.room.Entity import kotlinx.android.parcel.Parcelize import org.walleth.enhancedlist.ListItem import java.math.BigInteger import android.os.Parcelable as Parcelable1 @Parcelize data class NativeCurrency( val symbol: String, val name: String = symbol, val decimals: Int = 18 ) : Parcelable1 @Entity(tableName = "chains", primaryKeys = ["chainId"]) @Parcelize data class ChainInfo( override val name: String, val chainId: BigInteger, val networkId: Long, val shortName: String, val rpc: List<String> = emptyList(), val faucets: List<String> = emptyList(), val infoURL: String = "", var order: Int? = null, var starred: Boolean = false, var useEIP1559: Boolean = false, @ColumnInfo(name = "softDeleted") override var deleted: Boolean = false, @Embedded(prefix = "token_") val nativeCurrency: NativeCurrency ) : ListItem, Parcelable1
gpl-3.0
c0828decd71287b6ee66f4199fdda2c0
27.526316
56
0.674977
4.197674
false
false
false
false
NerdNumber9/TachiyomiEH
app/src/main/java/eu/kanade/tachiyomi/data/library/LibraryUpdateNotifier.kt
1
3086
package eu.kanade.tachiyomi.data.library import android.app.Notification import android.app.PendingIntent import android.content.Context import android.content.Intent import android.graphics.BitmapFactory import android.os.Build import android.support.v4.app.NotificationCompat import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.data.notification.Notifications import eu.kanade.tachiyomi.ui.main.MainActivity import eu.kanade.tachiyomi.util.chop import eu.kanade.tachiyomi.util.notification import eu.kanade.tachiyomi.util.notificationManager class LibraryUpdateNotifier(private val context: Context) { /** * Bitmap of the app for notifications. */ val notificationBitmap by lazy { BitmapFactory.decodeResource(context.resources, R.mipmap.ic_launcher) } /** * Shows the notification containing the result of the update done by the service. * * @param updates a list of manga with new updates. */ fun showResultNotification(updates: List<Manga>) { val newUpdates = updates.map { it.title.chop(45) }.toMutableSet() // Append new chapters from a previous, existing notification if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { val previousNotification = context.notificationManager.activeNotifications .find { it.id == Notifications.ID_LIBRARY_RESULT } if (previousNotification != null) { val oldUpdates = previousNotification.notification.extras .getString(Notification.EXTRA_BIG_TEXT) if (!oldUpdates.isNullOrEmpty()) { newUpdates += oldUpdates.split("\n") } } } context.notificationManager.notify(Notifications.ID_LIBRARY_RESULT, context.notification(Notifications.CHANNEL_LIBRARY) { setSmallIcon(R.drawable.ic_book_white_24dp) setLargeIcon(notificationBitmap) setContentTitle(context.getString(R.string.notification_new_chapters)) if (newUpdates.size > 1) { setContentText(context.getString(R.string.notification_new_chapters_text, newUpdates.size)) setStyle(NotificationCompat.BigTextStyle().bigText(newUpdates.joinToString("\n"))) setNumber(newUpdates.size) } else { setContentText(newUpdates.first()) } priority = NotificationCompat.PRIORITY_HIGH setContentIntent(getNotificationIntent(context)) setAutoCancel(true) }) } /** * Returns an intent to open the main activity. */ private fun getNotificationIntent(context: Context): PendingIntent { val intent = Intent(context, MainActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP intent.action = MainActivity.SHORTCUT_RECENTLY_UPDATED return PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT) } }
apache-2.0
b4c626562543d2baa036ae55ba45d903
40.16
129
0.683409
4.762346
false
false
false
false
da1z/intellij-community
uast/uast-java/src/org/jetbrains/uast/java/JavaAbstractUElement.kt
1
3315
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.uast.java import com.intellij.psi.* import org.jetbrains.uast.* import org.jetbrains.uast.java.internal.JavaUElementWithComments abstract class JavaAbstractUElement(givenParent: UElement?) : JavaUElementWithComments, JvmDeclarationUElement { @Suppress("unused") // Used in Kotlin 1.2, to be removed in 2018.1 @Deprecated("use JavaAbstractUElement(givenParent)", ReplaceWith("JavaAbstractUElement(givenParent)")) constructor() : this(null) override fun equals(other: Any?): Boolean { if (other !is UElement || other.javaClass != this.javaClass) return false return if (this.psi != null) this.psi == other.psi else this === other } override fun hashCode() = psi?.hashCode() ?: System.identityHashCode(this) override fun asSourceString(): String { return this.psi?.text ?: super<JavaUElementWithComments>.asSourceString() } override fun toString() = asRenderString() override val uastParent: UElement? by lz { givenParent ?: convertParent() } protected open fun convertParent(): UElement? = getPsiParentForLazyConversion()?.let { JavaConverter.unwrapElements(it).toUElement() }?.also { if (it === this) throw IllegalStateException("lazy parent loop for $this") if (it.psi != null && it.psi === this.psi) throw IllegalStateException( "lazy parent loop: psi ${this.psi}(${this.psi?.javaClass}) for $this of ${this.javaClass}") } protected open fun getPsiParentForLazyConversion() = this.psi?.parent //explicitly overridden in abstract class to be binary compatible with Kotlin override val comments: List<UComment> get() = super<JavaUElementWithComments>.comments override val sourcePsi: PsiElement? get() = super.sourcePsi override val javaPsi: PsiElement? get() = super.javaPsi } abstract class JavaAbstractUExpression(givenParent: UElement?) : JavaAbstractUElement(givenParent), UExpression { @Suppress("unused") // Used in Kotlin 1.2, to be removed in 2018.1 @Deprecated("use JavaAbstractUExpression(givenParent)", ReplaceWith("JavaAbstractUExpression(givenParent)")) constructor() : this(null) override fun evaluate(): Any? { val project = psi?.project ?: return null return JavaPsiFacade.getInstance(project).constantEvaluationHelper.computeConstantExpression(psi) } override val annotations: List<UAnnotation> get() = emptyList() override fun getExpressionType(): PsiType? { val expression = psi as? PsiExpression ?: return null return expression.type } override fun getPsiParentForLazyConversion(): PsiElement? = super.getPsiParentForLazyConversion()?.let { when (it) { is PsiResourceExpression -> it.parent else -> it } } }
apache-2.0
d8a090c07817adde4a6a426198179666
36.247191
113
0.731222
4.675599
false
false
false
false
CarlosEsco/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/ui/browse/migration/manga/MigrateMangaPresenter.kt
1
1895
package eu.kanade.tachiyomi.ui.browse.migration.manga import android.os.Bundle import eu.kanade.domain.manga.interactor.GetFavorites import eu.kanade.presentation.browse.MigrateMangaState import eu.kanade.presentation.browse.MigrateMangaStateImpl import eu.kanade.presentation.browse.MigrationMangaState import eu.kanade.tachiyomi.ui.base.presenter.BasePresenter import eu.kanade.tachiyomi.util.lang.launchIO import eu.kanade.tachiyomi.util.system.logcat import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.receiveAsFlow import logcat.LogPriority import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get class MigrateMangaPresenter( private val sourceId: Long, private val state: MigrateMangaStateImpl = MigrationMangaState() as MigrateMangaStateImpl, private val getFavorites: GetFavorites = Injekt.get(), ) : BasePresenter<MigrationMangaController>(), MigrateMangaState by state { private val _events = Channel<Event>(Int.MAX_VALUE) val events = _events.receiveAsFlow() override fun onCreate(savedState: Bundle?) { super.onCreate(savedState) presenterScope.launchIO { getFavorites .subscribe(sourceId) .catch { exception -> logcat(LogPriority.ERROR, exception) _events.send(Event.FailedFetchingFavorites) } .map { list -> list.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.title }) } .collectLatest { sortedList -> state.isLoading = false state.items = sortedList } } } sealed class Event { object FailedFetchingFavorites : Event() } }
apache-2.0
4ba0bdb2033893550854b7d6c2cded47
36.156863
94
0.696042
4.679012
false
false
false
false
Heiner1/AndroidAPS
automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerIob.kt
1
2941
package info.nightscout.androidaps.plugins.general.automation.triggers import android.widget.LinearLayout import com.google.common.base.Optional import dagger.android.HasAndroidInjector import info.nightscout.androidaps.automation.R import info.nightscout.shared.logging.LTag import info.nightscout.androidaps.plugins.general.automation.elements.Comparator import info.nightscout.androidaps.plugins.general.automation.elements.InputInsulin import info.nightscout.androidaps.plugins.general.automation.elements.LabelWithElement import info.nightscout.androidaps.plugins.general.automation.elements.LayoutBuilder import info.nightscout.androidaps.plugins.general.automation.elements.StaticLabel import info.nightscout.androidaps.utils.JsonHelper import org.json.JSONObject class TriggerIob(injector: HasAndroidInjector) : Trigger(injector) { var insulin = InputInsulin() var comparator: Comparator = Comparator(rh) constructor(injector: HasAndroidInjector, triggerIob: TriggerIob) : this(injector) { insulin = InputInsulin(triggerIob.insulin) comparator = Comparator(rh, triggerIob.comparator.value) } fun setValue(value: Double): TriggerIob { insulin.value = value return this } fun comparator(comparator: Comparator.Compare): TriggerIob { this.comparator.value = comparator return this } override fun shouldRun(): Boolean { val profile = profileFunction.getProfile() ?: return false val iob = iobCobCalculator.calculateFromTreatmentsAndTemps(dateUtil.now(), profile) if (comparator.value.check(iob.iob, insulin.value)) { aapsLogger.debug(LTag.AUTOMATION, "Ready for execution: " + friendlyDescription()) return true } aapsLogger.debug(LTag.AUTOMATION, "NOT ready for execution: " + friendlyDescription()) return false } override fun dataJSON(): JSONObject = JSONObject() .put("insulin", insulin.value) .put("comparator", comparator.value.toString()) override fun fromJSON(data: String): Trigger { val d = JSONObject(data) insulin.value = JsonHelper.safeGetDouble(d, "insulin") comparator.setValue(Comparator.Compare.valueOf(JsonHelper.safeGetString(d, "comparator")!!)) return this } override fun friendlyName(): Int = R.string.iob override fun friendlyDescription(): String = rh.gs(R.string.iobcompared, rh.gs(comparator.value.stringRes), insulin.value) override fun icon(): Optional<Int> = Optional.of(R.drawable.ic_keyboard_capslock) override fun duplicate(): Trigger = TriggerIob(injector, this) override fun generateDialog(root: LinearLayout) { LayoutBuilder() .add(StaticLabel(rh, R.string.iob, this)) .add(comparator) .add(LabelWithElement(rh, rh.gs(R.string.iob_u), "", insulin)) .build(root) } }
agpl-3.0
128e7cac1cb068f59aee980a10ad0948
38.756757
100
0.716763
4.545595
false
false
false
false
Heiner1/AndroidAPS
diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/AppConfirmSettingResponsePacket.kt
1
1490
package info.nightscout.androidaps.diaconn.packet import dagger.android.HasAndroidInjector import info.nightscout.androidaps.diaconn.DiaconnG8Pump import info.nightscout.shared.logging.LTag import javax.inject.Inject /** * AppConfirmSettingResponsePacket */ class AppConfirmSettingResponsePacket( injector: HasAndroidInjector ) : DiaconnG8Packet(injector ) { @Inject lateinit var diaconnG8Pump: DiaconnG8Pump var result =0 init { msgType = 0xB7.toByte() aapsLogger.debug(LTag.PUMPCOMM, "AppConfirmSettingReqPacket Response ") } override fun handleMessage(data: ByteArray?) { val defectCheck = defect(data) if (defectCheck != 0) { aapsLogger.debug(LTag.PUMPCOMM, "AppConfirmSettingResponsePacket Got some Error") failed = true return } else failed = false val bufferData = prefixDecode(data) result = getByteToInt(bufferData) aapsLogger.debug(LTag.PUMPCOMM, "Result --> ${result}") if(!isSuccSettingResponseResult(result)) { diaconnG8Pump.resultErrorCode = result failed = true return } // The bolus progress diallog opens only when the confirm result is successfull if(diaconnG8Pump.bolusConfirmMessage == 0x07.toByte()) { diaconnG8Pump.isReadyToBolus = true } } override fun getFriendlyName(): String { return "PUMP_APP_CONFIRM_SETTING_RESPONSE" } }
agpl-3.0
37431b56c6d5b79a5e6145dd2ac6089a
30.723404
93
0.675168
4.584615
false
false
false
false
kvakil/venus
src/main/kotlin/venus/riscv/MachineCode.kt
1
1112
package venus.riscv /** * Represents the machine code of an instruction. * * For now this only supports RV32. * * @param encoding the underlying machine code of the instruction */ class MachineCode(private var encoding: Int) { val length = 4 /** * Returns the value of the given instruction field for this instruction. * * @param ifield the instruction field to get * @return the value of the given instruction field */ operator fun get(ifield: InstructionField): Int { val mask = ((1L shl ifield.hi) - (1L shl ifield.lo)).toInt() return (encoding and mask) ushr ifield.lo } /** * Sets an instruction field to the given value. * * @param ifield the instruction field to set * @param value the value to set the field to */ operator fun set(ifield: InstructionField, value: Int) { val mask = ((1L shl ifield.hi) - (1L shl ifield.lo)).toInt() encoding = encoding and mask.inv() encoding = encoding or ((value shl ifield.lo) and mask) } override fun toString() = encoding.toString() }
mit
833de82dc82d941f79c64f7b68bdcbdf
29.081081
77
0.642986
4.043636
false
false
false
false
xurxodev/Movies-Kotlin-Kata
app/src/main/kotlin/com/xurxodev/movieskotlinkata/data/FakeMovieRepository.kt
1
3641
package com.xurxodev.movieskotlinkata.data import android.app.Application import com.xurxodev.moviesandroidkotlin.R import com.xurxodev.movieskotlinkata.domain.boundary.MovieRepository import com.xurxodev.movieskotlinkata.domain.common.functional.Either import com.xurxodev.movieskotlinkata.domain.common.functional.flatMap import com.xurxodev.movieskotlinkata.domain.common.functional.fold import com.xurxodev.movieskotlinkata.domain.entity.Movie import com.xurxodev.movieskotlinkata.domain.failures.GetMovieFailure import com.xurxodev.movieskotlinkata.domain.failures.GetMoviesFailure class FakeMovieRepository (val context: Application): MovieRepository { override fun getAll (): Either<GetMoviesFailure,List<Movie>> { try { val baseAddress = context.getString(R.string.base_address) var movies:MutableList<Movie> = mutableListOf() movies.add(Movie(1, "Inferno", baseAddress + "anmLLbDx9d98NMZRyVUtxwJR6ab.jpg", "After waking up in a hospital with amnesia, professor Robert Langdon and a doctor must race against time to foil a deadly global plot.")) movies.add(Movie(2, "Jack Reacher: Never Go Back", baseAddress + "4ynQYtSEuU5hyipcGkfD6ncwtwz.jpg", "Jack Reacher must uncover the truth behind a major government conspiracy in order to clear his name. On the run as a fugitive from the law, Reacher uncovers a potential secret from his past that could change his life forever.")) movies.add(Movie(3, "Star Trek Beyond", "" + baseAddress + "doqRJwhRFsHHneYG82bM0hSTqpz.jpg", "The USS Enterprise crew explores the furthest reaches of uncharted space, where they encounter a mysterious new enemy who puts them and everything the Federation stands for to the test.")) movies.add(Movie(4, "Doctor Strange", baseAddress + "2wgKgQAqso1p1yP6unsq9nl7Xdc.jpg", "After his career is destroyed, a brilliant but arrogant surgeon gets a new lease on life when a sorcerer takes him under his wing and trains him to defend the world against evil.")) movies.add(Movie(5, "The Girl on the Train", baseAddress + "fpq86AP0YBYUwNgDvUj5kxwycxH.jpg", "Rachel Watson, devastated by her recent divorce, spends her daily commute fantasizing about the seemingly perfect couple who live in a house that her train passes every day, until one morning she sees something shocking happen there and becomes entangled in the mystery that unfolds.")) movies.add(Movie(6, "Deepwater Horizon", baseAddress + "zjYdnBHbIOYBqKZxvBUsT5MevUA.jpg", "A story set on the offshore drilling rig Deepwater Horizon, which exploded during April 2010 and created the worst oil spill in U.S. history.")) movies.add(Movie(7, "A Monster Calls", baseAddress + "xVW8REyVqKwxAtUYY07UGlZH43L.jpg", "A boy attempts to deal with his mother's illness and the bullying of his classmates by escaping to a fantastical world.")) simulateDelay(); return Either.Right(movies.toList()); } catch (ex: Exception) { return Either.Left(GetMoviesFailure.NetworkConnection()) } } private fun simulateDelay() { try { Thread.sleep(2000) } catch (e: InterruptedException) { e.printStackTrace() } } override fun getById (id: Long): Either<GetMovieFailure,Movie> { return getAll().fold({Either.Left(GetMovieFailure.NetworkConnection())},{ if (it.any { movie -> movie.id == id }){ Either.Right(it.first{it.id == id}) } else { Either.Left(GetMovieFailure.MovieNotFound()) } }) } }
apache-2.0
422de7387d9b7e8652a94e111e44315c
61.775862
393
0.723153
3.784823
false
false
false
false
Maccimo/intellij-community
platform/build-scripts/groovy/org/jetbrains/intellij/build/impl/SVGPreBuilder.kt
4
2708
// 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.intellij.build.impl import org.jetbrains.intellij.build.BuildContext import org.jetbrains.intellij.build.BuildOptions import org.jetbrains.intellij.build.TraceManager.spanBuilder import java.nio.file.Files import java.nio.file.Path import java.util.concurrent.ForkJoinTask /* Please do not convert this to direct call of ImageSvgPreCompiler since it brings too much modules to build scripts classpath, and it'll be too slow to compile by jps-bootstrap Please do not call it via constructing special classloader, since external process does not take too much time, and it's much easier to reason about */ object SVGPreBuilder { fun createPrebuildSvgIconsTask(context: BuildContext): ForkJoinTask<*>? { return createSkippableTask(spanBuilder("prebuild SVG icons"), BuildOptions.SVGICONS_PREBUILD_STEP, context) { val requestBuilder = StringBuilder() // build for all modules - so, icon db will be suitable for any non-bundled plugin for (module in context.project.modules) { requestBuilder.append(context.getModuleOutputDir(module).toString()).append("\n") } val requestFile = context.paths.tempDir.resolve("svg-prebuild-request.txt") Files.createDirectories(requestFile.parent) Files.writeString(requestFile, requestBuilder) val svgToolClasspath = context.getModuleRuntimeClasspath(module = context.findRequiredModule("intellij.platform.images.build"), forTests = false) runSvgTool(context = context, svgToolClasspath = svgToolClasspath, requestFile = requestFile) } } private fun runSvgTool(context: BuildContext, svgToolClasspath: List<String>, requestFile: Path) { val dbDir = context.paths.tempDir.resolve("icons.db.dir") runJava( context = context, mainClass = "org.jetbrains.intellij.build.images.ImageSvgPreCompiler", args = listOf(dbDir.toString(), requestFile.toString()) + context.applicationInfo.svgProductIcons, jvmArgs = listOf("-Xmx1024m"), classPath = svgToolClasspath ) Files.newDirectoryStream(dbDir).use { dirStream -> var found = false for (file in dirStream) { if (!Files.isRegularFile(file)) { context.messages.error("SVG tool: output must be a regular file: $file") } found = true context.addDistFile(java.util.Map.entry(file, "bin/icons")) } if (!found) { context.messages.error("SVG tool: after running SVG prebuild it must be a least one file at $dbDir") } } } }
apache-2.0
bcd0f37067f26ce3619e2135ebc89804
42
133
0.713811
4.346709
false
false
false
false
KotlinNLP/SimpleDNN
src/main/kotlin/com/kotlinnlp/simplednn/simplemath/ndarray/sparsebinary/SparseBinaryNDArrayFactory.kt
1
3724
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ package com.kotlinnlp.simplednn.simplemath.ndarray.sparsebinary import com.kotlinnlp.simplednn.simplemath.ndarray.Indices import com.kotlinnlp.simplednn.simplemath.ndarray.NDArrayFactory import com.kotlinnlp.simplednn.simplemath.ndarray.Shape import com.kotlinnlp.simplednn.simplemath.ndarray.VectorIndices /** * */ object SparseBinaryNDArrayFactory : NDArrayFactory<SparseBinaryNDArray> { /** * Private val used to serialize the class (needed by Serializable). */ @Suppress("unused") private const val serialVersionUID: Long = 1L /** * @param shape shape * * @return a new empty [SparseBinaryNDArray] */ override fun emptyArray(shape: Shape): SparseBinaryNDArray { TODO("not implemented") } /** * Build a new [SparseBinaryNDArray] filled with zeros. * * @param shape shape * * @return a new [SparseBinaryNDArray] */ override fun zeros(shape: Shape): SparseBinaryNDArray { TODO("not implemented") } /** * Build a new diagonal [SparseBinaryNDArray] filled with ones. * * @param size the number of rows and columns * * @return a new [SparseBinaryNDArray] */ override fun eye(size: Int): SparseBinaryNDArray = this.arrayOf(activeIndices = Array(size) { i -> Indices(i, i) }, shape = Shape(size, size)) /** * Build a new [SparseBinaryNDArray] filled with a constant value. * * @param shape shape * @param value the init value * * @return a new [SparseBinaryNDArray] */ override fun fill(shape: Shape, value: Double): SparseBinaryNDArray { TODO("not implemented") } /** * Build a new [SparseBinaryNDArray] filled with zeros but one with 1.0. * * @param length the length of the array * @param oneAt the index of the one element * * @return a oneHotEncoder [SparseBinaryNDArray] */ override fun oneHotEncoder(length: Int, oneAt: Int): SparseBinaryNDArray { TODO("not implemented") } /** * Build a new [SparseBinaryNDArray] filled with random values uniformly distributed in range [[from], [to]]. * * @param shape shape * @param from inclusive lower bound of random values range * @param to inclusive upper bound of random values range * * @return a new [SparseBinaryNDArray] filled with random values */ override fun random(shape: Shape, from: Double, to: Double): SparseBinaryNDArray { TODO("not implemented") } /** * */ fun arrayOf(activeIndices: List<Int>, shape: Shape): SparseBinaryNDArray { require(shape.dim1 == 1 || shape.dim2 == 1) { "Invalid shape (only a 1-dim SparseBinaryNDArray can be created given a list of active indices)" } val vectorMap = mutableMapOf<Int, VectorIndices?>(Pair(0, activeIndices.toMutableList())) val indicesMap = mutableMapOf<Int, VectorIndices?>() activeIndices.forEach { i -> indicesMap[i] = null } return if (shape.dim1 == 1) SparseBinaryNDArray(activeIndicesByRow = vectorMap, activeIndicesByColumn = indicesMap, shape = shape) else SparseBinaryNDArray(activeIndicesByRow = indicesMap, activeIndicesByColumn = vectorMap, shape = shape) } /** * */ fun arrayOf(activeIndices: Array<Indices>, shape: Shape): SparseBinaryNDArray { val res = SparseBinaryNDArray(shape = shape) activeIndices.forEach { (i, j) -> res.set(i, j) } return res } }
mpl-2.0
714325608879ef2bf561aecc9d417c26
28.322835
111
0.675886
4.236633
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/whatsnew/FeatureAnnouncementDialogFragment.kt
1
3835
package org.wordpress.android.ui.whatsnew import android.app.Dialog import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.fragment.app.DialogFragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import org.wordpress.android.R import org.wordpress.android.WordPress import org.wordpress.android.ui.WPWebViewActivity import org.wordpress.android.util.extensions.setStatusBarAsSurfaceColor import javax.inject.Inject class FeatureAnnouncementDialogFragment : DialogFragment() { @Inject lateinit var viewModelFactory: ViewModelProvider.Factory private lateinit var viewModel: FeatureAnnouncementViewModel companion object { const val TAG = "FEATURE_ANNOUNCEMENT_DIALOG_FRAGMENT" } override fun getTheme(): Int { return R.style.FeatureAnnouncementDialogFragment } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val dialog = super.onCreateDialog(savedInstanceState) viewModel = ViewModelProvider(this, viewModelFactory) .get(FeatureAnnouncementViewModel::class.java) dialog.setStatusBarAsSurfaceColor() return dialog } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.feature_announcement_dialog_fragment, container, false) val progressIndicator = view.findViewById<View>(R.id.feature_list_progress_container) val versionLabel = view.findViewById<TextView>(R.id.feature_announcement_version_label) val closeButton = view.findViewById<View>(R.id.close_feature_announcement_button) closeButton.setOnClickListener { viewModel.onCloseDialogButtonPressed() } val recyclerView = view.findViewById<RecyclerView>(R.id.feature_list) recyclerView.layoutManager = LinearLayoutManager(recyclerView.context) val featureAdapter = FeatureAnnouncementListAdapter(this) recyclerView.adapter = featureAdapter val titleTextView = view.findViewById<TextView>(R.id.feature_announcement_dialog_label) val appName = getString(R.string.app_name) val title = getString(R.string.feature_announcement_dialog_label, appName) titleTextView.text = title viewModel.uiModel.observe(this, Observer { it?.let { uiModel -> progressIndicator.visibility = if (uiModel.isProgressVisible) View.VISIBLE else View.GONE versionLabel.text = getString(R.string.version_with_name_param, uiModel.appVersion) featureAdapter.toggleFooterVisibility(uiModel.isFindOutMoreVisible) } }) viewModel.onDialogClosed.observe(this, Observer { dismiss() }) viewModel.onAnnouncementDetailsRequested.observe(this, Observer { detailsUrl -> WPWebViewActivity.openURL(context, detailsUrl) }) viewModel.featureItems.observe(this, Observer { featureItems -> featureAdapter.updateList(featureItems) }) viewModel.start() return view } override fun onAttach(context: Context) { super.onAttach(context) (requireActivity().applicationContext as WordPress).component().inject(this) } override fun onPause() { super.onPause() viewModel.onSessionPaused() } override fun onDestroy() { super.onDestroy() viewModel.onSessionEnded() } override fun onStart() { super.onStart() viewModel.onSessionStarted() } }
gpl-2.0
85013014ed03c78d06a04313331201d5
36.23301
116
0.722555
4.97406
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/stats/refresh/utils/BarChartAccessibilityHelper.kt
1
2664
package org.wordpress.android.ui.stats.refresh.utils import android.graphics.Rect import android.os.Bundle import androidx.core.view.accessibility.AccessibilityNodeInfoCompat import androidx.core.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat import androidx.customview.widget.ExploreByTouchHelper import com.github.mikephil.charting.charts.BarChart import com.github.mikephil.charting.data.BarEntry import com.github.mikephil.charting.interfaces.datasets.IBarDataSet class BarChartAccessibilityHelper( private val barChart: BarChart, private val contentDescriptions: List<String>, private val accessibilityEvent: BarChartAccessibilityEvent ) : ExploreByTouchHelper(barChart) { private val dataSet: IBarDataSet = barChart.data.dataSets.first() interface BarChartAccessibilityEvent { fun onHighlight(entry: BarEntry, index: Int) } init { barChart.setOnHoverListener { _, event -> dispatchHoverEvent(event) } } override fun getVirtualViewAt(x: Float, y: Float): Int { val entry = barChart.getEntryByTouchPoint(x, y) return when { entry != null -> { dataSet.getEntryIndex(entry as BarEntry?) } else -> { INVALID_ID } } } override fun getVisibleVirtualViews(virtualViewIds: MutableList<Int>?) { for (i in 0 until dataSet.entryCount) { virtualViewIds?.add(i) } } override fun onPerformActionForVirtualView( virtualViewId: Int, action: Int, arguments: Bundle? ): Boolean { when (action) { AccessibilityNodeInfoCompat.ACTION_CLICK -> { val entry = dataSet.getEntryForIndex(virtualViewId) accessibilityEvent.onHighlight(entry, virtualViewId) return true } } return false } @Suppress("DEPRECATION") override fun onPopulateNodeForVirtualView( virtualViewId: Int, node: AccessibilityNodeInfoCompat ) { node.contentDescription = contentDescriptions[virtualViewId] barChart.highlighted?.let { highlights -> highlights.forEach { highlight -> if (highlight.dataIndex == virtualViewId) { node.isSelected = true } } } node.addAction(AccessibilityActionCompat.ACTION_CLICK) val entryRectF = barChart.getBarBounds(dataSet.getEntryForIndex(virtualViewId)) val entryRect = Rect() entryRectF.round(entryRect) node.setBoundsInParent(entryRect) } }
gpl-2.0
1abca709dc76fae06bf2b51ac644942d
30.714286
93
0.659159
4.774194
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/engagement/UserProfileBottomSheetFragment.kt
1
6745
package org.wordpress.android.ui.engagement import android.content.Context import android.content.DialogInterface import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import android.widget.ImageView import android.widget.TextView import androidx.core.view.ViewCompat import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelStoreOwner import com.google.android.material.bottomsheet.BottomSheetBehavior import com.google.android.material.bottomsheet.BottomSheetDialog import com.google.android.material.bottomsheet.BottomSheetDialogFragment import org.wordpress.android.R import org.wordpress.android.WordPress import org.wordpress.android.ui.engagement.BottomSheetUiState.UserProfileUiState import org.wordpress.android.ui.utils.UiHelpers import org.wordpress.android.util.GravatarUtils import org.wordpress.android.util.PhotonUtils import org.wordpress.android.util.PhotonUtils.Quality.HIGH import org.wordpress.android.util.UrlUtils import org.wordpress.android.util.image.ImageManager import org.wordpress.android.util.image.ImageType.AVATAR_WITH_BACKGROUND import org.wordpress.android.util.image.ImageType.BLAVATAR import org.wordpress.android.viewmodel.ResourceProvider import javax.inject.Inject class UserProfileBottomSheetFragment : BottomSheetDialogFragment() { @Inject lateinit var viewModelFactory: ViewModelProvider.Factory @Inject lateinit var imageManager: ImageManager @Inject lateinit var uiHelpers: UiHelpers @Inject lateinit var resourceProvider: ResourceProvider private lateinit var viewModel: UserProfileViewModel companion object { const val USER_PROFILE_VIEW_MODEL_KEY = "user_profile_view_model_key" fun newInstance(viewModelKey: String): UserProfileBottomSheetFragment { val fragment = UserProfileBottomSheetFragment() val bundle = Bundle() bundle.putString(USER_PROFILE_VIEW_MODEL_KEY, viewModelKey) fragment.arguments = bundle return fragment } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.user_profile_bottom_sheet, container) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val vmKey = requireArguments().getString(USER_PROFILE_VIEW_MODEL_KEY)!! ViewCompat.setAccessibilityPaneTitle(view, getString(R.string.user_profile_bottom_sheet_description)) viewModel = ViewModelProvider(parentFragment as ViewModelStoreOwner, viewModelFactory) .get(vmKey, UserProfileViewModel::class.java) initObservers(view) dialog?.setOnShowListener { dialogInterface -> val sheetDialog = dialogInterface as? BottomSheetDialog val bottomSheet = sheetDialog?.findViewById<View>( com.google.android.material.R.id.design_bottom_sheet ) as? FrameLayout bottomSheet?.let { val behavior = BottomSheetBehavior.from(it) val metrics = resources.displayMetrics behavior.peekHeight = metrics.heightPixels } } } private fun initObservers(view: View) { val userAvatar = view.findViewById<ImageView>(R.id.user_avatar) val blavatar = view.findViewById<ImageView>(R.id.user_site_blavatar) val userName = view.findViewById<TextView>(R.id.user_name) val userLogin = view.findViewById<TextView>(R.id.user_login) val userBio = view.findViewById<TextView>(R.id.user_bio) val siteTitle = view.findViewById<TextView>(R.id.site_title) val siteUrl = view.findViewById<TextView>(R.id.site_url) val siteSectionHeader = view.findViewById<TextView>(R.id.site_section_header) val siteData = view.findViewById<View>(R.id.site_data) viewModel.bottomSheetUiState.observe(viewLifecycleOwner, { state -> when (state) { is UserProfileUiState -> { val avatarSz = resourceProvider.getDimensionPixelSize(R.dimen.user_profile_bottom_sheet_avatar_sz) val blavatarSz = resourceProvider.getDimensionPixelSize(R.dimen.avatar_sz_medium) imageManager.loadIntoCircle( userAvatar, AVATAR_WITH_BACKGROUND, GravatarUtils.fixGravatarUrl(state.userAvatarUrl, avatarSz) ) userName.text = state.userName userLogin.text = if (state.userLogin.isNotBlank()) { getString(R.string.at_username, state.userLogin) } else { "" } if (state.userBio.isNotBlank()) { userBio.text = state.userBio userBio.visibility = View.VISIBLE } else { userBio.visibility = View.GONE } imageManager.load( blavatar, BLAVATAR, PhotonUtils.getPhotonImageUrl(state.blavatarUrl, blavatarSz, blavatarSz, HIGH) ) if (state.hasSiteUrl) { siteTitle.text = state.siteTitle siteUrl.text = UrlUtils.getHost(state.siteUrl) siteData.setOnClickListener { state.onSiteClickListener?.invoke( state.siteId, state.siteUrl, state.blogPreviewSource ) } siteSectionHeader.visibility = View.VISIBLE blavatar.visibility = View.VISIBLE siteData.visibility = View.VISIBLE } else { siteSectionHeader.visibility = View.GONE blavatar.visibility = View.GONE siteData.visibility = View.GONE } } } }) } override fun onAttach(context: Context) { super.onAttach(context) (requireActivity().applicationContext as WordPress).component().inject(this) } override fun onCancel(dialog: DialogInterface) { super.onCancel(dialog) viewModel.onBottomSheetCancelled() } }
gpl-2.0
7999ef68e86487d61bd7f33b97527074
40.635802
118
0.631134
5.273651
false
false
false
false
ingokegel/intellij-community
tools/ideTestingFramework/intellij.tools.ide.starter/src/com/intellij/ide/starter/ide/IdeProductProvider.kt
2
1229
package com.intellij.ide.starter.ide import com.intellij.ide.starter.di.di import com.intellij.ide.starter.models.IdeInfo import com.intellij.ide.starter.models.IdeProduct import org.kodein.di.direct import org.kodein.di.instance import kotlin.reflect.full.declaredMemberProperties object IdeProductProvider { /** GoLand */ val GO: IdeInfo = di.direct.instance<IdeProduct>().GO /** IntelliJ Ultimate */ val IU: IdeInfo = di.direct.instance<IdeProduct>().IU /** IntelliJ Community */ val IC: IdeInfo = di.direct.instance<IdeProduct>().IC /** Android Studio */ val AI: IdeInfo = di.direct.instance<IdeProduct>().AI /** WebStorm */ val WS: IdeInfo = di.direct.instance<IdeProduct>().WS /** PhpStorm */ val PS: IdeInfo = di.direct.instance<IdeProduct>().PS /** DataGrip */ val DB: IdeInfo = di.direct.instance<IdeProduct>().DB /** RubyMine */ val RM: IdeInfo = di.direct.instance<IdeProduct>().RM /** PyCharm Professional */ val PY: IdeInfo = di.direct.instance<IdeProduct>().PY /** CLion */ val CL: IdeInfo = di.direct.instance<IdeProduct>().CL fun getProducts(): List<IdeInfo> = IdeProductProvider::class.declaredMemberProperties.map { it.get(IdeProductProvider) as IdeInfo } }
apache-2.0
bbccb26d0b587017a68c5464a65b0555
28.285714
133
0.715216
3.625369
false
false
false
false
android/nowinandroid
feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/AuthorsCarousel.kt
1
8951
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.nowinandroid.feature.foryou import androidx.compose.foundation.background import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.sizeIn import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.selection.toggleable import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.ripple.rememberRipple import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.drawBehind import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.onClick import androidx.compose.ui.semantics.semantics import androidx.compose.ui.semantics.stateDescription import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import coil.compose.AsyncImage import com.google.samples.apps.nowinandroid.core.designsystem.icon.NiaIcons import com.google.samples.apps.nowinandroid.core.designsystem.theme.NiaTheme import com.google.samples.apps.nowinandroid.core.domain.model.FollowableAuthor import com.google.samples.apps.nowinandroid.core.model.data.Author import com.google.samples.apps.nowinandroid.core.ui.TrackScrollJank @Composable fun AuthorsCarousel( authors: List<FollowableAuthor>, onAuthorClick: (String, Boolean) -> Unit, modifier: Modifier = Modifier ) { val lazyListState = rememberLazyListState() val tag = "forYou:authors" TrackScrollJank(scrollableState = lazyListState, stateName = tag) LazyRow( modifier = modifier.testTag(tag), contentPadding = PaddingValues(16.dp), horizontalArrangement = Arrangement.spacedBy(8.dp), state = lazyListState ) { items(items = authors, key = { item -> item.author.id }) { followableAuthor -> AuthorItem( author = followableAuthor.author, following = followableAuthor.isFollowed, onAuthorClick = { following -> onAuthorClick(followableAuthor.author.id, following) }, ) } } } @Composable fun AuthorItem( author: Author, following: Boolean, onAuthorClick: (Boolean) -> Unit, modifier: Modifier = Modifier, ) { val followDescription = if (following) { stringResource(R.string.following) } else { stringResource(R.string.not_following) } val followActionLabel = if (following) { stringResource(R.string.unfollow) } else { stringResource(R.string.follow) } Column( modifier = modifier .toggleable( value = following, role = Role.Button, interactionSource = remember { MutableInteractionSource() }, indication = rememberRipple(bounded = false), onValueChange = { newFollowing -> onAuthorClick(newFollowing) }, ) .padding(8.dp) .sizeIn(maxWidth = 48.dp) .semantics(mergeDescendants = true) { // Add information for A11y services, explaining what each state means and // what will happen when the user interacts with the author item. stateDescription = "$followDescription ${author.name}" onClick(label = followActionLabel, action = null) } ) { Box( modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center, ) { val authorImageModifier = Modifier .size(48.dp) .clip(CircleShape) if (author.imageUrl.isEmpty()) { Icon( modifier = authorImageModifier .background(MaterialTheme.colorScheme.surface) .padding(4.dp), imageVector = NiaIcons.Person, contentDescription = null // decorative image ) } else { AsyncImage( modifier = authorImageModifier, model = author.imageUrl, contentScale = ContentScale.Crop, contentDescription = null ) } val backgroundColor = if (following) MaterialTheme.colorScheme.primaryContainer else MaterialTheme.colorScheme.surface Icon( imageVector = if (following) NiaIcons.Check else NiaIcons.Add, contentDescription = null, modifier = Modifier .align(Alignment.BottomEnd) .size(18.dp) .drawBehind { drawCircle( color = backgroundColor, radius = 12.dp.toPx() ) } ) } Spacer(modifier = Modifier.height(4.dp)) Text( text = author.name, style = MaterialTheme.typography.bodySmall, textAlign = TextAlign.Center, fontWeight = FontWeight.Medium, maxLines = 2, modifier = Modifier.fillMaxWidth() ) } } @Preview @Composable fun AuthorCarouselPreview() { NiaTheme { Surface { AuthorsCarousel( authors = listOf( FollowableAuthor( Author( id = "1", name = "Android Dev", imageUrl = "", twitter = "", mediumPage = "", bio = "", ), false ), FollowableAuthor( author = Author( id = "2", name = "Android Dev2", imageUrl = "", twitter = "", mediumPage = "", bio = "", ), isFollowed = true ), FollowableAuthor( Author( id = "3", name = "Android Dev3", imageUrl = "", twitter = "", mediumPage = "", bio = "", ), false ) ), onAuthorClick = { _, _ -> }, ) } } } @Preview @Composable fun AuthorItemPreview() { NiaTheme { Surface { AuthorItem( author = Author( id = "0", name = "Android Dev", imageUrl = "", twitter = "", mediumPage = "", bio = "", ), following = true, onAuthorClick = { } ) } } }
apache-2.0
8b496035f844bf9b643e01c70308e466
34.947791
90
0.566641
5.290189
false
false
false
false
hermantai/samples
kotlin/Mastering-Kotlin-master/Chapter11/src/html/HtmlDsl.kt
1
2859
/** * Code adapted from Kotlin Documentation * https://kotlinlang.org/docs/reference/type-safe-builders.html * * Web-based playground is available * https://play.kotlinlang.org/byExample/09_Kotlin_JS/06_HtmlBuilder?_ga=2.106950851.1336981844.1560437384-1764368703.1548557434 */ interface Element { fun render(builder: StringBuilder, indent: String) } class TextElement(val text: String) : Element { override fun render(builder: StringBuilder, indent: String) { builder.append("$indent$text\n") } } @DslMarker annotation class HtmlTagMarker @HtmlTagMarker abstract class Tag(val name: String) : Element { val children = arrayListOf<Element>() val attributes = hashMapOf<String, String>() protected fun <T : Element> initTag(tag: T, init: T.() -> Unit): T { tag.init() children.add(tag) return tag } override fun render(builder: StringBuilder, indent: String) { builder.append("$indent<$name${renderAttributes()}>\n") for (c in children) { c.render(builder, indent + " ") } builder.append("$indent</$name>\n") } private fun renderAttributes(): String { val builder = StringBuilder() for ((attr, value) in attributes) { builder.append(" $attr=\"$value\"") } return builder.toString() } override fun toString(): String { val builder = StringBuilder() render(builder, "") return builder.toString() } } abstract class TagWithText(name: String) : Tag(name) { operator fun String.unaryPlus() { children.add(TextElement(this)) } } class HTML : TagWithText("html") { fun head(init: Head.() -> Unit) = initTag(Head(), init) fun body(init: Body.() -> Unit) = initTag(Body(), init) } class Head : TagWithText("head") { fun title(init: Title.() -> Unit) = initTag(Title(), init) } class Title : TagWithText("title") abstract class BodyTag(name: String) : TagWithText(name) { fun b(init: B.() -> Unit) = initTag(B(), init) fun p(init: P.() -> Unit) = initTag(P(), init) fun h1(init: H1.() -> Unit) = initTag(H1(), init) fun ul(init: UL.() -> Unit) = initTag(UL(), init) fun li(init: LI.() -> Unit) = initTag(LI(), init) fun a(href: String, init: A.() -> Unit) { val a = initTag(A(), init) a.href = href } } class Body : BodyTag("body") class B : BodyTag("b") class P : BodyTag("p") class H1 : BodyTag("h1") class UL : BodyTag("ul") class LI : BodyTag("li") class A : BodyTag("a") { var href: String get() = attributes["href"]!! set(value) { attributes["href"] = value } } fun HTML.html(init: HTML.() -> Unit): HTML { init() return this } fun html(init: HTML.() -> Unit): HTML { val html = HTML() html.init() return html }
apache-2.0
6c297c50a6995bfe294e4759b42a3a3d
25
128
0.60021
3.614412
false
false
false
false
spinnaker/orca
orca-migration/src/main/kotlin/com/netflix/spinnaker/orca/pipeline/persistence/migration/OrchestrationMigrationAgent.kt
4
3524
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.pipeline.persistence.migration import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionType.ORCHESTRATION import com.netflix.spinnaker.orca.api.pipeline.models.PipelineExecution import com.netflix.spinnaker.orca.front50.Front50Service import com.netflix.spinnaker.orca.notifications.AbstractPollingNotificationAgent import com.netflix.spinnaker.orca.notifications.NotificationClusterLock import com.netflix.spinnaker.orca.pipeline.persistence.DualExecutionRepository import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository import org.slf4j.LoggerFactory /** * Requires DualExecutionRepository being enabled to run migrations. */ class OrchestrationMigrationAgent( clusterLock: NotificationClusterLock, private val front50Service: Front50Service, private val dualExecutionRepository: DualExecutionRepository, private val pollingIntervalMs: Long ) : AbstractPollingNotificationAgent(clusterLock) { private val log = LoggerFactory.getLogger(javaClass) override fun tick() { val previouslyMigratedOrchestrationIds = dualExecutionRepository.primary.retrieveAllExecutionIds(ORCHESTRATION) val executionCriteria = ExecutionRepository.ExecutionCriteria().apply { pageSize = 3500 setStatuses(ExecutionStatus.COMPLETED.map { it.name }) } val allApplications = front50Service.allApplications log.info("Found ${allApplications.size} applications") allApplications.forEachIndexed { index, application -> val applicationName = application.name.toLowerCase() val unmigratedOrchestrations = dualExecutionRepository.previous .retrieveOrchestrationsForApplication(applicationName, executionCriteria) .filter { !previouslyMigratedOrchestrationIds.contains(it.id) } .sorted { t1, t2 -> return@sorted when { t1.getRealStartTime() > t2.getRealStartTime() -> 1 t1.getRealStartTime() < t2.getRealStartTime() -> -1 else -> 0 } } .limit(1000) .toList() .toBlocking() .single() if (unmigratedOrchestrations.isNotEmpty()) { log.info("${unmigratedOrchestrations.size} orchestrations to migrate ($applicationName) [$index/${allApplications.size}]") unmigratedOrchestrations.forEach { dualExecutionRepository.primary.store(it) } log.info("${unmigratedOrchestrations.size} orchestrations migrated ($applicationName) [$index/${allApplications.size}]") } } } private fun PipelineExecution.getRealStartTime(): Long { return if (startTime == null) { if (buildTime == null) Long.MAX_VALUE else buildTime!! } else { startTime!! } } override fun getPollingInterval() = pollingIntervalMs override fun getNotificationType() = "orchestrationMigrator" }
apache-2.0
06f8f673e6e157e3f4c6a43b0723b862
38.155556
130
0.745176
4.570687
false
false
false
false
JavaEden/Orchid-Core
plugins/OrchidTaxonomies/src/main/kotlin/com/eden/orchid/taxonomies/menus/TaxonomyTermMenuType.kt
2
2622
package com.eden.orchid.taxonomies.menus import com.eden.orchid.api.OrchidContext import com.eden.orchid.api.options.annotations.Description import com.eden.orchid.api.options.annotations.IntDefault import com.eden.orchid.api.options.annotations.Option import com.eden.orchid.api.theme.menus.MenuItem import com.eden.orchid.api.theme.menus.OrchidMenuFactory import com.eden.orchid.api.theme.pages.OrchidPage import com.eden.orchid.taxonomies.models.TaxonomiesModel @Description( "Link to a specific Taxonomy Term landing page, optionally with links to its associated pages.", name = "Taxonomy Term" ) class TaxonomyTermMenuType : OrchidMenuFactory("taxonomyTerm") { @Option @Description("The Taxonomy to include terms from.") lateinit var taxonomyType: String @Option @Description("The Term within the Taxonomy to include pages from.") lateinit var termType: String @Option @Description( "Whether to have the menu link out to the Term landing page, or include child menu items with " + "links out to the Term's associated pages." ) var includePages = false @Option @Description( "If `includePages` is true, whether to keep the associated pages as children of a single menu item, " + "or expand them all to the root." ) var pagesAtRoot = false @Option @IntDefault(4) @Description("The maximum number of associated pages to include in this menu item.") var limit: Int = 4 override fun getMenuItems( context: OrchidContext, page: OrchidPage ): List<MenuItem> { val model = context.resolve(TaxonomiesModel::class.java) val taxonomy = model.taxonomies[taxonomyType] val term = taxonomy?.terms?.get(termType) val items = ArrayList<MenuItem>() if (term != null) { if (includePages) { val pageList = if (term.allPages.size > limit) term.allPages.subList(0, limit) else term.allPages if (pagesAtRoot) { pageList.forEach { items.add(MenuItem.Builder(context).page(it).build()) } } else { items.add(MenuItem.Builder(context).title(term.title).pages(pageList).build()) } } else { items.add( MenuItem.Builder(context) .title(term.title) .page(term.archivePages.first()) .build() ) } } return items } }
mit
1ce6f7b427ca8acce032bf6f156c49f7
32.189873
113
0.619756
4.528497
false
false
false
false
SDS-Studios/ScoreKeeper
app/src/main/java/io/github/sdsstudios/ScoreKeeper/Database/AppDatabase.kt
1
2951
package io.github.sdsstudios.ScoreKeeper.Database import android.arch.persistence.room.Database import android.arch.persistence.room.Room import android.arch.persistence.room.RoomDatabase import android.arch.persistence.room.TypeConverters import android.content.Context import io.github.sdsstudios.ScoreKeeper.Database.Dao.GameDao import io.github.sdsstudios.ScoreKeeper.Database.Dao.PlayerDao import io.github.sdsstudios.ScoreKeeper.Database.Dao.ScoresDao import io.github.sdsstudios.ScoreKeeper.Database.Dao.TimeLimitDao import io.github.sdsstudios.ScoreKeeper.Database.TypeConverters.DateConverter import io.github.sdsstudios.ScoreKeeper.Database.TypeConverters.IntListConverter import io.github.sdsstudios.ScoreKeeper.Game.Game import io.github.sdsstudios.ScoreKeeper.Game.Player import io.github.sdsstudios.ScoreKeeper.Game.Scores import io.github.sdsstudios.ScoreKeeper.TimeLimit /** * Created by sethsch1 on 29/10/17. */ /* Database version changelog: * */ @Database(entities = [(Game::class), (Player::class), (TimeLimit::class), (Scores::class)], version = 1) @TypeConverters( DateConverter::class, IntListConverter::class ) abstract class AppDatabase : RoomDatabase() { companion object { private const val DATABASE_NAME = "scorekeeper_db" private var INSTANCE: AppDatabase? = null fun getDatabase(context: Context): AppDatabase { if (INSTANCE == null) { INSTANCE = Room.databaseBuilder(context.applicationContext, AppDatabase::class.java, DATABASE_NAME) .build() } return INSTANCE!! } // // private val MIGRATION_1_2 = object : Migration(1, 2) { // override fun migrate(database: SupportSQLiteDatabase) { // dropColumn(database, GameDao.TABLE_NAME, GameDao.KEY_USE_PLAYER_COLORS) // } // } // // private fun dropColumn(db: SupportSQLiteDatabase, // tableName: String, // columnToDrop: String) { // // val allColumnsCursor = db.query("SELECT * FROM $tableName") // // val columnNames = allColumnsCursor.columnNames.toMutableList() // columnNames.remove(columnToDrop) // // val columnTypes = buildSequence { // for (i in 1..columnNames.size){ // yield(allColumnsCursor.getType(i)) // } // }.toList() // // Log.e(this::class.java.simpleName, columnTypes.toString()) // // val columnsString = columnNames.toString().removePrefix("[").removeSuffix("]") // // db.execSQL("CREATE TABLE $tableName (${columnNames})") // } } abstract fun timeLimitDao(): TimeLimitDao abstract fun gameDao(): GameDao abstract fun scoresDao(): ScoresDao abstract fun playerDao(): PlayerDao }
gpl-3.0
524ec9000553b135c12ab748decce92d
35
92
0.651982
4.519142
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/UnfoldAssignmentToWhenIntention.kt
4
1794
// 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.intentions.branchedTransformations.intentions import com.intellij.codeInsight.intention.LowPriorityAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention import org.jetbrains.kotlin.idea.intentions.branchedTransformations.BranchedUnfoldingUtils import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtBinaryExpression import org.jetbrains.kotlin.psi.KtPsiUtil import org.jetbrains.kotlin.psi.KtWhenExpression import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.startOffset class UnfoldAssignmentToWhenIntention : SelfTargetingRangeIntention<KtBinaryExpression>( KtBinaryExpression::class.java, KotlinBundle.lazyMessage("replace.assignment.with.when.expression") ), LowPriorityAction { override fun applicabilityRange(element: KtBinaryExpression): TextRange? { if (element.operationToken !in KtTokens.ALL_ASSIGNMENTS) return null if (element.left == null) return null val right = element.right as? KtWhenExpression ?: return null if (!KtPsiUtil.checkWhenExpressionHasSingleElse(right)) return null if (right.entries.any { it.expression == null }) return null return TextRange(element.startOffset, right.whenKeyword.endOffset) } override fun applyTo(element: KtBinaryExpression, editor: Editor?) = BranchedUnfoldingUtils.unfoldAssignmentToWhen(element, editor) }
apache-2.0
b704f9fd8869e7047107cffc7d02f160
51.794118
158
0.80379
4.733509
false
false
false
false
google/accompanist
permissions/src/androidTest/java/com/google/accompanist/permissions/FakeTests.kt
1
1363
/* * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.accompanist.permissions import androidx.test.filters.SdkSuppress import org.junit.Test /** * Fake tests to avoid the "No tests found error" when running in Build.VERSION.SDK_INT < 23 */ class FakeTests { @SdkSuppress(maxSdkVersion = 22) @Test fun fakeTestToAvoidNoTestsFoundErrorInAPI22AndBelow() = Unit // More Fake tests to help with sharding: https://github.com/android/android-test/issues/973 @Test fun fake1() = Unit @Test fun fake2() = Unit @Test fun fake3() = Unit @Test fun fake4() = Unit @Test fun fake5() = Unit @Test fun fake6() = Unit @Test fun fake7() = Unit @Test fun fake8() = Unit @Test fun fake9() = Unit }
apache-2.0
11f77a343b0be55c39b0c77f0bc7199a
22.5
96
0.683786
3.872159
false
true
false
false
ktorio/ktor
ktor-server/ktor-server-core/jvm/src/io/ktor/server/config/HoconApplicationConfig.kt
1
3261
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.config import com.typesafe.config.* import io.ktor.server.config.ConfigLoader.Companion.load import java.io.* /** * Loads a [Config] from a hocon file. */ public class HoconConfigLoader : ConfigLoader { /** * Tries loading an application configuration from the specified [path]. * * @return configuration or null if the path is not found or configuration format is not supported. */ override fun load(path: String?): ApplicationConfig? { val resolvedPath = when { path == null -> "application.conf" path.endsWith(".conf") || path.endsWith(".json") || path.endsWith(".properties") -> path else -> return null } val resource = Thread.currentThread().contextClassLoader.getResource(resolvedPath) val config = when { resource != null -> ConfigFactory.load(resolvedPath) else -> { val file = File(resolvedPath) if (file.exists()) ConfigFactory.parseFile(file) else null } }?.resolve() ?: return null return HoconApplicationConfig(config) } } /** * Implements [ApplicationConfig] by loading configuration from HOCON data structures */ public open class HoconApplicationConfig(private val config: Config) : ApplicationConfig { override fun property(path: String): ApplicationConfigValue { if (!config.hasPath(path)) { throw ApplicationConfigurationException("Property $path not found.") } return HoconApplicationConfigValue(config, path) } override fun propertyOrNull(path: String): ApplicationConfigValue? { if (!config.hasPath(path)) { return null } return HoconApplicationConfigValue(config, path) } override fun configList(path: String): List<ApplicationConfig> { return config.getConfigList(path).map { HoconApplicationConfig(it) } } override fun config(path: String): ApplicationConfig = HoconApplicationConfig(config.getConfig(path)) override fun keys(): Set<String> { return config.entrySet().map { it.key }.toSet() } override fun toMap(): Map<String, Any?> { return config.root().unwrapped() } private class HoconApplicationConfigValue(val config: Config, val path: String) : ApplicationConfigValue { override fun getString(): String = config.getString(path) override fun getList(): List<String> = config.getStringList(path) } } /** * Returns a string value for [path] or `null` if missing */ public fun Config.tryGetString(path: String): String? = if (hasPath(path)) getString(path) else null /** * Returns a list of values for [path] or `null` if missing */ public fun Config.tryGetStringList(path: String): List<String>? = if (hasPath(path)) getStringList(path) else null /** * Returns [ApplicationConfig] by loading configuration from a resource specified by [configPath] * or a default resource if [configPath] is `null` */ public fun ApplicationConfig(configPath: String?): ApplicationConfig = ConfigLoader.load(configPath)
apache-2.0
280a5885437c21d829c3346ef695e8c5
33.691489
119
0.673413
4.522885
false
true
false
false